code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<div class="faq">
<div class="window">
<b>Краткая сводка:</b>
<li>Уровень: 60</li>
<li>Зона: Contested</li>
<li>Тип подземелья: <b>Raid (40-man)</b></li>
<li>Location: <a href="?zone=139">Eastern Plaguelands</a></li>
<li>Фракция: <a href="?faction=529">Argent Dawn</a></li>
<li>Последний босс: <a href="?npc=15990">Kel'Thuzad</a></li>
<li>Attunement: <a href="?quest=9122">The Dread Citadel</a></li>
</div>
<h4>Naxxramas</h4>
<B>Naxxramas</B> - это огромный некрополис, парящий в воздухе над <A href="?zone=139">Eastern Plaguelands</A>. Он имеет сомнительную честь служить пристанищем для одного из наиболее могущественных командиров <b>Lich King</b>'а – ужасного <A href="?npc=15990">Kel'Thuzad</A>'а.
<br>
<br>
Данное подземелье предназначено для рейд-группы из 40 человек и разделено на 4 части, которые игрокам предстоит пройти, чтобы попасть в пятую - заключительную - часть под названием <b>Frostwyrm Lair</b>. Прохождение четырех частей может выполняться в любой последовательности.
<br>
<br>
Для получения доступа необходимо отдать некоторое количество материалов в зависимости от уровня вашей репутации у фракции <A href="?faction=529">Argent Dawn</A>. Если ваша репутация находится на уровне <A href="?quest=9123">Exalted</A>, то доступ будет предоставлен вам бесплатно.
<br>
<br>
<h4>История</h4>
<B>Naxxramas</B>, древняя башня, построенная <b>Nerubian</b>'ами, была вырвана из земли помощниками <b>Lich King</b>'а с целью использования в качестве операционного штаба <A href="?npc=15990">Kel'Thuzad</A>'а во время наложения им проклятия на земли <b>Lordaeron</b>'а.
<br>
<br>
В связи с тем, что <A href="?npc=15990">Kel'Thuzad</A> воевал с силами <b>Scarlet Crusade</b>, фракцией <A href="?spell=17350">Argent Dawn</A>, с людьми и нежитью из Альянса, а также постоянно подвергался налетам со стороны искателей приключений всех рас и наций, ежедневно вторгавшихся в контролируемую <b>Scourge</b> часть <b>Plaguelands</b>, его войска были в основном заняты охраной подступов к некрополису. Но сейчас, когда врата <B>Naxxramas</B> открылись, новые солдаты <A href="?npc=15990">Kel'Thuzad</A>'а стали стремительно сметать всех врагов <b>Scourge</b>.
<br>
<br>
<h4>Достойный внимания лут </h4>
Со всех боссов в <B>Naxxramas</B> падают жетоны, используемые для завершения квестов на получение частей брони класса Tier 3. С <A href="?npc=15990">Kel'thuzad</A>'а падает кольцо, являющееся частью комплекта Tier 3 Raid Set.
<br>
<br>
В <B>Naxxramas</B> начинается сбор частей <A href="?s=i&class=2.10&name=Atiesh">[Atiesh, Greatstaff of the Guardian]</A>. Все боссы (кроме <A href="?npc=15990">Kel'thuzad</A>'а и <A href="?npc=15989">Sapphiron</A>'а) в некоторых случаях выбрасывают <A href="?item=22726">[Splinter of Atiesh]</A>. Соединив 40 шт., можно создать <A href="?item=22727">[Frame of Atiesh]</A>, что положит начало квесту, по которому нужно будет поговорить с <A href="?npc=15192">Anachronos</A>. Тот пошлет вас за <A href="?item=22733">[Staff Head of Atiesh]</A> и <A href="?item=22734">[Base of Atiesh]</A>, выбить которые можно из <A href="?npc=15990">Kel'Thuzad</A>'а и <A href="?npc=15727">C'Thun</A>'а, соответственно.
</div>
|
borgotech/Infinity_MaNGOS
|
sql/Tools & Optional/Websites/I_CSwowd/lang/map_ru/533.html
|
HTML
|
gpl-2.0
| 4,512
|
package com.example.myweather2;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class WebServiceUtil {
// 定义 Web Service 的命名空间
static final String SERVICE_NS = "http://WebXml.com.cn/";
// 定义 Web Service 提供服务的URL
static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
// 远程调用 Web Service 获取省份列表
public static List<String> getProvinceList() {
// 调用的方法
final String methodName = "getRegionProvince";
// 创建 HttpTransportSE 传输对象
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
// 使用 SOAP1.1 协议创建 Envelop 对象
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 实例化 SoapObject对象
SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
envelope.bodyOut = soapObject;
// 设置与 .NET 提供的Web Service保存较好的兼容性
envelope.dotNet = true;
FutureTask<List<String>> task = new FutureTask<List<String>>(
new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
// TODO Auto-generated method stub
// 调用web service
ht.call(SERVICE_NS + methodName, envelope);
if (envelope.getResponse() != null) {
// 获取服务器响应返回的SOAP消息
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result
.getProperty(methodName + "Result");
// 解析服务器响应的SOAP消息
return parseProvinceOrCity(detail);
}
return null;
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
// 根据省份获取城市列表
public static List<String> getCityListByProvince(String province) {
// 调用的方法
final String methodName = "getSupportCityString";
// 创建HttpTransportSE传输对象
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
// 添加一个请求参数
soapObject.addProperty("theRegionCode", province);
// 创建Envelop对象
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.bodyOut = soapObject;
envelope.dotNet = true;
FutureTask<List<String>> task = new FutureTask<List<String>>(
new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
// TODO Auto-generated method stub
ht.call(SERVICE_NS + methodName, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result
.getProperty(methodName + "Result");
return parseProvinceOrCity(detail);
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
private static List<String> parseProvinceOrCity(SoapObject detail) {
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < detail.getPropertyCount(); i++) {
// 解析出每个省份或城市
result.add(detail.getProperty(i).toString().split(",")[0]);
}
return result;
}
public static SoapObject getWeatherByCity(String cityName) {
final String methodName = "getWeather";
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
soapObject.addProperty("theCityCode", cityName);
envelope.bodyOut = soapObject;
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
FutureTask<SoapObject> task = new FutureTask<SoapObject>(
new Callable<SoapObject>() {
@Override
public SoapObject call() throws Exception {
// TODO Auto-generated method stub
ht.call(SERVICE_NS + methodName, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result
.getProperty(methodName + "Result");
return detail;
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}
|
treizeor/android-examples
|
疯狂Android讲义/第13章/MyWeather2/src/com/example/myweather2/WebServiceUtil.java
|
Java
|
gpl-2.0
| 4,751
|
/*------------------------------------------------------------------------
* Jastram-Test-Model for Adaptive FD-Grid
*
* Daniel Koehn
* last update 23.10.2004
*
* ---------------------------------------------------------------------*/
#include "fd.h"
void model_elastic(float ** rho, float ** pi, float ** u){
/*--------------------------------------------------------------------------*/
FILE *FP1, *FP2, *FP3;
/* extern variables */
extern float DH;
extern int NX, NY, NXG, NYG, POS[3], MYID;
/* local variables */
float Rho, Vp, Vs, Vpnm1, x, y, undf, r;
float aund, ampund, FW, shiftx;
int i, j, ii, jj;
char modfile[STRING_SIZE];
/* parameters for background */
const float vp2=2000.0, vs2=vp2/sqrt(3.0), rho2=1000.0*0.31*pow(vp2,(1.0/4.0));
/* parameters for sphere 1 and 2 */
const float vp3=1500.0, vs3=vp3/sqrt(3.0), rho3=1000.0*0.31*pow(vp3,(1.0/4.0));
/* location of the spheres */
const float X01 = 80.0;
const float Y01 = 130.0;
/* radii of spheres */
float A0, A1, A3, A4, lambda0, lambda1, lambda3, lambda4;
float y0, y1, y2, y3, y4, y5, undy0, undy1, undy3, undy4;
lambda0=1600.0;
A0=50.0;
y0=1200.0;
lambda1=lambda0/2.0;
A1=100.0;
y1=1000.0;
y2=800.0;
lambda3=lambda0/2.0;
A3=150.0;
y3=600.0;
lambda4=lambda0/2.0;
A4=50.0;
y4=410.0;
y5=100.0;
FP1=fopen("/fastfs/koehn/DENISE_backup/par/start/crase_smooth_model_vp.dat","r");
FP2=fopen("/fastfs/koehn/DENISE_backup/par/start/crase_smooth_model_vs.dat","r");
FP3=fopen("/fastfs/koehn/DENISE_backup/par/start/crase_smooth_model_rho.dat","r");
/* loop over global grid */
for (i=1;i<=NXG;i++){
for (j=1;j<=NYG;j++){
fscanf(FP1,"%e\n",&Vp);
fscanf(FP2,"%e\n",&Vs);
fscanf(FP3,"%e\n",&Rho);
if ((POS[1]==((i-1)/NX)) &&
(POS[2]==((j-1)/NY))){
ii=i-POS[1]*NX;
jj=j-POS[2]*NY;
u[jj][ii]=Vs*Vs*Rho;
rho[jj][ii]=Rho;
pi[jj][ii] = Vp*Vp*Rho - 2.0 * u[jj][ii];
/*if(j==NYG){pi[jj][ii] = pi[jj-1][ii];}*/
}
}
}
/* each PE writes his model to disk */
sprintf(modfile,"model/waveform_test_model_u.bin");
writemod(modfile,u,3);
MPI_Barrier(MPI_COMM_WORLD);
if (MYID==0) mergemod(modfile,3);
sprintf(modfile,"model/waveform_test_model_pi.bin");
writemod(modfile,pi,3);
MPI_Barrier(MPI_COMM_WORLD);
if (MYID==0) mergemod(modfile,3);
sprintf(modfile,"model/waveform_test_model_rho.bin");
writemod(modfile,rho,3);
MPI_Barrier(MPI_COMM_WORLD);
if (MYID==0) mergemod(modfile,3);
fclose(FP1);
fclose(FP2);
fclose(FP3);
}
|
daniel-koehn/DENISE-Black-Edition
|
src/models/waveform_crase_simple_start_smooth.c
|
C
|
gpl-2.0
| 2,851
|
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Cours Sécurité des Réseaux</title>
<meta name="description" content="Cours de téléphonie sur IP avec Asterisk">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="sommaire.html">Cours Sécurité (sommaire)</a>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="col-md-8 col-md-offset-2">
<h2>Attaques de l'extérieur</h2>
<img src="img/attaque_externe.svg" class="img-responsive">
<hr>
<h3>Découverte des ports ouverts et brute force</h3>
<p>La première méthode que l'on rencontre est qu'un attaquant extérieur découvre les ports ouverts sur notre adresse IP publique (avec nmap) par exemple.</p>
<p>L'attaquant utilise ensuite un logiciel de brute force comme Hydra par exemple. Afin de se faciliter la tâche, il peut utiliser des "dictionnaires" de mots de passe téléchargeables sur Internet comme par exemple <a href="https://crackstation.net/buy-crackstation-wordlist-password-cracking-dictionary.htm" target="_blank">https://crackstation.net/buy-crackstation-wordlist-password-cracking-dictionary.htm</a></p>
<code> hydra -t 4 -l root -P petitFichier.txt ssh://www.estem.ma</code>
<hr>
<h3>Deni de Service</h3>
<p>L'autre attaque qui ne vise pas à "pénétrer" dans un réseau mais à interrompre un service est le Deni de Service.</p>
<p>Pour effectuer un DOS il suffit par exemple d'utiliser l'utilitaire hping3 qui va faire des requête SYN jusqu'a saturer la machine distante :</p>
<code>hping3 -S -a y.y.y.y --flood -p 80 x.x.x.x</code>
<p>Ou : </p>
<ul>
<li>y.y.y.y : l'adresse de la machine pour laquelle on veut se faire passer</li>
<li>x.x.x.x : l'adresse de la machine que l'on veut attaquer</li>
</ul>
<hr>
<h3>Utilisation de failles connues</h3>
<p>Les logiciels ont de nombreuses failles de sécurité. Ces failles sont pour la plupart référencées dans <a href="https://cve.mitre.org/" target="_blank">https://cve.mitre.org/</a>.</p>
<p>Des outils comme Metasploit permettent de parcourir une machine à la recherche de faille CVE potientielles.</p>
<hr>
<h2>Attaques de l'intérieur</h2>
<hr>
<h3>Rejouer des captures</h3>
<p>Des outils comme TCPDUMP permettent de capturer le traffic réseau dans un fichier.</p>
<p>Avec la commande <code>tcpdump -i eth0 -s0 -w test.pcap</code> vous allez écrire tout le traffic recu par la carte réseau dans un fichier pcap.</p>
<p>Des outils d'analyse comme ChaosReader permettent d'analyser ces trames et de générer une page HTML résumant ce qui c'est passé durant la session de capture.</p>
<p>Grâce à l'analyse des requêtes POST et GET un attaquant peut rejouer un scénario de connexion à un site Web par exemple.</p>
<p><a class="btn btn-primary btn-lg pull-right" href="mesure-5.html" role="button">Continuer »</a></p>
</div>
</div>
<script src="js/vendor/jquery-1.11.2.min.js"></script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
|
jeremysalmon/coursSecurite
|
mesure-4.html
|
HTML
|
gpl-2.0
| 5,050
|
/*
Miranda NG: the free IM client for Microsoft* Windows*
Copyright (C) 2012-22 Miranda NG team (https://miranda-ng.org),
Copyright (c) 2004-009 Roman Miklashevsky, A. Petkevich, Kosh&chka, persei
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.
*/
#ifndef M_STOPSPAM_H__
#define M_STOPSPAM_H__
#define CS_NOTPASSED 0
#define CS_PASSED 1
//check is contact pass the stopspam
//wParam=(HANDLE)hContact
//lParam=0
//returns a "Contact Stae" flag
#define MS_STOPSPAM_CONTACTPASSED "StopSpam/IsContactPassed"
#endif
|
miranda-ng/miranda-ng
|
plugins/ExternalAPI/m_stopspam.h
|
C
|
gpl-2.0
| 1,191
|
/*
* Kendo UI v2015.2.624 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([ "./kendo.data", "./kendo.popup" ], f);
})(function(){
/*jshint evil: true*/
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.ui,
Widget = ui.Widget,
keys = kendo.keys,
support = kendo.support,
htmlEncode = kendo.htmlEncode,
activeElement = kendo._activeElement,
ObservableArray = kendo.data.ObservableArray,
ID = "id",
LI = "li",
CHANGE = "change",
CHARACTER = "character",
FOCUSED = "k-state-focused",
HOVER = "k-state-hover",
LOADING = "k-loading",
OPEN = "open",
CLOSE = "close",
SELECT = "select",
SELECTED = "selected",
REQUESTSTART = "requestStart",
REQUESTEND = "requestEnd",
WIDTH = "width",
extend = $.extend,
proxy = $.proxy,
isArray = $.isArray,
browser = support.browser,
isIE8 = browser.msie && browser.version < 9,
quotRegExp = /"/g,
alternativeNames = {
"ComboBox": "DropDownList",
"DropDownList": "ComboBox"
};
var List = kendo.ui.DataBoundWidget.extend({
init: function(element, options) {
var that = this,
ns = that.ns,
id;
Widget.fn.init.call(that, element, options);
element = that.element;
options = that.options;
that._isSelect = element.is(SELECT);
if (that._isSelect && that.element[0].length) {
if (!options.dataSource) {
options.dataTextField = options.dataTextField || "text";
options.dataValueField = options.dataValueField || "value";
}
}
that.ul = $('<ul unselectable="on" class="k-list k-reset"/>')
.attr({
tabIndex: -1,
"aria-hidden": true
});
that.list = $("<div class='k-list-container'/>")
.append(that.ul)
.on("mousedown" + ns, proxy(that._listMousedown, that));
id = element.attr(ID);
if (id) {
that.list.attr(ID, id + "-list");
that.ul.attr(ID, id + "_listbox");
}
that._header();
that._accessors();
that._initValue();
},
options: {
valuePrimitive: false,
headerTemplate: ""
},
setOptions: function(options) {
Widget.fn.setOptions.call(this, options);
if (options && options.enable !== undefined) {
options.enabled = options.enable;
}
},
focus: function() {
this._focused.focus();
},
readonly: function(readonly) {
this._editable({
readonly: readonly === undefined ? true : readonly,
disable: false
});
},
enable: function(enable) {
this._editable({
readonly: false,
disable: !(enable = enable === undefined ? true : enable)
});
},
_listOptions: function(options) {
var currentOptions = this.options;
options = options || {};
options = {
height: options.height || currentOptions.height,
dataValueField: options.dataValueField || currentOptions.dataValueField,
dataTextField: options.dataTextField || currentOptions.dataTextField,
groupTemplate: options.groupTemplate || currentOptions.groupTemplate,
fixedGroupTemplate: options.fixedGroupTemplate || currentOptions.fixedGroupTemplate,
template: options.template || currentOptions.template
};
if (!options.template) {
options.template = "#:" + kendo.expr(options.dataTextField, "data") + "#";
}
return options;
},
_initList: function() {
var that = this;
var options = that.options;
var virtual = options.virtual;
var hasVirtual = !!virtual;
var value = options.value;
var listBoundHandler = proxy(that._listBound, that);
var listOptions = {
autoBind: false,
selectable: true,
dataSource: that.dataSource,
click: proxy(that._click, that),
change: proxy(that._listChange, that),
activate: proxy(that._activateItem, that),
deactivate: proxy(that._deactivateItem, that),
dataBinding: function() {
that.trigger("dataBinding");
that._angularItems("cleanup");
},
dataBound: listBoundHandler,
listBound: listBoundHandler,
selectedItemChange: proxy(that._listChange, that)
};
listOptions = $.extend(that._listOptions(), listOptions, typeof virtual === "object" ? virtual : {});
if (!hasVirtual) {
that.listView = new kendo.ui.StaticList(that.ul, listOptions);
} else {
that.listView = new kendo.ui.VirtualList(that.ul, listOptions);
}
if (value !== undefined) {
that.listView.value(value).done(function() {
var text = options.text;
if (!that.listView.filter() && that.input) {
if (that.selectedIndex === -1) {
if (text === undefined || text === null) {
text = value;
}
that._accessor(value);
that.input.val(text);
} else if (that._oldIndex === -1) {
that._oldIndex = that.selectedIndex;
}
}
});
}
},
_listMousedown: function(e) {
if (!this.filterInput || this.filterInput[0] !== e.target) {
e.preventDefault();
}
},
_filterSource: function(filter, force) {
var that = this;
var options = that.options;
var dataSource = that.dataSource;
var expression = extend({}, dataSource.filter() || {});
var removed = removeFiltersForField(expression, options.dataTextField);
if ((filter || removed) && that.trigger("filtering", { filter: filter })) {
return;
}
if (filter) {
expression = expression.filters || [];
expression.push(filter);
}
if (!force) {
dataSource.filter(expression);
} else {
dataSource.read(expression);
}
},
//TODO: refactor
_header: function() {
var that = this;
var template = that.options.headerTemplate;
var header;
if ($.isFunction(template)) {
template = template({});
}
if (template) {
that.list.prepend(template);
header = that.ul.prev();
that.header = header[0] ? header : null;
if (that.header) {
that.angular("compile", function(){
return { elements: that.header };
});
}
}
},
_initValue: function() {
var that = this,
value = that.options.value;
if (value !== null) {
that.element.val(value);
} else {
value = that._accessor();
that.options.value = value;
}
that._old = value;
},
_ignoreCase: function() {
var that = this,
model = that.dataSource.reader.model,
field;
if (model && model.fields) {
field = model.fields[that.options.dataTextField];
if (field && field.type && field.type !== "string") {
that.options.ignoreCase = false;
}
}
},
_focus: function(candidate) {
return this.listView.focus(candidate);
},
current: function(candidate) {
return this._focus(candidate);
},
items: function() {
return this.ul[0].children;
},
destroy: function() {
var that = this;
var ns = that.ns;
Widget.fn.destroy.call(that);
that._unbindDataSource();
that.listView.destroy();
that.list.off(ns);
that.popup.destroy();
if (that._form) {
that._form.off("reset", that._resetHandler);
}
},
dataItem: function(index) {
var that = this;
if (index === undefined) {
return that.listView.selectedDataItems()[0];
}
if (typeof index !== "number") {
index = $(that.items()).index(index);
}
return that.dataSource.flatView()[index];
},
_activateItem: function() {
var current = this.listView.focus();
if (current) {
this._focused.add(this.filterInput).attr("aria-activedescendant", current.attr("id"));
}
},
_deactivateItem: function() {
this._focused.add(this.filterInput).removeAttr("aria-activedescendant");
},
_accessors: function() {
var that = this;
var element = that.element;
var options = that.options;
var getter = kendo.getter;
var textField = element.attr(kendo.attr("text-field"));
var valueField = element.attr(kendo.attr("value-field"));
if (!options.dataTextField && textField) {
options.dataTextField = textField;
}
if (!options.dataValueField && valueField) {
options.dataValueField = valueField;
}
that._text = getter(options.dataTextField);
that._value = getter(options.dataValueField);
},
_aria: function(id) {
var that = this,
options = that.options,
element = that._focused.add(that.filterInput);
if (options.suggest !== undefined) {
element.attr("aria-autocomplete", options.suggest ? "both" : "list");
}
id = id ? id + " " + that.ul[0].id : that.ul[0].id;
element.attr("aria-owns", id);
that.ul.attr("aria-live", !options.filter || options.filter === "none" ? "off" : "polite");
},
_blur: function() {
var that = this;
that._change();
that.close();
},
_change: function() {
var that = this;
var index = that.selectedIndex;
var optionValue = that.options.value;
var value = that.value();
var trigger;
if (that._isSelect && !that.listView.isBound() && optionValue) {
value = optionValue;
}
if (value !== that._old) {
trigger = true;
} else if (index !== undefined && index !== that._oldIndex) {
trigger = true;
}
if (trigger) {
that._old = value;
that._oldIndex = index;
if (!that._typing) {
// trigger the DOM change event so any subscriber gets notified
that.element.trigger(CHANGE);
}
that.trigger(CHANGE);
}
that.typing = false;
},
_data: function() {
return this.dataSource.view();
},
_enable: function() {
var that = this,
options = that.options,
disabled = that.element.is("[disabled]");
if (options.enable !== undefined) {
options.enabled = options.enable;
}
if (!options.enabled || disabled) {
that.enable(false);
} else {
that.readonly(that.element.is("[readonly]"));
}
},
_dataValue: function(dataItem) {
var value = this._value(dataItem);
if (value === undefined) {
value = this._text(dataItem);
}
return value;
},
_offsetHeight: function() {
var offsetHeight = 0;
var siblings = this.listView.content.prevAll(":visible");
siblings.each(function() {
var element = $(this);
if (element.hasClass("k-list-filter")) {
offsetHeight += element.children().outerHeight();
} else {
offsetHeight += element.outerHeight();
}
});
return offsetHeight;
},
_height: function(length) {
var that = this;
var list = that.list;
var height = that.options.height;
var visible = that.popup.visible();
var offsetTop;
var popups;
if (length) {
popups = list.add(list.parent(".k-animation-container")).show();
height = that.listView.content[0].scrollHeight > height ? height : "auto";
popups.height(height);
if (height !== "auto") {
offsetTop = that._offsetHeight();
if (offsetTop) {
height -= offsetTop;
}
}
that.listView.content.height(height);
if (!visible) {
popups.hide();
}
}
return height;
},
_adjustListWidth: function() {
var list = this.list,
width = list[0].style.width,
wrapper = this.wrapper,
computedStyle, computedWidth;
if (!list.data(WIDTH) && width) {
return;
}
computedStyle = window.getComputedStyle ? window.getComputedStyle(wrapper[0], null) : 0;
computedWidth = computedStyle ? parseFloat(computedStyle.width) : wrapper.outerWidth();
if (computedStyle && browser.msie) { // getComputedStyle returns different box in IE.
computedWidth += parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight) + parseFloat(computedStyle.borderLeftWidth) + parseFloat(computedStyle.borderRightWidth);
}
if (list.css("box-sizing") !== "border-box") {
width = computedWidth - (list.outerWidth() - list.width());
} else {
width = computedWidth;
}
list.css({
fontFamily: wrapper.css("font-family"),
width: width
})
.data(WIDTH, width);
return true;
},
_openHandler: function(e) {
this._adjustListWidth();
if (this.trigger(OPEN)) {
e.preventDefault();
} else {
this._focused.attr("aria-expanded", true);
this.ul.attr("aria-hidden", false);
}
},
_closeHandler: function(e) {
if (this.trigger(CLOSE)) {
e.preventDefault();
} else {
this._focused.attr("aria-expanded", false);
this.ul.attr("aria-hidden", true);
}
},
_focusItem: function() {
var listView = this.listView;
var focusedItem = listView.focus();
var index = listView.select();
index = index[index.length - 1];
if (index === undefined && this.options.highlightFirst && !focusedItem) {
index = 0;
}
if (index !== undefined) {
listView.focus(index);
} else {
listView.scrollToIndex(0);
}
},
_calculateGroupPadding: function(height) {
var li = this.ul.children(".k-first:first");
var groupHeader = this.listView.content.prev(".k-group-header");
var padding = 0;
if (groupHeader[0] && groupHeader[0].style.display !== "none") {
if (height !== "auto") {
padding = kendo.support.scrollbar();
}
padding += parseFloat(li.css("border-right-width"), 10) + parseFloat(li.children(".k-group").css("padding-right"), 10);
groupHeader.css("padding-right", padding);
}
},
_firstOpen: function() {
var height = this._height(this.dataSource.flatView().length);
this._calculateGroupPadding(height);
},
_popup: function() {
var that = this;
that.popup = new ui.Popup(that.list, extend({}, that.options.popup, {
anchor: that.wrapper,
open: proxy(that._openHandler, that),
close: proxy(that._closeHandler, that),
animation: that.options.animation,
isRtl: support.isRtl(that.wrapper)
}));
if (!that.options.virtual) {
that.popup.one(OPEN, proxy(that._firstOpen, that));
}
},
_makeUnselectable: function() {
if (isIE8) {
this.list.find("*").not(".k-textbox").attr("unselectable", "on");
}
},
_toggleHover: function(e) {
$(e.currentTarget).toggleClass(HOVER, e.type === "mouseenter");
},
_toggle: function(open, preventFocus) {
var that = this;
var touchEnabled = support.mobileOS && (support.touch || support.MSPointers || support.pointers);
open = open !== undefined? open : !that.popup.visible();
if (!preventFocus && !touchEnabled && that._focused[0] !== activeElement()) {
that._prevent = true;
that._focused.focus();
that._prevent = false;
}
that[open ? OPEN : CLOSE]();
},
_triggerCascade: function() {
var that = this;
if (!that._cascadeTriggered || that._old !== that.value() || that._oldIndex !== that.selectedIndex) {
that._cascadeTriggered = true;
that.trigger("cascade", { userTriggered: that._userTriggered });
}
},
_unbindDataSource: function() {
var that = this;
that.dataSource.unbind(REQUESTSTART, that._requestStartHandler)
.unbind(REQUESTEND, that._requestEndHandler)
.unbind("error", that._errorHandler);
}
});
extend(List, {
inArray: function(node, parentNode) {
var idx, length, siblings = parentNode.children;
if (!node || node.parentNode !== parentNode) {
return -1;
}
for (idx = 0, length = siblings.length; idx < length; idx++) {
if (node === siblings[idx]) {
return idx;
}
}
return -1;
}
});
kendo.ui.List = List;
ui.Select = List.extend({
init: function(element, options) {
List.fn.init.call(this, element, options);
this._initial = this.element.val();
},
setDataSource: function(dataSource) {
var that = this;
var parent;
that.options.dataSource = dataSource;
that._dataSource();
that.listView.setDataSource(that.dataSource);
if (that.options.autoBind) {
that.dataSource.fetch();
}
parent = that._parentWidget();
if (parent) {
parent.trigger("cascade");
}
},
close: function() {
this.popup.close();
},
select: function(candidate) {
var that = this;
if (candidate === undefined) {
return that.selectedIndex;
} else {
that._select(candidate);
that._old = that._accessor();
that._oldIndex = that.selectedIndex;
}
},
search: function(word) {
word = typeof word === "string" ? word : this.text();
var that = this;
var length = word.length;
var options = that.options;
var ignoreCase = options.ignoreCase;
var filter = options.filter;
var field = options.dataTextField;
clearTimeout(that._typingTimeout);
if (!length || length >= options.minLength) {
that._state = "filter";
that.listView.filter(true);
if (filter === "none") {
that._filter(word);
} else {
that._open = true;
that._filterSource({
value: ignoreCase ? word.toLowerCase() : word,
field: field,
operator: filter,
ignoreCase: ignoreCase
});
}
}
},
_accessor: function(value, idx) {
return this[this._isSelect ? "_accessorSelect" : "_accessorInput"](value, idx);
},
_accessorInput: function(value) {
var element = this.element[0];
if (value === undefined) {
return element.value;
} else {
if (value === null) {
value = "";
}
element.value = value;
}
},
_accessorSelect: function(value, idx) {
var element = this.element[0];
var selectedIndex = element.selectedIndex;
var option;
if (value === undefined) {
if (selectedIndex > -1) {
option = element.options[selectedIndex];
}
if (option) {
value = option.value;
}
return value || "";
} else {
if (selectedIndex > -1) {
element.options[selectedIndex].removeAttribute(SELECTED);
}
if (idx === undefined) {
idx = -1;
}
if (value !== null && value !== "" && idx == -1) {
this._custom(value);
} else {
if (value) {
element.value = value;
} else {
element.selectedIndex = idx;
}
if (element.selectedIndex > -1) {
option = element.options[element.selectedIndex];
}
if (option) {
option.setAttribute(SELECTED, SELECTED);
}
}
}
},
_custom: function(value) {
var that = this;
var element = that.element;
var custom = that._customOption;
if (!custom) {
custom = $("<option/>");
that._customOption = custom;
element.append(custom);
}
custom.text(value);
custom[0].setAttribute(SELECTED, SELECTED);
custom[0].selected = true;
},
_hideBusy: function () {
var that = this;
clearTimeout(that._busy);
that._arrow.removeClass(LOADING);
that._focused.attr("aria-busy", false);
that._busy = null;
},
_showBusy: function () {
var that = this;
that._request = true;
if (that._busy) {
return;
}
that._busy = setTimeout(function () {
if (that._arrow) { //destroyed after request start
that._focused.attr("aria-busy", true);
that._arrow.addClass(LOADING);
}
}, 100);
},
_requestEnd: function() {
this._request = false;
this._hideBusy();
},
_dataSource: function() {
var that = this,
element = that.element,
options = that.options,
dataSource = options.dataSource || {},
idx;
dataSource = $.isArray(dataSource) ? {data: dataSource} : dataSource;
if (that._isSelect) {
idx = element[0].selectedIndex;
if (idx > -1) {
options.index = idx;
}
dataSource.select = element;
dataSource.fields = [{ field: options.dataTextField },
{ field: options.dataValueField }];
}
if (that.dataSource) {
that._unbindDataSource();
} else {
that._requestStartHandler = proxy(that._showBusy, that);
that._requestEndHandler = proxy(that._requestEnd, that);
that._errorHandler = proxy(that._hideBusy, that);
}
that.dataSource = kendo.data.DataSource.create(dataSource)
.bind(REQUESTSTART, that._requestStartHandler)
.bind(REQUESTEND, that._requestEndHandler)
.bind("error", that._errorHandler);
},
_firstItem: function() {
this.listView.first();
},
_lastItem: function() {
this.listView.last();
},
_nextItem: function() {
this.listView.next();
},
_prevItem: function() {
this.listView.prev();
},
_move: function(e) {
var that = this;
var key = e.keyCode;
var ul = that.ul[0];
var down = key === keys.DOWN;
var dataItem;
var pressed;
var current;
if (key === keys.UP || down) {
if (e.altKey) {
that.toggle(down);
} else {
if (!that.listView.isBound()) {
if (!that._fetch) {
that.dataSource.one(CHANGE, function() {
that._fetch = false;
that._move(e);
});
that._fetch = true;
that._filterSource();
}
e.preventDefault();
return true; //pressed
}
current = that._focus();
if (!that._fetch && (!current || current.hasClass("k-state-selected"))) {
if (down) {
that._nextItem();
if (!that._focus()) {
that._lastItem();
}
} else {
that._prevItem();
if (!that._focus()) {
that._firstItem();
}
}
}
if (that.trigger(SELECT, { item: that.listView.focus() })) {
that._focus(current);
return;
}
that._select(that._focus(), true);
if (!that.popup.visible()) {
that._blur();
}
}
e.preventDefault();
pressed = true;
} else if (key === keys.ENTER || key === keys.TAB) {
if (that.popup.visible()) {
e.preventDefault();
}
current = that._focus();
dataItem = that.dataItem();
if (!that.popup.visible() && (!dataItem || that.text() !== that._text(dataItem))) {
current = null;
}
var activeFilter = that.filterInput && that.filterInput[0] === activeElement();
if (current) {
if (that.trigger(SELECT, { item: current })) {
return;
}
that._select(current);
} else if (that.input) {
that._accessor(that.input.val());
that.listView.value(that.input.val());
}
if (that._focusElement) {
that._focusElement(that.wrapper);
}
if (activeFilter && key === keys.TAB) {
that.wrapper.focusout();
} else {
that._blur();
}
that.close();
pressed = true;
} else if (key === keys.ESC) {
if (that.popup.visible()) {
e.preventDefault();
}
that.close();
pressed = true;
}
return pressed;
},
_fetchData: function() {
var that = this;
var hasItems = !!that.dataSource.view().length;
if (that._request || that.options.cascadeFrom) {
return;
}
if (!that.listView.isBound() && !that._fetch && !hasItems) {
that._fetch = true;
that.dataSource.fetch().done(function() {
that._fetch = false;
});
}
},
_options: function(data, optionLabel, value) {
var that = this,
element = that.element,
length = data.length,
options = "",
option,
dataItem,
dataText,
dataValue,
idx = 0;
if (optionLabel) {
options = optionLabel;
}
for (; idx < length; idx++) {
option = "<option";
dataItem = data[idx];
dataText = that._text(dataItem);
dataValue = that._value(dataItem);
if (dataValue !== undefined) {
dataValue += "";
if (dataValue.indexOf('"') !== -1) {
dataValue = dataValue.replace(quotRegExp, """);
}
option += ' value="' + dataValue + '"';
}
option += ">";
if (dataText !== undefined) {
option += htmlEncode(dataText);
}
option += "</option>";
options += option;
}
element.html(options);
if (value !== undefined) {
element[0].value = value;
}
},
_reset: function() {
var that = this,
element = that.element,
formId = element.attr("form"),
form = formId ? $("#" + formId) : element.closest("form");
if (form[0]) {
that._resetHandler = function() {
setTimeout(function() {
that.value(that._initial);
});
};
that._form = form.on("reset", that._resetHandler);
}
},
_parentWidget: function() {
var name = this.options.name;
var parentElement = $("#" + this.options.cascadeFrom);
var parent = parentElement.data("kendo" + name);
if (!parent) {
parent = parentElement.data("kendo" + alternativeNames[name]);
}
return parent;
},
_cascade: function() {
var that = this,
options = that.options,
cascade = options.cascadeFrom,
select, valueField,
parent, change;
if (cascade) {
parent = that._parentWidget();
if (!parent) {
return;
}
options.autoBind = false;
valueField = options.cascadeFromField || parent.options.dataValueField;
change = function() {
that.dataSource.unbind(CHANGE, change);
var value = that._accessor();
if (that._userTriggered) {
that._clearSelection(parent, true);
} else if (value) {
if (value !== that.listView.value()[0]) {
that.value(value);
}
if (!that.dataSource.view()[0] || that.selectedIndex === -1) {
that._clearSelection(parent, true);
}
} else if (that.dataSource.flatView().length) {
that.select(options.index);
}
that.enable();
that._triggerCascade();
that._userTriggered = false;
};
select = function() {
var dataItem = parent.dataItem(),
filterValue = dataItem ? parent._value(dataItem) : null,
expressions, filters;
if (filterValue || filterValue === 0) {
expressions = that.dataSource.filter() || {};
removeFiltersForField(expressions, valueField);
filters = expressions.filters || [];
filters.push({
field: valueField,
operator: "eq",
value: filterValue
});
var handler = function() {
that.unbind("dataBound", handler);
change.apply(that, arguments);
};
that.first("dataBound", handler);
that.dataSource.filter(filters);
} else {
that.enable(false);
that._clearSelection(parent);
that._triggerCascade();
that._userTriggered = false;
}
};
parent.first("cascade", function(e) {
that._userTriggered = e.userTriggered;
select();
});
//refresh was called
if (parent.listView.isBound()) {
select();
} else if (!parent.value()) {
that.enable(false);
}
}
}
});
var STATIC_LIST_NS = ".StaticList";
var StaticList = kendo.ui.DataBoundWidget.extend({
init: function(element, options) {
Widget.fn.init.call(this, element, options);
this.element.attr("role", "listbox")
.on("click" + STATIC_LIST_NS, "li", proxy(this._click, this))
.on("mouseenter" + STATIC_LIST_NS, "li", function() { $(this).addClass(HOVER); })
.on("mouseleave" + STATIC_LIST_NS, "li", function() { $(this).removeClass(HOVER); });
this.content = this.element
.wrap("<div unselectable='on'></div>")
.parent()
.css({
"overflow": "auto",
"position": "relative"
});
this.header = this.content.before('<div class="k-group-header" style="display:none"></div>').prev();
this._bound = false;
this._optionID = kendo.guid();
this._selectedIndices = [];
this._view = [];
this._dataItems = [];
this._values = [];
var value = this.options.value;
if (value) {
this._values = $.isArray(value) ? value.slice(0) : [value];
}
this._getter();
this._templates();
this.setDataSource(this.options.dataSource);
this._onScroll = proxy(function() {
var that = this;
clearTimeout(that._scrollId);
that._scrollId = setTimeout(function() {
that._renderHeader();
}, 50);
}, this);
},
options: {
name: "StaticList",
dataValueField: null,
selectable: true,
template: null,
groupTemplate: null,
fixedGroupTemplate: null
},
events: [
"click",
"change",
"activate",
"deactivate",
"dataBinding",
"dataBound",
"selectedItemChange"
],
setDataSource: function(source) {
var that = this;
var dataSource = source || {};
var value;
dataSource = $.isArray(dataSource) ? { data: dataSource } : dataSource;
dataSource = kendo.data.DataSource.create(dataSource);
if (that.dataSource) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
value = that.value();
that.value([]);
that._bound = false;
that.value(value);
} else {
that._refreshHandler = proxy(that.refresh, that);
}
that.dataSource = dataSource.bind(CHANGE, that._refreshHandler);
that._fixedHeader();
},
setOptions: function(options) {
Widget.fn.setOptions.call(this, options);
this._getter();
this._templates();
this._render();
},
destroy: function() {
this.element.off(STATIC_LIST_NS);
if (this._refreshHandler) {
this.dataSource.unbind(CHANGE, this._refreshHandler);
}
Widget.fn.destroy.call(this);
},
scrollToIndex: function(index) {
var item = this.element[0].children[index];
if (item) {
this.scroll(item);
}
},
scroll: function (item) {
if (!item) {
return;
}
if (item[0]) {
item = item[0];
}
var content = this.content[0],
itemOffsetTop = item.offsetTop,
itemOffsetHeight = item.offsetHeight,
contentScrollTop = content.scrollTop,
contentOffsetHeight = content.clientHeight,
bottomDistance = itemOffsetTop + itemOffsetHeight,
yDimension, offsetHeight;
if (contentScrollTop > itemOffsetTop) {
contentScrollTop = itemOffsetTop;
} else if (bottomDistance > (contentScrollTop + contentOffsetHeight)) {
contentScrollTop = (bottomDistance - contentOffsetHeight);
}
content.scrollTop = contentScrollTop;
},
selectedDataItems: function(dataItems) {
var getter = this._valueGetter;
if (dataItems === undefined) {
return this._dataItems.slice();
}
this._dataItems = dataItems;
this._values = $.map(dataItems, function(dataItem) {
return getter(dataItem);
});
},
next: function() {
var current = this.focus();
if (!current) {
current = 0;
} else {
current = current.next();
}
this.focus(current);
},
prev: function() {
var current = this.focus();
if (!current) {
current = this.element[0].children.length - 1;
} else {
current = current.prev();
}
this.focus(current);
},
first: function() {
this.focus(this.element[0].children[0]);
},
last: function() {
this.focus(this.element[0].children[this.element[0].children.length - 1]);
},
focus: function(candidate) {
var that = this;
var id = that._optionID;
var hasCandidate;
if (candidate === undefined) {
return that._current;
}
candidate = that._get(candidate);
candidate = candidate[candidate.length - 1];
candidate = $(this.element[0].children[candidate]);
if (that._current) {
that._current
.removeClass(FOCUSED)
.removeAttr("aria-selected")
.removeAttr(ID);
that.trigger("deactivate");
}
hasCandidate = !!candidate[0];
if (hasCandidate) {
candidate.addClass(FOCUSED);
that.scroll(candidate);
candidate.attr("id", id);
}
that._current = hasCandidate ? candidate : null;
that.trigger("activate");
},
focusIndex: function() {
return this.focus() ? this.focus().index() : undefined;
},
filter: function(filter, skipValueUpdate) {
if (filter === undefined) {
return this._filtered;
}
this._filtered = filter;
},
skipUpdate: function(skipUpdate) {
this._skipUpdate = skipUpdate;
},
select: function(indices) {
var that = this;
var selectable = that.options.selectable;
var singleSelection = selectable !== "multiple" && selectable !== false;
var selectedIndices = that._selectedIndices;
var added = [];
var removed = [];
var result;
if (indices === undefined) {
return selectedIndices.slice();
}
indices = that._get(indices);
if (indices.length === 1 && indices[0] === -1) {
indices = [];
}
if (that._filtered && !singleSelection && that._deselectFiltered(indices)) {
return;
}
if (singleSelection && !that._filtered && $.inArray(indices[indices.length - 1], selectedIndices) !== -1) {
if (that._dataItems.length && that._view.length) {
that._dataItems = [that._view[selectedIndices[0]].item];
}
return;
}
result = that._deselect(indices);
removed = result.removed;
indices = result.indices;
if (indices.length) {
if (singleSelection) {
indices = [indices[indices.length - 1]];
}
added = that._select(indices);
}
if (added.length || removed.length) {
that._valueComparer = null;
that.trigger("change", {
added: added,
removed: removed
});
}
},
removeAt: function(position) {
this._selectedIndices.splice(position, 1);
this._values.splice(position, 1);
return {
position: position,
dataItem: this._dataItems.splice(position, 1)[0]
};
},
setValue: function(value) {
value = $.isArray(value) || value instanceof ObservableArray ? value.slice(0) : [value];
this._values = value;
this._valueComparer = null;
},
value: function(value) {
var that = this;
var deferred = that._valueDeferred;
var indices;
if (value === undefined) {
return that._values.slice();
}
that.setValue(value);
if (!deferred || deferred.state() === "resolved") {
that._valueDeferred = deferred = $.Deferred();
}
if (that.isBound()) {
indices = that._valueIndices(that._values);
if (that.options.selectable === "multiple") {
that.select(-1);
}
that.select(indices);
deferred.resolve();
}
that._skipUpdate = false;
return deferred;
},
_click: function(e) {
if (!e.isDefaultPrevented()) {
this.trigger("click", { item: $(e.currentTarget) });
}
},
_valueExpr: function(type, values) {
var that = this;
var value;
var idx = 0;
var body;
var comparer;
var normalized = [];
if (!that._valueComparer || that._valueType !== type) {
that._valueType = type;
for (; idx < values.length; idx++) {
value = values[idx];
if (value !== undefined && value !== "" && value !== null) {
if (type === "boolean") {
value = Boolean(value);
} else if (type === "number") {
value = Number(value);
} else if (type === "string") {
value = value.toString();
}
}
normalized.push(value);
}
body = "for (var idx = 0; idx < " + normalized.length + "; idx++) {" +
" if (current === values[idx]) {" +
" return idx;" +
" }" +
"} " +
"return -1;";
comparer = new Function(["current", "values"], body);
that._valueComparer = function(current) {
return comparer(current, normalized);
};
}
return that._valueComparer;
},
_dataItemPosition: function(dataItem, values) {
var value = this._valueGetter(dataItem);
var valueExpr = this._valueExpr(typeof value, values);
return valueExpr(value);
},
_getter: function() {
this._valueGetter = kendo.getter(this.options.dataValueField);
},
_deselect: function(indices) {
var that = this;
var children = that.element[0].children;
var selectable = that.options.selectable;
var selectedIndices = that._selectedIndices;
var dataItems = that._dataItems;
var values = that._values;
var removed = [];
var i = 0;
var j;
var index, selectedIndex;
var removedIndices = 0;
indices = indices.slice();
if (selectable === true || !indices.length) {
for (; i < selectedIndices.length; i++) {
$(children[selectedIndices[i]]).removeClass("k-state-selected");
removed.push({
position: i,
dataItem: dataItems[i]
});
}
that._values = [];
that._dataItems = [];
that._selectedIndices = [];
} else if (selectable === "multiple") {
for (; i < indices.length; i++) {
index = indices[i];
if (!$(children[index]).hasClass("k-state-selected")) {
continue;
}
for (j = 0; j < selectedIndices.length; j++) {
selectedIndex = selectedIndices[j];
if (selectedIndex === index) {
$(children[selectedIndex]).removeClass("k-state-selected");
removed.push({
position: j + removedIndices,
dataItem: dataItems.splice(j, 1)[0]
});
selectedIndices.splice(j, 1);
indices.splice(i, 1);
values.splice(j, 1);
removedIndices += 1;
i -= 1;
j -= 1;
break;
}
}
}
}
return {
indices: indices,
removed: removed
};
},
_deselectFiltered: function(indices) {
var children = this.element[0].children;
var dataItem, index, position;
var removed = [];
var idx = 0;
for (; idx < indices.length; idx++) {
index = indices[idx];
dataItem = this._view[index].item;
position = this._dataItemPosition(dataItem, this._values);
if (position > -1) {
removed.push(this.removeAt(position));
$(children[index]).removeClass("k-state-selected");
}
}
if (removed.length) {
this.trigger("change", {
added: [],
removed: removed
});
return true;
}
return false;
},
_select: function(indices) {
var that = this;
var children = that.element[0].children;
var data = that._view;
var dataItem, index;
var added = [];
var idx = 0;
if (indices[indices.length - 1] !== -1) {
that.focus(indices);
}
for (; idx < indices.length; idx++) {
index = indices[idx];
dataItem = data[index];
if (index === -1 || !dataItem) {
continue;
}
dataItem = dataItem.item;
that._selectedIndices.push(index);
that._dataItems.push(dataItem);
that._values.push(that._valueGetter(dataItem));
$(children[index]).addClass("k-state-selected").attr("aria-selected", true);
added.push({
dataItem: dataItem
});
}
return added;
},
_get: function(candidate) {
if (typeof candidate === "number") {
candidate = [candidate];
} else if (!isArray(candidate)) {
candidate = $(candidate).data("offset-index");
if (candidate === undefined) {
candidate = -1;
}
candidate = [candidate];
}
return candidate;
},
_template: function() {
var that = this;
var options = that.options;
var template = options.template;
if (!template) {
template = kendo.template('<li tabindex="-1" role="option" unselectable="on" class="k-item">${' + kendo.expr(options.dataTextField, "data") + "}</li>", { useWithBlock: false });
} else {
template = kendo.template(template);
template = function(data) {
return '<li tabindex="-1" role="option" unselectable="on" class="k-item">' + template(data) + "</li>";
};
}
return template;
},
_templates: function() {
var template;
var templates = {
template: this.options.template,
groupTemplate: this.options.groupTemplate,
fixedGroupTemplate: this.options.fixedGroupTemplate
};
for (var key in templates) {
template = templates[key];
if (template && typeof template !== "function") {
templates[key] = kendo.template(template);
}
}
this.templates = templates;
},
_normalizeIndices: function(indices) {
var newIndices = [];
var idx = 0;
for (; idx < indices.length; idx++) {
if (indices[idx] !== undefined) {
newIndices.push(indices[idx]);
}
}
return newIndices;
},
_valueIndices: function(values, indices) {
var data = this._view;
var idx = 0;
var index;
indices = indices ? indices.slice() : [];
if (!values.length) {
return [];
}
for (; idx < data.length; idx++) {
index = this._dataItemPosition(data[idx].item, values);
if (index !== -1) {
indices[index] = idx;
}
}
return this._normalizeIndices(indices);
},
_firstVisibleItem: function() {
var element = this.element[0];
var content = this.content[0];
var scrollTop = content.scrollTop;
var itemHeight = $(element.children[0]).height();
var itemIndex = Math.floor(scrollTop / itemHeight) || 0;
var item = element.children[itemIndex] || element.lastChild;
var forward = item.offsetTop < scrollTop;
while (item) {
if (forward) {
if ((item.offsetTop + itemHeight) > scrollTop || !item.nextSibling) {
break;
}
item = item.nextSibling;
} else {
if (item.offsetTop <= scrollTop || !item.previousSibling) {
break;
}
item = item.previousSibling;
}
}
return this._view[$(item).data("offset-index")];
},
_fixedHeader: function() {
if (this.isGrouped() && this.templates.fixedGroupTemplate) {
this.header.show();
this.content.scroll(this._onScroll);
} else {
this.header.hide();
this.content.off("scroll", this._onScroll);
}
},
_renderHeader: function() {
var template = this.templates.fixedGroupTemplate;
if (!template) {
return;
}
var visibleItem = this._firstVisibleItem();
if (visibleItem) {
this.header.html(template(visibleItem.group));
}
},
_renderItem: function(context) {
var item = '<li tabindex="-1" role="option" unselectable="on" class="k-item';
var dataItem = context.item;
var notFirstItem = context.index !== 0;
var selected = context.selected;
if (notFirstItem && context.newGroup) {
item += ' k-first';
}
if (selected) {
item += ' k-state-selected';
}
item += '"' + (selected ? ' aria-selected="true"' : "") + ' data-offset-index="' + context.index + '">';
item += this.templates.template(dataItem);
if (notFirstItem && context.newGroup) {
item += '<div class="k-group">' + this.templates.groupTemplate(context.group) + '</div>';
}
return item + "</li>";
},
_render: function() {
var html = "";
var i = 0;
var idx = 0;
var context;
var dataContext = [];
var view = this.dataSource.view();
var values = this.value();
var group, newGroup, j;
var isGrouped = this.isGrouped();
if (isGrouped) {
for (i = 0; i < view.length; i++) {
group = view[i];
newGroup = true;
for (j = 0; j < group.items.length; j++) {
context = {
selected: this._selected(group.items[j], values),
item: group.items[j],
group: group.value,
newGroup: newGroup,
index: idx };
dataContext[idx] = context;
idx += 1;
html += this._renderItem(context);
newGroup = false;
}
}
} else {
for (i = 0; i < view.length; i++) {
context = { selected: this._selected(view[i], values), item: view[i], index: i };
dataContext[i] = context;
html += this._renderItem(context);
}
}
this._view = dataContext;
this.element[0].innerHTML = html;
if (isGrouped && dataContext.length) {
this._renderHeader();
}
},
_selected: function(dataItem, values) {
var select = !this._filtered || this.options.selectable === "multiple";
return select && this._dataItemPosition(dataItem, values) !== -1;
},
refresh: function(e) {
var that = this;
var changedItems;
var action = e && e.action;
that.trigger("dataBinding");
that._fixedHeader();
that._render();
that._bound = true;
if (action === "itemchange") {
changedItems = findChangedItems(that._dataItems, e.items);
if (changedItems.length) {
that.trigger("selectedItemChange", {
items: changedItems
});
}
} else if (that._filtered || that._skipUpdate) {
that.focus(0);
if (that._skipUpdate) {
that._skipUpdate = false;
that._selectedIndices = that._valueIndices(that._values, that._selectedIndices);
}
} else if (!action || action === "add") {
that.value(that._values);
}
if (that._valueDeferred) {
that._valueDeferred.resolve();
}
that.trigger("dataBound");
},
isBound: function() {
return this._bound;
},
isGrouped: function() {
return (this.dataSource.group() || []).length;
}
});
ui.plugin(StaticList);
function findChangedItems(selected, changed) {
var changedLength = changed.length;
var result = [];
var dataItem;
var i, j;
for (i = 0; i < selected.length; i++) {
dataItem = selected[i];
for (j = 0; j < changedLength; j++) {
if (dataItem === changed[j]) {
result.push({
index: i,
item: dataItem
});
}
}
}
return result;
}
function removeFiltersForField(expression, field) {
var filters;
var found = false;
if (expression.filters) {
filters = $.grep(expression.filters, function(filter) {
found = removeFiltersForField(filter, field);
if (filter.filters) {
return filter.filters.length;
} else {
return filter.field != field;
}
});
if (!found && expression.filters.length !== filters.length) {
found = true;
}
expression.filters = filters;
}
return found;
}
})(window.kendo.jQuery);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
cuongnd/test_pro
|
media/Kendo_UI_Professional_Q2_2015/src/js/kendo.list.js
|
JavaScript
|
gpl-2.0
| 62,024
|
# Copyright (C) 2013-2015 Red Hat, Inc.
# Copyright (C) 2015 Thomas Spura
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
from dnfpluginscore import _, logger
import dnf
import dnf.cli
import dnf.exceptions
import dnf.i18n
import dnf.subject
import dnfpluginscore
import hawkey
import itertools
import os
import shutil
import copy
import glob
import subprocess
import sys
class BuildLocal(dnf.Plugin):
name = 'buildlocal'
def __init__(self, base, cli):
super(BuildLocal, self).__init__(base, cli)
self.base = base
self.cli = cli
if self.cli is not None:
self.cli.register_command(BuildLocalCommand)
#class BuildLocalCommand(dnf.cli.Command):
class BuildLocalCommand(dnf.cli.Command):
aliases = ['buildlocal']
summary = _('Locally build and install package')
usage = _('PACKAGE...')
def __init__(self, cli):
super(BuildLocalCommand, self).__init__(cli)
self.opts = None
self.parser = None
def configure(self, args):
# setup sack and populate it with enabled repos
demands = self.cli.demands
demands.sack_activation = True
demands.available_repos = True
def run(self, args):
"""Execute the util action here."""
# Setup ArgumentParser to handle util
# You must only add options not used by dnf already
self.parser = dnfpluginscore.ArgumentParser(self.aliases[0])
self.parser.add_argument('packages', nargs='+',
help=_('packages to install'))
self.parser.add_argument("--source", #action='store_true',
help=_('download the src.rpm instead'))
self.parser.add_argument(
'--destdir',
help=_('download path, default is current dir'))
self.parser.add_argument(
'--resolve', action='store_true',
help=_('resolve and download needed dependencies'))
# parse the options/args
# list available options/args on errors & exit
self.opts = self.parser.parse_args(args)
# show util help & exit
if self.opts.help_cmd:
print(self.parser.format_help())
return
locations = self._download_source(self.opts.packages)
pkgs = copy.deepcopy(self.opts.packages)
for loc in locations:
ret = subprocess.call(["mock", loc])
if ret != 0:
print("Building failed. Aborting...")
sys.exit(1)
# Install possible packages before continuing
g = glob.glob("/var/lib/mock/fedora-*/result/*[0-9]*.rpm")
print("FILES IN GLOB", g)
# save to cache
# inspect what to install and collect full list while shrinking pkgs
print(locations)
assert len(pkgs) == 0, "Not all packages were correctly installed %s"% pkgs
# do the install
return
if self.opts.source:
locations = self._download_source(self.opts.packages)
else:
locations = self._download_rpms(self.opts.packages)
if self.opts.destdir:
dest = self.opts.destdir
else:
dest = dnf.i18n.ucd(os.getcwd())
self._move_packages(dest, locations)
def _download_rpms(self, pkg_specs):
"""Download packages to dnf cache."""
if self.opts.resolve:
pkgs = self._get_packages_with_deps(pkg_specs)
else:
pkgs = self._get_packages(pkg_specs)
self.base.download_packages(pkgs, self.base.output.progress)
locations = sorted([pkg.localPkg() for pkg in pkgs])
return locations
def _download_source(self, pkg_specs):
"""Download source packages to dnf cache."""
pkgs = self._get_packages(pkg_specs)
source_pkgs = self._get_source_packages(pkgs)
self._enable_source_repos()
pkgs = self._get_packages(source_pkgs, source=True)
self.base.download_packages(pkgs, self.base.output.progress)
locations = sorted([pkg.localPkg() for pkg in pkgs])
return locations
def _get_packages(self, pkg_specs, source=False):
"""Get packages matching pkg_specs."""
if source:
queries = map(self._get_query_source, pkg_specs)
else:
queries = map(self._get_query, pkg_specs)
pkgs = list(itertools.chain(*queries))
return pkgs
def _get_packages_with_deps(self, pkg_specs, source=False):
"""Get packages matching pkg_specs and the deps."""
pkgs = self._get_packages(pkg_specs)
goal = hawkey.Goal(self.base.sack)
for pkg in pkgs:
goal.install(pkg)
rc = goal.run()
if rc:
pkgs = goal.list_installs()
return pkgs
else:
logger.debug(_('Error in resolve'))
return []
@staticmethod
def _get_source_packages(pkgs):
"""Get list of source rpm names for a list of packages."""
source_pkgs = set()
for pkg in pkgs:
if pkg.sourcerpm:
source_pkgs.add(pkg.sourcerpm)
logger.debug(' --> Package : %s Source : %s',
str(pkg), pkg.sourcerpm)
elif pkg.arch == 'src':
source_pkgs.add("%s-%s.src.rpm" % (pkg.name, pkg.evr))
else:
logger.info(_("No source rpm defined for %s"), str(pkg))
return list(source_pkgs)
def _enable_source_repos(self):
"""Enable source repositories for enabled binary repositories.
Don't disable the binary ones because they can contain SRPMs as well
(this applies to COPR and to user-managed repos).
The dnf sack will be reloaded.
"""
# enable the source repos
for repo in self.base.repos.iter_enabled():
source_repo_id = '%s-source' % repo.id
if source_repo_id in self.base.repos:
source_repo = self.base.repos[source_repo_id]
logger.info(_('enabled %s repository'), source_repo.id)
source_repo.enable()
# reload the sack
self.base.fill_sack()
def _get_query(self, pkg_spec):
"""Return a query to match a pkg_spec."""
subj = dnf.subject.Subject(pkg_spec)
q = subj.get_best_query(self.base.sack)
q = q.available()
q = q.latest()
return q
def _get_query_source(self, pkg_spec):
""""Return a query to match a source rpm file name."""
pkg_spec = pkg_spec[:-4] # skip the .rpm
nevra = hawkey.split_nevra(pkg_spec)
q = self.base.sack.query()
q = q.available()
q = q.latest()
q = q.filter(name=nevra.name, version=nevra.version,
release=nevra.release, arch=nevra.arch)
return q
@staticmethod
def _move_packages(target, locations):
"""Move the downloaded package to target."""
if not os.path.exists(target):
os.makedirs(target)
for pkg in locations:
shutil.copy(pkg, target)
os.unlink(pkg)
return target
|
tomspur/dnf-plugins-buildlocal
|
buildlocal.py
|
Python
|
gpl-2.0
| 8,142
|
/* 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.
*/
/*
* IPC ROUTER SMD XPRT module.
*/
#define DEBUG
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/of.h>
#include <linux/ipc_router_xprt.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <soc/qcom/smd.h>
#include <soc/qcom/smsm.h>
#include <soc/qcom/subsystem_restart.h>
static int msm_ipc_router_smd_xprt_debug_mask;
module_param_named(debug_mask, msm_ipc_router_smd_xprt_debug_mask,
int, S_IRUGO | S_IWUSR | S_IWGRP);
#if defined(DEBUG)
#define D(x...) do { \
if (msm_ipc_router_smd_xprt_debug_mask) \
pr_info(x); \
} while (0)
#else
#define D(x...) do { } while (0)
#endif
#define MIN_FRAG_SZ (IPC_ROUTER_HDR_SIZE + sizeof(union rr_control_msg))
#define NUM_SMD_XPRTS 4
#define XPRT_NAME_LEN (SMD_MAX_CH_NAME_LEN + 12)
/**
* msm_ipc_router_smd_xprt - IPC Router's SMD XPRT structure
* @list: IPC router's SMD XPRTs list.
* @ch_name: Name of the HSIC endpoint exported by ipc_bridge driver.
* @xprt_name: Name of the XPRT to be registered with IPC Router.
* @edge: SMD channel edge.
* @driver: Platform drivers register by this XPRT.
* @xprt: IPC Router XPRT structure to contain XPRT specific info.
* @channel: SMD channel specific info.
* @smd_xprt_wq: Workqueue to queue read & other XPRT related works.
* @write_avail_wait_q: wait queue for writer thread.
* @in_pkt: Pointer to any partially read packet.
* @is_partial_in_pkt: check pkt completion.
* @read_work: Read Work to perform read operation from SMD.
* @ss_reset_lock: Lock to protect access to the ss_reset flag.
* @ss_reset: flag used to check SSR state.
* @pil: handle to the remote subsystem.
* @sft_close_complete: Variable to indicate completion of SSR handling
* by IPC Router.
* @xprt_version: IPC Router header version supported by this XPRT.
* @xprt_option: XPRT specific options to be handled by IPC Router.
* @disable_pil_loading: Disable PIL Loading of the subsystem.
*/
struct msm_ipc_router_smd_xprt {
struct list_head list;
char ch_name[SMD_MAX_CH_NAME_LEN];
char xprt_name[XPRT_NAME_LEN];
uint32_t edge;
struct platform_driver driver;
struct msm_ipc_router_xprt xprt;
smd_channel_t *channel;
struct workqueue_struct *smd_xprt_wq;
wait_queue_head_t write_avail_wait_q;
struct rr_packet *in_pkt;
int is_partial_in_pkt;
struct delayed_work read_work;
spinlock_t ss_reset_lock; /*Subsystem reset lock*/
int ss_reset;
void *pil;
struct completion sft_close_complete;
unsigned xprt_version;
unsigned xprt_option;
bool disable_pil_loading;
};
struct msm_ipc_router_smd_xprt_work {
struct msm_ipc_router_xprt *xprt;
struct work_struct work;
};
static void smd_xprt_read_data(struct work_struct *work);
static void smd_xprt_open_event(struct work_struct *work);
static void smd_xprt_close_event(struct work_struct *work);
/**
* msm_ipc_router_smd_xprt_config - Config. Info. of each SMD XPRT
* @ch_name: Name of the SMD endpoint exported by SMD driver.
* @xprt_name: Name of the XPRT to be registered with IPC Router.
* @edge: ID to differentiate among multiple SMD endpoints.
* @link_id: Network Cluster ID to which this XPRT belongs to.
* @xprt_version: IPC Router header version supported by this XPRT.
* @disable_pil_loading: Disable PIL Loading of the subsystem.
*/
struct msm_ipc_router_smd_xprt_config {
char ch_name[SMD_MAX_CH_NAME_LEN];
char xprt_name[XPRT_NAME_LEN];
uint32_t edge;
uint32_t link_id;
unsigned xprt_version;
unsigned xprt_option;
bool disable_pil_loading;
};
struct msm_ipc_router_smd_xprt_config smd_xprt_cfg[] = {
{"RPCRPY_CNTL", "ipc_rtr_smd_rpcrpy_cntl", SMD_APPS_MODEM, 1, 1},
{"IPCRTR", "ipc_rtr_smd_ipcrtr", SMD_APPS_MODEM, 1, 1},
{"IPCRTR", "ipc_rtr_q6_ipcrtr", SMD_APPS_QDSP, 1, 1},
{"IPCRTR", "ipc_rtr_wcnss_ipcrtr", SMD_APPS_WCNSS, 1, 1},
};
#define MODULE_NAME "ipc_router_smd_xprt"
#define IPC_ROUTER_SMD_XPRT_WAIT_TIMEOUT 3000
static int ipc_router_smd_xprt_probe_done;
static struct delayed_work ipc_router_smd_xprt_probe_work;
static DEFINE_MUTEX(smd_remote_xprt_list_lock_lha1);
static LIST_HEAD(smd_remote_xprt_list);
static void pil_vote_load_worker(struct work_struct *work);
static void pil_vote_unload_worker(struct work_struct *work);
static struct workqueue_struct *pil_vote_wq;
static bool is_pil_loading_disabled(uint32_t edge);
static int msm_ipc_router_smd_get_xprt_version(
struct msm_ipc_router_xprt *xprt)
{
struct msm_ipc_router_smd_xprt *smd_xprtp;
if (!xprt)
return -EINVAL;
smd_xprtp = container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
return (int)smd_xprtp->xprt_version;
}
static int msm_ipc_router_smd_get_xprt_option(
struct msm_ipc_router_xprt *xprt)
{
struct msm_ipc_router_smd_xprt *smd_xprtp;
if (!xprt)
return -EINVAL;
smd_xprtp = container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
return (int)smd_xprtp->xprt_option;
}
static int msm_ipc_router_smd_remote_write_avail(
struct msm_ipc_router_xprt *xprt)
{
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
return smd_write_avail(smd_xprtp->channel);
}
static int msm_ipc_router_smd_remote_write(void *data,
uint32_t len,
struct msm_ipc_router_xprt *xprt)
{
struct rr_packet *pkt = (struct rr_packet *)data;
struct sk_buff *ipc_rtr_pkt;
int offset, sz_written = 0;
int ret, num_retries = 0;
unsigned long flags;
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
if (!pkt)
return -EINVAL;
if (!len || pkt->length != len)
return -EINVAL;
while ((ret = smd_write_start(smd_xprtp->channel, len)) < 0) {
spin_lock_irqsave(&smd_xprtp->ss_reset_lock, flags);
if (smd_xprtp->ss_reset) {
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock,
flags);
IPC_RTR_ERR("%s: %s chnl reset\n",
__func__, xprt->name);
return -ENETRESET;
}
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock, flags);
if (num_retries >= 5) {
IPC_RTR_ERR("%s: Error %d @smd_write_start for %s\n",
__func__, ret, xprt->name);
return ret;
}
msleep(50);
num_retries++;
}
D("%s: Ready to write %d bytes\n", __func__, len);
skb_queue_walk(pkt->pkt_fragment_q, ipc_rtr_pkt) {
offset = 0;
while (offset < ipc_rtr_pkt->len) {
if (!smd_write_segment_avail(smd_xprtp->channel))
smd_enable_read_intr(smd_xprtp->channel);
wait_event(smd_xprtp->write_avail_wait_q,
(smd_write_segment_avail(smd_xprtp->channel) ||
smd_xprtp->ss_reset));
smd_disable_read_intr(smd_xprtp->channel);
spin_lock_irqsave(&smd_xprtp->ss_reset_lock, flags);
if (smd_xprtp->ss_reset) {
spin_unlock_irqrestore(
&smd_xprtp->ss_reset_lock, flags);
IPC_RTR_ERR("%s: %s chnl reset\n",
__func__, xprt->name);
return -ENETRESET;
}
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock,
flags);
sz_written = smd_write_segment(smd_xprtp->channel,
ipc_rtr_pkt->data + offset,
(ipc_rtr_pkt->len - offset), 0);
offset += sz_written;
sz_written = 0;
}
D("%s: Wrote %d bytes over %s\n",
__func__, offset, xprt->name);
}
if (!smd_write_end(smd_xprtp->channel))
D("%s: Finished writing\n", __func__);
return len;
}
static int msm_ipc_router_smd_remote_close(struct msm_ipc_router_xprt *xprt)
{
int rc;
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
rc = smd_close(smd_xprtp->channel);
if (smd_xprtp->pil) {
subsystem_put(smd_xprtp->pil);
smd_xprtp->pil = NULL;
}
return rc;
}
static void smd_xprt_sft_close_done(struct msm_ipc_router_xprt *xprt)
{
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt, struct msm_ipc_router_smd_xprt, xprt);
complete_all(&smd_xprtp->sft_close_complete);
}
static void smd_xprt_read_data(struct work_struct *work)
{
int pkt_size, sz_read, sz;
struct sk_buff *ipc_rtr_pkt;
void *data;
unsigned long flags;
struct delayed_work *rwork = to_delayed_work(work);
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(rwork, struct msm_ipc_router_smd_xprt, read_work);
spin_lock_irqsave(&smd_xprtp->ss_reset_lock, flags);
if (smd_xprtp->ss_reset) {
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock, flags);
if (smd_xprtp->in_pkt)
release_pkt(smd_xprtp->in_pkt);
smd_xprtp->is_partial_in_pkt = 0;
IPC_RTR_ERR("%s: %s channel reset\n",
__func__, smd_xprtp->xprt.name);
return;
}
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock, flags);
D("%s pkt_size: %d, read_avail: %d\n", __func__,
smd_cur_packet_size(smd_xprtp->channel),
smd_read_avail(smd_xprtp->channel));
while ((pkt_size = smd_cur_packet_size(smd_xprtp->channel)) &&
smd_read_avail(smd_xprtp->channel)) {
if (!smd_xprtp->is_partial_in_pkt) {
smd_xprtp->in_pkt = create_pkt(NULL);
if (!smd_xprtp->in_pkt) {
IPC_RTR_ERR("%s: Couldn't alloc rr_packet\n",
__func__);
return;
}
smd_xprtp->is_partial_in_pkt = 1;
D("%s: Allocated rr_packet\n", __func__);
}
if (((pkt_size >= MIN_FRAG_SZ) &&
(smd_read_avail(smd_xprtp->channel) < MIN_FRAG_SZ)) ||
((pkt_size < MIN_FRAG_SZ) &&
(smd_read_avail(smd_xprtp->channel) < pkt_size)))
return;
sz = smd_read_avail(smd_xprtp->channel);
do {
ipc_rtr_pkt = alloc_skb(sz, GFP_KERNEL);
if (!ipc_rtr_pkt) {
if (sz <= (PAGE_SIZE/2)) {
queue_delayed_work(
smd_xprtp->smd_xprt_wq,
&smd_xprtp->read_work,
msecs_to_jiffies(100));
return;
}
sz = sz / 2;
}
} while (!ipc_rtr_pkt);
D("%s: Allocated the sk_buff of size %d\n", __func__, sz);
data = skb_put(ipc_rtr_pkt, sz);
sz_read = smd_read(smd_xprtp->channel, data, sz);
if (sz_read != sz) {
IPC_RTR_ERR("%s: Couldn't read %s completely\n",
__func__, smd_xprtp->xprt.name);
kfree_skb(ipc_rtr_pkt);
release_pkt(smd_xprtp->in_pkt);
smd_xprtp->is_partial_in_pkt = 0;
return;
}
skb_queue_tail(smd_xprtp->in_pkt->pkt_fragment_q, ipc_rtr_pkt);
smd_xprtp->in_pkt->length += sz_read;
if (sz_read != pkt_size)
smd_xprtp->is_partial_in_pkt = 1;
else
smd_xprtp->is_partial_in_pkt = 0;
if (!smd_xprtp->is_partial_in_pkt) {
D("%s: Packet size read %d\n",
__func__, smd_xprtp->in_pkt->length);
msm_ipc_router_xprt_notify(&smd_xprtp->xprt,
IPC_ROUTER_XPRT_EVENT_DATA,
(void *)smd_xprtp->in_pkt);
release_pkt(smd_xprtp->in_pkt);
smd_xprtp->in_pkt = NULL;
}
}
}
static void smd_xprt_open_event(struct work_struct *work)
{
struct msm_ipc_router_smd_xprt_work *xprt_work =
container_of(work, struct msm_ipc_router_smd_xprt_work, work);
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt_work->xprt,
struct msm_ipc_router_smd_xprt, xprt);
unsigned long flags;
spin_lock_irqsave(&smd_xprtp->ss_reset_lock, flags);
smd_xprtp->ss_reset = 0;
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock, flags);
msm_ipc_router_xprt_notify(xprt_work->xprt,
IPC_ROUTER_XPRT_EVENT_OPEN, NULL);
D("%s: Notified IPC Router of %s OPEN\n",
__func__, xprt_work->xprt->name);
kfree(xprt_work);
}
static void smd_xprt_close_event(struct work_struct *work)
{
struct msm_ipc_router_smd_xprt_work *xprt_work =
container_of(work, struct msm_ipc_router_smd_xprt_work, work);
struct msm_ipc_router_smd_xprt *smd_xprtp =
container_of(xprt_work->xprt,
struct msm_ipc_router_smd_xprt, xprt);
init_completion(&smd_xprtp->sft_close_complete);
msm_ipc_router_xprt_notify(xprt_work->xprt,
IPC_ROUTER_XPRT_EVENT_CLOSE, NULL);
D("%s: Notified IPC Router of %s CLOSE\n",
__func__, xprt_work->xprt->name);
wait_for_completion(&smd_xprtp->sft_close_complete);
kfree(xprt_work);
}
static void msm_ipc_router_smd_remote_notify(void *_dev, unsigned event)
{
unsigned long flags;
struct msm_ipc_router_smd_xprt *smd_xprtp;
struct msm_ipc_router_smd_xprt_work *xprt_work;
smd_xprtp = (struct msm_ipc_router_smd_xprt *)_dev;
if (!smd_xprtp)
return;
switch (event) {
case SMD_EVENT_DATA:
if (smd_read_avail(smd_xprtp->channel))
queue_delayed_work(smd_xprtp->smd_xprt_wq,
&smd_xprtp->read_work, 0);
if (smd_write_segment_avail(smd_xprtp->channel))
wake_up(&smd_xprtp->write_avail_wait_q);
break;
case SMD_EVENT_OPEN:
xprt_work = kmalloc(sizeof(struct msm_ipc_router_smd_xprt_work),
GFP_ATOMIC);
if (!xprt_work) {
IPC_RTR_ERR(
"%s: Couldn't notify %d event to IPC Router\n",
__func__, event);
return;
}
xprt_work->xprt = &smd_xprtp->xprt;
INIT_WORK(&xprt_work->work, smd_xprt_open_event);
queue_work(smd_xprtp->smd_xprt_wq, &xprt_work->work);
break;
case SMD_EVENT_CLOSE:
spin_lock_irqsave(&smd_xprtp->ss_reset_lock, flags);
smd_xprtp->ss_reset = 1;
spin_unlock_irqrestore(&smd_xprtp->ss_reset_lock, flags);
wake_up(&smd_xprtp->write_avail_wait_q);
xprt_work = kmalloc(sizeof(struct msm_ipc_router_smd_xprt_work),
GFP_ATOMIC);
if (!xprt_work) {
IPC_RTR_ERR(
"%s: Couldn't notify %d event to IPC Router\n",
__func__, event);
return;
}
xprt_work->xprt = &smd_xprtp->xprt;
INIT_WORK(&xprt_work->work, smd_xprt_close_event);
queue_work(smd_xprtp->smd_xprt_wq, &xprt_work->work);
break;
}
}
static void *msm_ipc_load_subsystem(uint32_t edge)
{
void *pil = NULL;
const char *peripheral;
bool loading_disabled;
loading_disabled = is_pil_loading_disabled(edge);
peripheral = smd_edge_to_pil_str(edge);
if (!IS_ERR_OR_NULL(peripheral) && !loading_disabled) {
pil = subsystem_get(peripheral);
if (IS_ERR(pil)) {
IPC_RTR_ERR("%s: Failed to load %s\n",
__func__, peripheral);
pil = NULL;
}
}
return pil;
}
/**
* find_smd_xprt_list() - Find xprt item specific to an HSIC endpoint
* @pdev: Platform device registered by HSIC's ipc_bridge driver
*
* @return: pointer to msm_ipc_router_smd_xprt if matching endpoint is found,
* else NULL.
*
* This function is used to find specific xprt item from the global xprt list
*/
static struct msm_ipc_router_smd_xprt *
find_smd_xprt_list(struct platform_device *pdev)
{
struct msm_ipc_router_smd_xprt *smd_xprtp;
mutex_lock(&smd_remote_xprt_list_lock_lha1);
list_for_each_entry(smd_xprtp, &smd_remote_xprt_list, list) {
if (!strcmp(pdev->name, smd_xprtp->ch_name)
&& (pdev->id == smd_xprtp->edge)) {
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
return smd_xprtp;
}
}
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
return NULL;
}
/**
* is_pil_loading_disabled() - Check if pil loading a subsystem is disabled
* @edge: Edge that points to the remote subsystem.
*
* @return: true if disabled, false if enabled.
*/
static bool is_pil_loading_disabled(uint32_t edge)
{
struct msm_ipc_router_smd_xprt *smd_xprtp;
mutex_lock(&smd_remote_xprt_list_lock_lha1);
list_for_each_entry(smd_xprtp, &smd_remote_xprt_list, list) {
if (smd_xprtp->edge == edge) {
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
return smd_xprtp->disable_pil_loading;
}
}
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
return true;
}
/**
* msm_ipc_router_smd_remote_probe() - Probe an SMD endpoint
*
* @pdev: Platform device corresponding to SMD endpoint.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called when the underlying SMD driver registers
* a platform device, mapped to SMD endpoint.
*/
static int msm_ipc_router_smd_remote_probe(struct platform_device *pdev)
{
int rc;
struct msm_ipc_router_smd_xprt *smd_xprtp;
smd_xprtp = find_smd_xprt_list(pdev);
if (!smd_xprtp) {
IPC_RTR_ERR("%s No device with name %s\n",
__func__, pdev->name);
return -EPROBE_DEFER;
}
if (strcmp(pdev->name, smd_xprtp->ch_name)
|| (pdev->id != smd_xprtp->edge)) {
IPC_RTR_ERR("%s wrong item name:%s edge:%d\n",
__func__, smd_xprtp->ch_name, smd_xprtp->edge);
return -ENODEV;
}
smd_xprtp->smd_xprt_wq =
create_singlethread_workqueue(pdev->name);
if (!smd_xprtp->smd_xprt_wq) {
IPC_RTR_ERR("%s: WQ creation failed for %s\n",
__func__, pdev->name);
return -EFAULT;
}
smd_xprtp->pil = msm_ipc_load_subsystem(
smd_xprtp->edge);
rc = smd_named_open_on_edge(smd_xprtp->ch_name,
smd_xprtp->edge,
&smd_xprtp->channel,
smd_xprtp,
msm_ipc_router_smd_remote_notify);
if (rc < 0) {
IPC_RTR_ERR("%s: Channel open failed for %s\n",
__func__, smd_xprtp->ch_name);
if (smd_xprtp->pil) {
subsystem_put(smd_xprtp->pil);
smd_xprtp->pil = NULL;
}
destroy_workqueue(smd_xprtp->smd_xprt_wq);
return rc;
}
smd_disable_read_intr(smd_xprtp->channel);
smsm_change_state(SMSM_APPS_STATE, 0, SMSM_RPCINIT);
return 0;
}
struct pil_vote_info {
void *pil_handle;
struct work_struct load_work;
struct work_struct unload_work;
};
/**
* pil_vote_load_worker() - Process vote to load the modem
*
* @work: Work item to process
*
* This function is called to process votes to load the modem that have been
* queued by msm_ipc_load_default_node().
*/
static void pil_vote_load_worker(struct work_struct *work)
{
const char *peripheral;
struct pil_vote_info *vote_info;
bool loading_disabled;
vote_info = container_of(work, struct pil_vote_info, load_work);
peripheral = smd_edge_to_pil_str(SMD_APPS_MODEM);
loading_disabled = is_pil_loading_disabled(SMD_APPS_MODEM);
if (!IS_ERR_OR_NULL(peripheral) && !strcmp(peripheral, "modem") &&
!loading_disabled) {
vote_info->pil_handle = subsystem_get(peripheral);
if (IS_ERR(vote_info->pil_handle)) {
IPC_RTR_ERR("%s: Failed to load %s\n",
__func__, peripheral);
vote_info->pil_handle = NULL;
}
} else {
vote_info->pil_handle = NULL;
}
}
/**
* pil_vote_unload_worker() - Process vote to unload the modem
*
* @work: Work item to process
*
* This function is called to process votes to unload the modem that have been
* queued by msm_ipc_unload_default_node().
*/
static void pil_vote_unload_worker(struct work_struct *work)
{
struct pil_vote_info *vote_info;
vote_info = container_of(work, struct pil_vote_info, unload_work);
if (vote_info->pil_handle) {
subsystem_put(vote_info->pil_handle);
vote_info->pil_handle = NULL;
}
kfree(vote_info);
}
/**
* msm_ipc_load_default_node() - Queue a vote to load the modem.
*
* @return: PIL vote info structure on success, NULL on failure.
*
* This function places a work item that loads the modem on the
* single-threaded workqueue used for processing PIL votes to load
* or unload the modem.
*/
void *msm_ipc_load_default_node(void)
{
struct pil_vote_info *vote_info;
vote_info = kmalloc(sizeof(struct pil_vote_info), GFP_KERNEL);
if (vote_info == NULL) {
pr_err("%s: mem alloc for pil_vote_info failed\n", __func__);
return NULL;
}
INIT_WORK(&vote_info->load_work, pil_vote_load_worker);
queue_work(pil_vote_wq, &vote_info->load_work);
return vote_info;
}
EXPORT_SYMBOL(msm_ipc_load_default_node);
/**
* msm_ipc_unload_default_node() - Queue a vote to unload the modem.
*
* @pil_vote: PIL vote info structure, containing the PIL handle
* and work structure.
*
* This function places a work item that unloads the modem on the
* single-threaded workqueue used for processing PIL votes to load
* or unload the modem.
*/
void msm_ipc_unload_default_node(void *pil_vote)
{
struct pil_vote_info *vote_info;
if (pil_vote) {
vote_info = (struct pil_vote_info *) pil_vote;
INIT_WORK(&vote_info->unload_work, pil_vote_unload_worker);
queue_work(pil_vote_wq, &vote_info->unload_work);
}
}
EXPORT_SYMBOL(msm_ipc_unload_default_node);
/**
* msm_ipc_router_smd_driver_register() - register SMD XPRT drivers
*
* @smd_xprtp: pointer to Ipc router smd xprt structure.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called when a new XPRT is added to register platform
* drivers for new XPRT.
*/
static int msm_ipc_router_smd_driver_register(
struct msm_ipc_router_smd_xprt *smd_xprtp)
{
int ret;
struct msm_ipc_router_smd_xprt *item;
unsigned already_registered = 0;
mutex_lock(&smd_remote_xprt_list_lock_lha1);
list_for_each_entry(item, &smd_remote_xprt_list, list) {
if (!strcmp(smd_xprtp->ch_name, item->ch_name))
already_registered = 1;
}
list_add(&smd_xprtp->list, &smd_remote_xprt_list);
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
if (!already_registered) {
smd_xprtp->driver.driver.name = smd_xprtp->ch_name;
smd_xprtp->driver.driver.owner = THIS_MODULE;
smd_xprtp->driver.probe = msm_ipc_router_smd_remote_probe;
ret = platform_driver_register(&smd_xprtp->driver);
if (ret) {
IPC_RTR_ERR(
"%s: Failed to register platform driver [%s]\n",
__func__, smd_xprtp->ch_name);
return ret;
}
} else {
IPC_RTR_ERR("%s Already driver registered %s\n",
__func__, smd_xprtp->ch_name);
}
return 0;
}
/**
* msm_ipc_router_smd_config_init() - init SMD xprt configs
*
* @smd_xprt_config: pointer to SMD xprt configurations.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called to initialize the SMD XPRT pointer with
* the SMD XPRT configurations either from device tree or static arrays.
*/
static int msm_ipc_router_smd_config_init(
struct msm_ipc_router_smd_xprt_config *smd_xprt_config)
{
struct msm_ipc_router_smd_xprt *smd_xprtp;
smd_xprtp = kzalloc(sizeof(struct msm_ipc_router_smd_xprt), GFP_KERNEL);
if (IS_ERR_OR_NULL(smd_xprtp)) {
IPC_RTR_ERR("%s: kzalloc() failed for smd_xprtp id:%s\n",
__func__, smd_xprt_config->ch_name);
return -ENOMEM;
}
smd_xprtp->xprt.link_id = smd_xprt_config->link_id;
smd_xprtp->xprt_version = smd_xprt_config->xprt_version;
smd_xprtp->edge = smd_xprt_config->edge;
smd_xprtp->xprt_option = smd_xprt_config->xprt_option;
smd_xprtp->disable_pil_loading = smd_xprt_config->disable_pil_loading;
strlcpy(smd_xprtp->ch_name, smd_xprt_config->ch_name,
SMD_MAX_CH_NAME_LEN);
strlcpy(smd_xprtp->xprt_name, smd_xprt_config->xprt_name,
XPRT_NAME_LEN);
smd_xprtp->xprt.name = smd_xprtp->xprt_name;
smd_xprtp->xprt.get_version =
msm_ipc_router_smd_get_xprt_version;
smd_xprtp->xprt.get_option =
msm_ipc_router_smd_get_xprt_option;
smd_xprtp->xprt.read_avail = NULL;
smd_xprtp->xprt.read = NULL;
smd_xprtp->xprt.write_avail =
msm_ipc_router_smd_remote_write_avail;
smd_xprtp->xprt.write = msm_ipc_router_smd_remote_write;
smd_xprtp->xprt.close = msm_ipc_router_smd_remote_close;
smd_xprtp->xprt.sft_close_done = smd_xprt_sft_close_done;
smd_xprtp->xprt.priv = NULL;
init_waitqueue_head(&smd_xprtp->write_avail_wait_q);
smd_xprtp->in_pkt = NULL;
smd_xprtp->is_partial_in_pkt = 0;
INIT_DELAYED_WORK(&smd_xprtp->read_work, smd_xprt_read_data);
spin_lock_init(&smd_xprtp->ss_reset_lock);
smd_xprtp->ss_reset = 0;
msm_ipc_router_smd_driver_register(smd_xprtp);
return 0;
}
/**
* parse_devicetree() - parse device tree binding
*
* @node: pointer to device tree node
* @smd_xprt_config: pointer to SMD XPRT configurations
*
* @return: 0 on success, -ENODEV on failure.
*/
static int parse_devicetree(struct device_node *node,
struct msm_ipc_router_smd_xprt_config *smd_xprt_config)
{
int ret;
int edge;
int link_id;
int version;
char *key;
const char *ch_name;
const char *remote_ss;
key = "qcom,ch-name";
ch_name = of_get_property(node, key, NULL);
if (!ch_name)
goto error;
strlcpy(smd_xprt_config->ch_name, ch_name, SMD_MAX_CH_NAME_LEN);
key = "qcom,xprt-remote";
remote_ss = of_get_property(node, key, NULL);
if (!remote_ss)
goto error;
edge = smd_remote_ss_to_edge(remote_ss);
if (edge < 0)
goto error;
smd_xprt_config->edge = edge;
key = "qcom,xprt-linkid";
ret = of_property_read_u32(node, key, &link_id);
if (ret)
goto error;
smd_xprt_config->link_id = link_id;
key = "qcom,xprt-version";
ret = of_property_read_u32(node, key, &version);
if (ret)
goto error;
smd_xprt_config->xprt_version = version;
key = "qcom,fragmented-data";
smd_xprt_config->xprt_option = of_property_read_bool(node, key);
key = "qcom,disable-pil-loading";
smd_xprt_config->disable_pil_loading = of_property_read_bool(node, key);
scnprintf(smd_xprt_config->xprt_name, XPRT_NAME_LEN, "%s_%s",
remote_ss, smd_xprt_config->ch_name);
return 0;
error:
IPC_RTR_ERR("%s: missing key: %s\n", __func__, key);
return -ENODEV;
}
/**
* msm_ipc_router_smd_xprt_probe() - Probe an SMD xprt
*
* @pdev: Platform device corresponding to SMD xprt.
*
* @return: 0 on success, standard Linux error codes on error.
*
* This function is called when the underlying device tree driver registers
* a platform device, mapped to an SMD transport.
*/
static int msm_ipc_router_smd_xprt_probe(struct platform_device *pdev)
{
int ret;
struct msm_ipc_router_smd_xprt_config smd_xprt_config;
if (pdev) {
if (pdev->dev.of_node) {
mutex_lock(&smd_remote_xprt_list_lock_lha1);
ipc_router_smd_xprt_probe_done = 1;
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
ret = parse_devicetree(pdev->dev.of_node,
&smd_xprt_config);
if (ret) {
IPC_RTR_ERR("%s: Failed to parse device tree\n",
__func__);
return ret;
}
ret = msm_ipc_router_smd_config_init(&smd_xprt_config);
if (ret) {
IPC_RTR_ERR("%s init failed\n", __func__);
return ret;
}
}
}
return 0;
}
/**
* ipc_router_smd_xprt_probe_worker() - probe worker for non DT configurations
*
* @work: work item to process
*
* This function is called by schedule_delay_work after 3sec and check if
* device tree probe is done or not. If device tree probe fails the default
* configurations read from static array.
*/
static void ipc_router_smd_xprt_probe_worker(struct work_struct *work)
{
int i, ret;
BUG_ON(ARRAY_SIZE(smd_xprt_cfg) != NUM_SMD_XPRTS);
mutex_lock(&smd_remote_xprt_list_lock_lha1);
if (!ipc_router_smd_xprt_probe_done) {
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
for (i = 0; i < ARRAY_SIZE(smd_xprt_cfg); i++) {
ret = msm_ipc_router_smd_config_init(&smd_xprt_cfg[i]);
if (ret)
IPC_RTR_ERR(" %s init failed config idx %d\n",
__func__, i);
}
mutex_lock(&smd_remote_xprt_list_lock_lha1);
}
mutex_unlock(&smd_remote_xprt_list_lock_lha1);
}
static struct of_device_id msm_ipc_router_smd_xprt_match_table[] = {
{ .compatible = "qcom,ipc_router_smd_xprt" },
{},
};
static struct platform_driver msm_ipc_router_smd_xprt_driver = {
.probe = msm_ipc_router_smd_xprt_probe,
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table = msm_ipc_router_smd_xprt_match_table,
},
};
static int __init msm_ipc_router_smd_xprt_init(void)
{
int rc;
rc = platform_driver_register(&msm_ipc_router_smd_xprt_driver);
if (rc) {
IPC_RTR_ERR(
"%s: msm_ipc_router_smd_xprt_driver register failed %d\n",
__func__, rc);
return rc;
}
pil_vote_wq = create_singlethread_workqueue("pil_vote_wq");
if (IS_ERR_OR_NULL(pil_vote_wq)) {
pr_err("%s: create_singlethread_workqueue failed\n", __func__);
return -EFAULT;
}
INIT_DELAYED_WORK(&ipc_router_smd_xprt_probe_work,
ipc_router_smd_xprt_probe_worker);
schedule_delayed_work(&ipc_router_smd_xprt_probe_work,
msecs_to_jiffies(IPC_ROUTER_SMD_XPRT_WAIT_TIMEOUT));
return 0;
}
module_init(msm_ipc_router_smd_xprt_init);
MODULE_DESCRIPTION("IPC Router SMD XPRT");
MODULE_LICENSE("GPL v2");
|
ipaccess/fsm99xx-kernel-sources
|
drivers/soc/qcom/ipc_router_smd_xprt.c
|
C
|
gpl-2.0
| 27,768
|
from testscenarios import TestWithScenarios
import unittest
from geocode.geocode import GeoCodeAccessAPI
class GeoCodeTests(TestWithScenarios, unittest.TestCase):
scenarios = [
(
"Scenario - 1: Get latlng from address",
{
'address': "Sydney NSW",
'latlng': (-33.8674869, 151.2069902),
'method': "geocode",
}
),
(
"Scenario - 2: Get address from latlng",
{
'address': "Sydney NSW",
'latlng': (-33.8674869, 151.2069902),
'method': "address",
}
),
]
def setUp(self):
self.api = GeoCodeAccessAPI()
def test_geocode(self):
if self.method == 'geocode':
expected_address = self.address
expected_lat = self.latlng[0]
expected_lng = self.latlng[1]
geocode = self.api.get_geocode(expected_address)
self.assertAlmostEqual(geocode.lat, expected_lat, delta=5)
self.assertAlmostEqual(geocode.lng, expected_lng, delta=5)
self.assertIn(expected_address, geocode.address)
else:
expected_address = self.address
expected_lat = self.latlng[0]
expected_lng = self.latlng[1]
address = self.api.get_address(lat=expected_lat, lng=expected_lng)
self.assertIn(expected_address, address)
def tearDown(self):
pass
if __name__ == "__main__":
unittest.main()
|
saleem-latif/GeoCode
|
tests/unittest_geocode.py
|
Python
|
gpl-2.0
| 1,541
|
body {
/**background-color: #000;*/
/**background-image: url(img/eg_bg_04.gif);*/
/**color: #fff;*/
}
.center{
margin-left: auto;
margin-right: auto;
}
.element {
width: 120px;
height: 160px;
box-shadow: 0px 0px 12px rgba(0,255,255,0.5);
border: 1px solid rgba(127,255,255,0.25);
text-align: center;
cursor: default;
}
.element:hover {
box-shadow: 0px 0px 12px rgba(0,255,255,0.75);
border: 1px solid rgba(127,255,255,0.75);
}
.element .number {
position: absolute;
top: 20px;
right: 20px;
font-size: 12px;
color: rgba(127,255,255,0.75);
}
.element .symbol {
position: absolute;
top: 40px;
left: 0px;
right: 0px;
font-size: 60px;
font-weight: bold;
color: rgba(255,255,255,0.75);
text-shadow: 0 0 10px rgba(0,255,255,0.95);
}
.element .details {
position: absolute;
bottom: 15px;
left: 0px;
right: 0px;
font-size: 12px;
color: rgba(127,255,255,0.75);
}
.button {
color: rgba(127,255,255,0.75);
background: transparent;
outline: 1px solid rgba(127,255,255,0.75);
border: 0px;
padding: 5px 10px;
cursor: pointer;
}
.button:hover {
background-color: rgba(0,255,255,0.5);
}
.button:active {
color: #000000;
background-color: rgba(0,255,255,0.75);
}
|
bigbubble/bigbubble.github.io
|
css/index.css
|
CSS
|
gpl-2.0
| 1,188
|
/* Copyright (C) 1993-2013 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <unistd.h>
#include <hurd.h>
#include <hurd/id.h>
/* Get the real user ID of the calling process. */
uid_t
__getuid ()
{
error_t err;
uid_t uid;
HURD_CRITICAL_BEGIN;
__mutex_lock (&_hurd_id.lock);
if (err = _hurd_check_ids ())
{
errno = err;
uid = -1;
}
else if (_hurd_id.aux.nuids >= 1)
uid = _hurd_id.aux.uids[0];
else
{
/* We do not even have a real uid. */
errno = EGRATUITOUS;
uid = -1;
}
__mutex_unlock (&_hurd_id.lock);
HURD_CRITICAL_END;
return uid;
}
weak_alias (__getuid, getuid)
|
czankel/xtensa-glibc
|
sysdeps/mach/hurd/getuid.c
|
C
|
gpl-2.0
| 1,385
|
<?php namespace XoopsModules\Jobs;
/**
* Jobs for XOOPS
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
* 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.
*
* @copyright {@link https://xoops.org/ XOOPS Project}
* @license {@link http://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later}
* @package jobs
* @author XOOPS Development Team
*/
use Xmf\Request;
use XoopsModules\Jobs;
use XoopsModules\Jobs\Common;
/**
* Class Utility
*/
class Utility
{
use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
use Common\ServerStats; // getServerStats Trait
use Common\FilesManagement; // Files Management Trait
//--------------- Custom module methods -----------------------------
}
|
mambax7/jobs
|
class/Utility.php
|
PHP
|
gpl-2.0
| 1,068
|
#!/usr/bin/ruby
require './shotfunc.rb'
require './playerplay.rb'
require './defenseplay.rb'
require './savestats.rb'
require './engine.rb'
require 'pg'
jornada = [9,1,2]
begin
db=PGconn.connect( :hostaddr=>"127.0.0.1", :port=>5432, :dbname=>"manager_development", :user=>"testuser", :password=>"testpw")
partidos = db.exec("SELECT id,hometeam_id,awayteam_id FROM matches WHERE jornada_id = #{jornada[0].to_i} LIMIT 20")
rescue Exception => e
puts "Exception occurred"
puts e
ensure
db.close if db
end
partidos.each do |partido|
puts partido
simpartido(partido["id"],partido["hometeam_id"],partido["awayteam_id"])
end
|
Frensdev/Basket-Manager
|
simulation/simjornada.rb
|
Ruby
|
gpl-2.0
| 654
|
var description = {
"author":"mengcraft.com",
"name":"AntiBedFucker",
"version":"1.0",
}
plugin.addListener("blockbreakevent", function(event) {
var b = event.block
if (b.type == org.bukkit.Material.BED_BLOCK) {
var p = event.player
var target = p.getTargetBlock(null, 5)
if (target == null || target.type != org.bukkit.Material.BED_BLOCK) {
event.cancelled = true
}
}
})
|
caoli5288/script
|
src/main/resources/antibedfucker.js
|
JavaScript
|
gpl-2.0
| 441
|
/* SPDX-License-Identifier: LGPL-2.1+ */
/***
***/
#include <pthread.h>
#include "sd-bus.h"
#include "sd-event.h"
#include "sd-id128.h"
#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "mkdir.h"
#include "path-util.h"
#include "random-util.h"
#include "rm-rf.h"
#include "socket-util.h"
#include "string-util.h"
static int method_foobar(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
log_info("Got Foobar() call.");
assert_se(sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 0) >= 0);
return sd_bus_reply_method_return(m, NULL);
}
static int method_exit(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
log_info("Got Exit() call");
assert_se(sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 1) >= 0);
return sd_bus_reply_method_return(m, NULL);
}
static const sd_bus_vtable vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_METHOD("Foobar", NULL, NULL, method_foobar, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD("Exit", NULL, NULL, method_exit, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_VTABLE_END,
};
static void* thread_server(void *p) {
_cleanup_free_ char *suffixed = NULL, *suffixed2 = NULL, *d = NULL;
_cleanup_close_ int fd = -1;
union sockaddr_union u = {
.un.sun_family = AF_UNIX,
};
const char *path = p;
log_debug("Initializing server");
/* Let's play some games, by slowly creating the socket directory, and renaming it in the middle */
(void) usleep(100 * USEC_PER_MSEC);
assert_se(mkdir_parents(path, 0755) >= 0);
(void) usleep(100 * USEC_PER_MSEC);
d = dirname_malloc(path);
assert_se(d);
assert_se(asprintf(&suffixed, "%s.%" PRIx64, d, random_u64()) >= 0);
assert_se(rename(d, suffixed) >= 0);
(void) usleep(100 * USEC_PER_MSEC);
assert_se(asprintf(&suffixed2, "%s.%" PRIx64, d, random_u64()) >= 0);
assert_se(symlink(suffixed2, d) >= 0);
(void) usleep(100 * USEC_PER_MSEC);
assert_se(symlink(basename(suffixed), suffixed2) >= 0);
(void) usleep(100 * USEC_PER_MSEC);
strncpy(u.un.sun_path, path, sizeof(u.un.sun_path));
fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
assert_se(fd >= 0);
assert_se(bind(fd, &u.sa, SOCKADDR_UN_LEN(u.un)) >= 0);
usleep(100 * USEC_PER_MSEC);
assert_se(listen(fd, SOMAXCONN) >= 0);
usleep(100 * USEC_PER_MSEC);
assert_se(touch(path) >= 0);
usleep(100 * USEC_PER_MSEC);
log_debug("Initialized server");
for (;;) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_(sd_event_unrefp) sd_event *event = NULL;
sd_id128_t id;
int bus_fd, code;
assert_se(sd_id128_randomize(&id) >= 0);
assert_se(sd_event_new(&event) >= 0);
bus_fd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
assert_se(bus_fd >= 0);
log_debug("Accepted server connection");
assert_se(sd_bus_new(&bus) >= 0);
assert_se(sd_bus_set_description(bus, "server") >= 0);
assert_se(sd_bus_set_fd(bus, bus_fd, bus_fd) >= 0);
assert_se(sd_bus_set_server(bus, true, id) >= 0);
/* assert_se(sd_bus_set_anonymous(bus, true) >= 0); */
assert_se(sd_bus_attach_event(bus, event, 0) >= 0);
assert_se(sd_bus_add_object_vtable(bus, NULL, "/foo", "foo.TestInterface", vtable, NULL) >= 0);
assert_se(sd_bus_start(bus) >= 0);
assert_se(sd_event_loop(event) >= 0);
assert_se(sd_event_get_exit_code(event, &code) >= 0);
if (code > 0)
break;
}
log_debug("Server done");
return NULL;
}
static void* thread_client1(void *p) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
const char *path = p, *t;
int r;
log_debug("Initializing client1");
assert_se(sd_bus_new(&bus) >= 0);
assert_se(sd_bus_set_description(bus, "client1") >= 0);
t = strjoina("unix:path=", path);
assert_se(sd_bus_set_address(bus, t) >= 0);
assert_se(sd_bus_set_watch_bind(bus, true) >= 0);
assert_se(sd_bus_start(bus) >= 0);
r = sd_bus_call_method(bus, "foo.bar", "/foo", "foo.TestInterface", "Foobar", &error, NULL, NULL);
assert_se(r >= 0);
log_debug("Client1 done");
return NULL;
}
static int client2_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
assert_se(sd_bus_message_is_method_error(m, NULL) == 0);
assert_se(sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 0) >= 0);
return 0;
}
static void* thread_client2(void *p) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_(sd_event_unrefp) sd_event *event = NULL;
const char *path = p, *t;
log_debug("Initializing client2");
assert_se(sd_event_new(&event) >= 0);
assert_se(sd_bus_new(&bus) >= 0);
assert_se(sd_bus_set_description(bus, "client2") >= 0);
t = strjoina("unix:path=", path);
assert_se(sd_bus_set_address(bus, t) >= 0);
assert_se(sd_bus_set_watch_bind(bus, true) >= 0);
assert_se(sd_bus_attach_event(bus, event, 0) >= 0);
assert_se(sd_bus_start(bus) >= 0);
assert_se(sd_bus_call_method_async(bus, NULL, "foo.bar", "/foo", "foo.TestInterface", "Foobar", client2_callback, NULL, NULL) >= 0);
assert_se(sd_event_loop(event) >= 0);
log_debug("Client2 done");
return NULL;
}
static void request_exit(const char *path) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
const char *t;
assert_se(sd_bus_new(&bus) >= 0);
t = strjoina("unix:path=", path);
assert_se(sd_bus_set_address(bus, t) >= 0);
assert_se(sd_bus_set_watch_bind(bus, true) >= 0);
assert_se(sd_bus_set_description(bus, "request-exit") >= 0);
assert_se(sd_bus_start(bus) >= 0);
assert_se(sd_bus_call_method(bus, "foo.bar", "/foo", "foo.TestInterface", "Exit", NULL, NULL, NULL) >= 0);
}
int main(int argc, char *argv[]) {
_cleanup_(rm_rf_physical_and_freep) char *d = NULL;
pthread_t server, client1, client2;
char *path;
log_set_max_level(LOG_DEBUG);
/* We use /dev/shm here rather than /tmp, since some weird distros might set up /tmp as some weird fs that
* doesn't support inotify properly. */
assert_se(mkdtemp_malloc("/dev/shm/systemd-watch-bind-XXXXXX", &d) >= 0);
path = strjoina(d, "/this/is/a/socket");
assert_se(pthread_create(&server, NULL, thread_server, path) == 0);
assert_se(pthread_create(&client1, NULL, thread_client1, path) == 0);
assert_se(pthread_create(&client2, NULL, thread_client2, path) == 0);
assert_se(pthread_join(client1, NULL) == 0);
assert_se(pthread_join(client2, NULL) == 0);
request_exit(path);
assert_se(pthread_join(server, NULL) == 0);
return 0;
}
|
fbuihuu/systemd
|
src/libsystemd/sd-bus/test-bus-watch-bind.c
|
C
|
gpl-2.0
| 7,455
|
#!/usr/bin/env bash
if [ "X$3" == "Xmaster" ]; then
cp /scripts/master-ossec.conf /var/ossec/etc/ossec.conf
elif [ "X$3" == "Xworker" ]; then
cp /scripts/worker-ossec.conf /var/ossec/etc/ossec.conf
fi
# add cluster configuration
sed -i "s:<key></key>:<key>9d273b53510fef702b54a92e9cffc82e</key>:g" /var/ossec/etc/ossec.conf
sed -i "s:<node>NODE_IP</node>:<node>$1</node>:g" /var/ossec/etc/ossec.conf
sed -i -e "/<cluster>/,/<\/cluster>/ s|<disabled>[a-z]\+</disabled>|<disabled>no</disabled>|g" /var/ossec/etc/ossec.conf
sed -i "s:<node_name>node01</node_name>:<node_name>$2</node_name>:g" /var/ossec/etc/ossec.conf
if [ "X$3" != "Xmaster" ]; then
sed -i "s:<node_type>master</node_type>:<node_type>worker</node_type>:g" /var/ossec/etc/ossec.conf
fi
# enable syscheck DB
echo 'wazuh_database.sync_syscheck=1' >> /var/ossec/etc/local_internal_options.conf
# configure API for development
sed -i 's/config.logs = "info";/config.logs = "debug";/g' /var/ossec/api/configuration/config.js
sed -i 's/config.cache_enabled = "yes";/config.cache_enabled = "no";/g' /var/ossec/api/configuration/config.js
sed -i 's/config.experimental_features = false;/config.experimental_features = true;/g' /var/ossec/api/configuration/config.js
cat <<EOT >> /var/ossec/api/configuration/preloaded_vars.conf
COUNTRY="US"
STATE="State"
LOCALITY="Locality"
ORG_NAME="Org Name"
ORG_UNIT="Org Unit Name"
COMMON_NAME="Common Name"
PASSWORD="password"
USER=foo
PASS=bar
PORT=55000
HTTPS=Y
AUTH=Y
PROXY=N
EOT
/var/ossec/api/scripts/configure_api.sh
# fix for generating Wazuh documentation
sed -i '26 s/self.errors/'\''ignore'\''/g' /usr/lib/python3.6/encodings/ascii.py
# start Wazuh
/var/ossec/bin/ossec-control start
# start Wazuh API
node /var/ossec/api/app.js &
# start SSH server
/usr/sbin/sshd -D &
tail -f /var/ossec/logs/ossec.log
|
wazuh/wazuh-API
|
test/environment/docker/ubuntu/wazuh-manager/entrypoint.sh
|
Shell
|
gpl-2.0
| 1,833
|
# Memory Master
Memory Master is a card matching game in the style of the classic ["Concentration"](https://en.wikipedia.org/wiki/Concentration_(game)). It's an HTML5 application targetting modern browsers, and currently has build targets for the web and the [Chrome Web Store](https://chrome.google.com/webstore/detail/memory-master/cmhijgcjdhjlklainhonijjncaklooai). The game is built entirely with HTML, CSS, and JavaScript (using [Angular](https://angularjs.org/)). The project is primarily an excuse to explore various front-end tools and Chrome APIs. For a quick look at the finished project, [try the game](http://www.blrice.net/memory_master/play/).
## Developing
1. Fork it.
2. Hack on files in app/
3. `grunt build` to build all targets
|
nevern02/memory_master
|
README.md
|
Markdown
|
gpl-2.0
| 753
|
/**
* @package AcyMailing for Joomla!
* @version 5.6.1
* @author acyba.com
* @copyright (C) 2009-2017 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
@import url("component_default_basic_black.css");
#acymodifyform .button:hover, #unsubbutton_div .button:hover, #acyarchivelisting .button:hover {
color:#bc1f00;}
#acyarchivelisting .contentheading{
color:#770000;
border-bottom:1px solid #770000;
}
#acyarchivelisting .contentpane .contentdescription{
color:#bc1f00;
}
#acyarchivelisting .sectiontableheader a:hover{
color:#bc1f00;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1 a:hover{
color:#bc1f00;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2 a:hover{
color:#bc1f00;
}
#acyarchiveview .contentheading{
color:#bc1f00;}
#acylistslisting .componentheading{
color:#770000;
border-bottom:1px solid #770000;
}
#acylistslisting .list_name a{
color:#bc1f00;
}
#acylistslisting .list_name a:hover, #acylistslisting .list_name a:focus {
color:#bc1f00;
}
#acymodifyform legend{
color:#770000;
border-bottom:1px solid #770000;
}
#acyusersubscription .list_name{
color: #bc1f00;
}
#unsubpage .unsubintro{
color:#770000;
border-bottom: 1px solid #770000;
}
#unsubpage .unsubsurveytext{
color:#770000;
border-bottom: 1px solid #770000;
}
|
natalyandreeva/joomla
|
media/com_acymailing/css/component_default_basic_red.css
|
CSS
|
gpl-2.0
| 1,470
|
/*
* arch/arm/mach-tegra/tegra2_dvfs.c
*
* Copyright (C) 2010 Google, Inc.
*
* Author:
* Colin Cross <ccross@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/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/module.h>
#include "clock.h"
#include "dvfs.h"
#include "fuse.h"
#ifdef CONFIG_TEGRA_CORE_DVFS
static bool tegra_dvfs_core_disabled;
#else
static bool tegra_dvfs_core_disabled = true;
#endif
#ifdef CONFIG_TEGRA_CPU_DVFS
static bool tegra_dvfs_cpu_disabled;
#else
static bool tegra_dvfs_cpu_disabled = true;
#endif
static const int core_millivolts[MAX_DVFS_FREQS] =
{950, 1000, 1100, 1200, 1225, 1275, 1300};
static const int cpu_millivolts[MAX_DVFS_FREQS] =
{750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025, 1050, 1100, 1125, 1125};
static const int cpu_speedo_nominal_millivolts[] =
/* spedo_id 0, 1, 2 */
{ 1100, 1025, 1125 };
static const int core_speedo_nominal_millivolts[] =
/* spedo_id 0, 1, 2 */
{ 1225, 1225, 1300 };
#define KHZ 1000
#define MHZ 1000000
static struct dvfs_rail tegra2_dvfs_rail_vdd_cpu = {
.reg_id = "vdd_cpu",
.max_millivolts = 1125,
.min_millivolts = 750,
.nominal_millivolts = 1125,
};
static struct dvfs_rail tegra2_dvfs_rail_vdd_core = {
.reg_id = "vdd_core",
.max_millivolts = 1300,
.min_millivolts = 950,
.nominal_millivolts = 1225,
.step = 150, /* step vdd_core by 150 mV to allow vdd_aon to follow */
};
static struct dvfs_rail tegra2_dvfs_rail_vdd_aon = {
.reg_id = "vdd_aon",
.max_millivolts = 1300,
.min_millivolts = 950,
.nominal_millivolts = 1225,
#ifndef CONFIG_TEGRA_CORE_DVFS
.disabled = true,
#endif
};
/* vdd_core and vdd_aon must be 50 mV higher than vdd_cpu */
static int tegra2_dvfs_rel_vdd_cpu_vdd_core(struct dvfs_rail *vdd_cpu,
struct dvfs_rail *vdd_core)
{
if (vdd_cpu->new_millivolts > vdd_cpu->millivolts &&
vdd_core->new_millivolts < vdd_cpu->new_millivolts + 50)
return vdd_cpu->new_millivolts + 50;
if (vdd_core->new_millivolts < vdd_cpu->millivolts + 50)
return vdd_cpu->millivolts + 50;
return vdd_core->new_millivolts;
}
/* vdd_aon must be within 170 mV of vdd_core */
static int tegra2_dvfs_rel_vdd_core_vdd_aon(struct dvfs_rail *vdd_core,
struct dvfs_rail *vdd_aon)
{
BUG_ON(abs(vdd_aon->millivolts - vdd_core->millivolts) >
vdd_aon->step);
return vdd_core->millivolts;
}
static struct dvfs_relationship tegra2_dvfs_relationships[] = {
{
/* vdd_core must be 50 mV higher than vdd_cpu */
.from = &tegra2_dvfs_rail_vdd_cpu,
.to = &tegra2_dvfs_rail_vdd_core,
.solve = tegra2_dvfs_rel_vdd_cpu_vdd_core,
},
{
/* vdd_aon must be 50 mV higher than vdd_cpu */
.from = &tegra2_dvfs_rail_vdd_cpu,
.to = &tegra2_dvfs_rail_vdd_aon,
.solve = tegra2_dvfs_rel_vdd_cpu_vdd_core,
},
{
/* vdd_aon must be within 170 mV of vdd_core */
.from = &tegra2_dvfs_rail_vdd_core,
.to = &tegra2_dvfs_rail_vdd_aon,
.solve = tegra2_dvfs_rel_vdd_core_vdd_aon,
},
};
static struct dvfs_rail *tegra2_dvfs_rails[] = {
&tegra2_dvfs_rail_vdd_cpu,
&tegra2_dvfs_rail_vdd_core,
&tegra2_dvfs_rail_vdd_aon,
};
#define CPU_DVFS(_clk_name, _speedo_id, _process_id, _mult, _freqs...) \
{ \
.clk_name = _clk_name, \
.speedo_id = _speedo_id, \
.process_id = _process_id, \
.freqs = {_freqs}, \
.freqs_mult = _mult, \
.millivolts = cpu_millivolts, \
.auto_dvfs = true, \
.dvfs_rail = &tegra2_dvfs_rail_vdd_cpu, \
}
#define CORE_DVFS(_clk_name, _process_id, _auto, _mult, _freqs...) \
{ \
.clk_name = _clk_name, \
.speedo_id = -1, \
.process_id = _process_id, \
.freqs = {_freqs}, \
.freqs_mult = _mult, \
.millivolts = core_millivolts, \
.auto_dvfs = _auto, \
.dvfs_rail = &tegra2_dvfs_rail_vdd_core, \
}
static struct dvfs dvfs_init[] = {
/* Cpu voltages (mV): 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025, 1050, 1100, 1125 */
CPU_DVFS("cpu", 0, MHZ, 314, 314, 314, 456, 456, 608, 608, 760, 817, 912, 1000, 1200, 1400),
CPU_DVFS("cpu", 1, MHZ, 314, 314, 314, 456, 456, 618, 618, 770, 827, 922, 1000, 1200, 1400),
CPU_DVFS("cpu", 2, MHZ, 494, 675, 675, 675, 817, 817, 922, 1000, 1200, 1400),
CPU_DVFS("cpu", 3, MHZ, 730, 760, 845, 845, 1000, 1200, 1400),
/* Core voltages (mV): 950, 1000, 1100, 1200, 1225, 1275, 1300 */
CORE_DVFS("emc", -1, 1, KHZ, 57000, 333000, 380000, 666000, 666000, 666000, 760000),
#if 0
/*
* The sdhci core calls the clock ops with a spinlock held, which
* conflicts with the sleeping dvfs api.
* For now, boards must ensure that the core voltage does not drop
* below 1V, or that the sdmmc busses are set to 44 MHz or less.
*/
CORE_DVFS("sdmmc1", -1, 1, KHZ, 44000, 52000, 52000, 52000, 52000, 52000, 52000),
CORE_DVFS("sdmmc2", -1, 1, KHZ, 44000, 52000, 52000, 52000, 52000, 52000, 52000),
CORE_DVFS("sdmmc3", -1, 1, KHZ, 44000, 52000, 52000, 52000, 52000, 52000, 52000),
CORE_DVFS("sdmmc4", -1, 1, KHZ, 44000, 52000, 52000, 52000, 52000, 52000, 52000),
#endif
CORE_DVFS("ndflash", -1, 1, KHZ, 130000, 150000, 158000, 164000, 164000, 164000, 164000),
CORE_DVFS("nor", -1, 1, KHZ, 0, 92000, 92000, 92000, 92000, 92000, 92000),
CORE_DVFS("ide", -1, 1, KHZ, 0, 0, 100000, 100000, 100000, 100000, 100000),
CORE_DVFS("mipi", -1, 1, KHZ, 0, 40000, 40000, 40000, 40000, 60000, 60000),
CORE_DVFS("usbd", -1, 1, KHZ, 0, 0, 0, 480000, 480000, 480000, 480000),
CORE_DVFS("usb2", -1, 1, KHZ, 0, 0, 0, 480000, 480000, 480000, 480000),
CORE_DVFS("usb3", -1, 1, KHZ, 0, 0, 0, 480000, 480000, 480000, 480000),
CORE_DVFS("pcie", -1, 1, KHZ, 0, 0, 0, 250000, 250000, 250000, 250000),
CORE_DVFS("dsi", -1, 1, KHZ, 100000, 100000, 100000, 500000, 500000, 500000, 500000),
CORE_DVFS("tvo", -1, 1, KHZ, 0, 0, 0, 250000, 250000, 250000, 250000),
/*
* The clock rate for the display controllers that determines the
* necessary core voltage depends on a divider that is internal
* to the display block. Disable auto-dvfs on the display clocks,
* and let the display driver call tegra_dvfs_set_rate manually
*/
CORE_DVFS("disp1", -1, 0, KHZ, 158000, 158000, 190000, 190000, 190000, 190000, 190000),
CORE_DVFS("disp2", -1, 0, KHZ, 158000, 158000, 190000, 190000, 190000, 190000, 190000),
CORE_DVFS("hdmi", -1, 0, KHZ, 0, 0, 0, 148500, 148500, 148500, 148500),
/*
* Clocks below depend on the core process id. Define per process_id
* tables for SCLK/VDE/3D clocks (maximum rate for these clocks is
* increased depending on tegra2 sku). Use the worst case value for
* other clocks for now.
*/
CORE_DVFS("host1x", -1, 1, KHZ, 104500, 133000, 166000, 166000, 166000, 166000, 166000),
CORE_DVFS("epp", -1, 1, KHZ, 133000, 171000, 247000, 300000, 300000, 300000, 300000),
CORE_DVFS("2d", -1, 1, KHZ, 133000, 171000, 247000, 300000, 300000, 300000, 300000),
CORE_DVFS("3d", 0, 1, KHZ, 114000, 161500, 247000, 304000, 304000, 333500, 333500),
CORE_DVFS("3d", 1, 1, KHZ, 161500, 209000, 285000, 333500, 333500, 361000, 361000),
CORE_DVFS("3d", 2, 1, KHZ, 218500, 256500, 323000, 380000, 380000, 400000, 400000),
CORE_DVFS("3d", 3, 1, KHZ, 247000, 285000, 351500, 400000, 400000, 400000, 400000),
CORE_DVFS("mpe", 0, 1, KHZ, 104500, 152000, 228000, 300000, 300000, 300000, 300000),
CORE_DVFS("mpe", 1, 1, KHZ, 142500, 190000, 275500, 300000, 300000, 300000, 300000),
CORE_DVFS("mpe", 2, 1, KHZ, 190000, 237500, 300000, 300000, 300000, 300000, 300000),
CORE_DVFS("mpe", 3, 1, KHZ, 228000, 266000, 300000, 300000, 300000, 300000, 300000),
CORE_DVFS("vi", -1, 1, KHZ, 85000, 100000, 150000, 150000, 150000, 150000, 150000),
CORE_DVFS("sclk", 0, 1, KHZ, 95000, 133000, 190000, 222500, 240000, 247000, 262000),
CORE_DVFS("sclk", 1, 1, KHZ, 123500, 159500, 207000, 240000, 240000, 264000, 277500),
CORE_DVFS("sclk", 2, 1, KHZ, 152000, 180500, 229500, 260000, 260000, 285000, 300000),
CORE_DVFS("sclk", 3, 1, KHZ, 171000, 218500, 256500, 292500, 292500, 300000, 300000),
CORE_DVFS("vde", 0, 1, KHZ, 95000, 123500, 209000, 275500, 275500, 300000, 300000),
CORE_DVFS("vde", 1, 1, KHZ, 123500, 152000, 237500, 300000, 300000, 300000, 300000),
CORE_DVFS("vde", 2, 1, KHZ, 152000, 209000, 285000, 300000, 300000, 300000, 300000),
CORE_DVFS("vde", 3, 1, KHZ, 171000, 218500, 300000, 300000, 300000, 300000, 300000),
/* What is this? */
CORE_DVFS("NVRM_DEVID_CLK_SRC", -1, 1, MHZ, 480, 600, 800, 1067, 1067, 1067, 1067),
};
int tegra_dvfs_disable_core_set(const char *arg, const struct kernel_param *kp)
{
int ret;
ret = param_set_bool(arg, kp);
if (ret)
return ret;
if (tegra_dvfs_core_disabled)
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_core);
else
tegra_dvfs_rail_enable(&tegra2_dvfs_rail_vdd_core);
return 0;
}
int tegra_dvfs_disable_cpu_set(const char *arg, const struct kernel_param *kp)
{
int ret;
ret = param_set_bool(arg, kp);
if (ret)
return ret;
if (tegra_dvfs_cpu_disabled)
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_cpu);
else
tegra_dvfs_rail_enable(&tegra2_dvfs_rail_vdd_cpu);
return 0;
}
int tegra_dvfs_disable_get(char *buffer, const struct kernel_param *kp)
{
return param_get_bool(buffer, kp);
}
static struct kernel_param_ops tegra_dvfs_disable_core_ops = {
.set = tegra_dvfs_disable_core_set,
.get = tegra_dvfs_disable_get,
};
static struct kernel_param_ops tegra_dvfs_disable_cpu_ops = {
.set = tegra_dvfs_disable_cpu_set,
.get = tegra_dvfs_disable_get,
};
module_param_cb(disable_core, &tegra_dvfs_disable_core_ops,
&tegra_dvfs_core_disabled, 0644);
module_param_cb(disable_cpu, &tegra_dvfs_disable_cpu_ops,
&tegra_dvfs_cpu_disabled, 0644);
void __init tegra2_init_dvfs(void)
{
int i;
struct clk *c;
struct dvfs *d;
int process_id;
int ret;
int cpu_process_id = tegra_cpu_process_id();
int core_process_id = tegra_core_process_id();
int speedo_id = tegra_soc_speedo_id();
BUG_ON(speedo_id >= ARRAY_SIZE(cpu_speedo_nominal_millivolts));
tegra2_dvfs_rail_vdd_cpu.nominal_millivolts =
cpu_speedo_nominal_millivolts[speedo_id];
BUG_ON(speedo_id >= ARRAY_SIZE(core_speedo_nominal_millivolts));
tegra2_dvfs_rail_vdd_core.nominal_millivolts =
core_speedo_nominal_millivolts[speedo_id];
tegra2_dvfs_rail_vdd_aon.nominal_millivolts =
core_speedo_nominal_millivolts[speedo_id];
tegra_dvfs_init_rails(tegra2_dvfs_rails, ARRAY_SIZE(tegra2_dvfs_rails));
tegra_dvfs_add_relationships(tegra2_dvfs_relationships,
ARRAY_SIZE(tegra2_dvfs_relationships));
/*
* VDD_CORE must always be at least 50 mV higher than VDD_CPU
* Fill out cpu_core_millivolts based on cpu_millivolts
*/
for (i = 0; i < ARRAY_SIZE(dvfs_init); i++) {
d = &dvfs_init[i];
process_id = strcmp(d->clk_name, "cpu") ?
core_process_id : cpu_process_id;
if ((d->process_id != -1 && d->process_id != process_id) ||
(d->speedo_id != -1 && d->speedo_id != speedo_id)) {
pr_debug("tegra_dvfs: rejected %s speedo %d,"
" process %d\n", d->clk_name, d->speedo_id,
d->process_id);
continue;
}
c = tegra_get_clock_by_name(d->clk_name);
if (!c) {
pr_debug("tegra_dvfs: no clock found for %s\n",
d->clk_name);
continue;
}
ret = tegra_enable_dvfs_on_clk(c, d);
if (ret)
pr_err("tegra_dvfs: failed to enable dvfs on %s\n",
c->name);
}
if (tegra_dvfs_core_disabled)
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_core);
if (tegra_dvfs_cpu_disabled)
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_cpu);
}
void tegra_dvfs_disable_core_cpu(void)
{
printk("tegra_dvfs: disable core & cpu dvfs\n");
tegra_dvfs_core_disabled = false;
tegra_dvfs_cpu_disabled = false;
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_core);
tegra_dvfs_rail_disable(&tegra2_dvfs_rail_vdd_cpu);
}
EXPORT_SYMBOL(tegra_dvfs_disable_core_cpu);
|
zuch0698o/lge-kernel-startablet
|
arch/arm/mach-tegra/tegra2_dvfs.c
|
C
|
gpl-2.0
| 12,424
|
/*
* %kadu copyright begin%
* Copyright 2009, 2010, 2011, 2012 Piotr Galiszewski (piotr.galiszewski@kadu.im)
* Copyright 2009 Wojciech Treter (juzefwt@gmail.com)
* Copyright 2009 Michał Podsiadlik (michal@kadu.net)
* Copyright 2009 Bartłomiej Zimoń (uzi18@o2.pl)
* Copyright 2010, 2011, 2013, 2014 Bartosz Brachaczek (b.brachaczek@gmail.com)
* Copyright 2009, 2010, 2011, 2012, 2013, 2014 Rafał Przemysław Malinowski (rafal.przemyslaw.malinowski@gmail.com)
* %kadu copyright end%
*
* 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/>.
*/
#ifndef CHAT_H
#define CHAT_H
#include "chat/chat-shared.h"
#include "exports.h"
#include "storage/shared-base.h"
class Account;
class ContactSet;
class ChatDetails;
class ChatType;
class StoragePoint;
class QString;
/**
* @addtogroup Chat
* @{
*/
/**
* @class Chat
* @short Access object for chat data.
*
* This class allows to access to chat data defined in @link ChatShared @endlink class.
*/
class KADUAPI Chat : public SharedBase<ChatShared>
{
KaduSharedBaseClass(Chat)
public : static Chat null;
Chat();
Chat(ChatShared *data);
explicit Chat(QObject *data);
Chat(const Chat ©);
virtual ~Chat();
bool showInAllGroup() const;
bool isInGroup(Group group) const;
void addToGroup(Group group) const;
void removeFromGroup(Group group) const;
KaduSharedBase_PropertyRead(ContactSet, contacts, Contacts);
KaduSharedBase_PropertyRead(QString, name, Name);
/**
* @short Details object for this chat.
*
* When ChatType for this chat is loaded and registered in ChatTypeManager
* this field contains ChatDetails object that holds detailed information
* about this chat.
*/
KaduSharedBase_PropertyRead(ChatDetails *, details, Details);
/**
* @short Account of this chat.
*
* Every chat is assigned to account. All contacts in every chat must
* belong to the same account as chat.
*/
KaduSharedBase_PropertyCRW(Account, chatAccount, ChatAccount);
/**
* @short Name of chat type.
*
* Name of chat type. @link ChatType @endlink object with the same name must be loaded
* and registered in @link ChatTypeManager @endlink to allow this chat object to
* be fully functional and used. Example chat types are: 'contact' (for one-to-one chats)
* and 'contact-set' (for on-to-many chats). Other what types could be: 'irc-room' (for irc room
* chats).
*/
KaduSharedBase_PropertyCRW(QString, type, Type);
KaduSharedBase_PropertyCRW(QString, display, Display);
KaduSharedBase_PropertyBool(IgnoreAllMessages);
KaduSharedBase_PropertyCRW(QSet<Group>, groups, Groups);
KaduSharedBase_Property(quint16, unreadMessagesCount, UnreadMessagesCount);
/**
* @short Return true when chat is connected.
* @return true when chat is connected
*
* Chat messages can only be send to/received from connected chat.
* Chat connection depends on chat type and is implemented in @link ChatDetails @endlink subclasses.
*
* For example, simple Contact and ContactSet chats are connected when an account is connected.
* MUC chats in XMPP are connected when account is connected and given group chat is joined.
*/
bool isConnected() const;
/**
* @short Get value of Open property.
* @return true when chat is open
*
* Chat is open when an associated chat widget is open.
*/
bool isOpen() const;
/**
* @short Set value of open property.
* @param open new value of Open property
*
* Changing value of Open property may result in emiting of @link opened() @endlink or @link closed() @endlink
* singals.
*/
void setOpen(bool open);
};
KADUAPI QString title(const Chat &chat);
/**
* @}
*/
Q_DECLARE_METATYPE(Chat)
#endif // CHAT_H
|
vogel/kadu
|
kadu-core/chat/chat.h
|
C
|
gpl-2.0
| 4,467
|
#include "NodeJSLocator.h"
#include "cl_standard_paths.h"
#include "globals.h"
#ifdef __WXMSW__
#include <wx/msw/registry.h>
#include <wx/volume.h>
#endif
NodeJSLocator::NodeJSLocator() {}
NodeJSLocator::~NodeJSLocator() {}
void NodeJSLocator::Locate(const wxArrayString& hints)
{
wxArrayString paths = hints;
wxFileName fn_npm;
#if defined(__WXGTK__) || defined(__WXOSX__)
// Linux
// add the standard paths
paths.Add("/usr/local/bin");
paths.Add("/usr/bin");
wxFileName nodejs;
wxFileName npm;
if(TryPaths(paths, "node", nodejs) || TryPaths(paths, "nodejs", nodejs) || TryPaths(paths, "node.osx", nodejs)) {
m_nodejs = nodejs.GetFullPath();
}
if(TryPaths(paths, "npm", npm)) {
m_npm = npm.GetFullPath();
}
#elif defined(__WXMSW__)
// Registry paths are searched first
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Node.js
wxRegKey regKeyNodeJS(wxRegKey::HKLM, "SOFTWARE\\Node.js");
wxString clInstallFolder;
if(regKeyNodeJS.Exists() && regKeyNodeJS.QueryValue("InstallPath", clInstallFolder) &&
wxDirExists(clInstallFolder)) {
paths.Add(clInstallFolder);
}
}
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Node.js
wxRegKey regKeyNodeJS(wxRegKey::HKLM, "SOFTWARE\\Wow6432Node\\Node.js");
wxString clInstallFolder;
if(regKeyNodeJS.Exists() && regKeyNodeJS.QueryValue("InstallPath", clInstallFolder) &&
wxDirExists(clInstallFolder)) {
paths.Add(clInstallFolder);
}
}
// On Windows, first try to locate npm.cmd
if(m_npm.IsEmpty() && ::clFindExecutable("npm.cmd", fn_npm, paths)) {
m_npm = fn_npm.GetFullPath();
}
#endif
// Still could not find it, try the PATH environment variable
wxFileName fn_node;
if(m_nodejs.empty() && ::clFindExecutable("node", fn_node, paths)) {
m_nodejs = fn_node.GetFullPath();
}
// No luck? locate npm
if(m_npm.empty() && ::clFindExecutable("npm", fn_npm, paths)) {
m_npm = fn_npm.GetFullPath();
}
}
bool NodeJSLocator::TryPaths(const wxArrayString& paths, const wxString& fullname, wxFileName& fullpath)
{
for(size_t i = 0; i < paths.size(); ++i) {
wxFileName fn(paths.Item(i), fullname);
if(fn.FileExists()) {
fullpath = fn;
return true;
}
}
return false;
}
|
eranif/codelite
|
Plugin/NodeJSLocator.cpp
|
C++
|
gpl-2.0
| 2,407
|
#!/usr/bin/perl
# -*- cperl -*-
# Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library 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
#
##############################################################################
#
# mysql-test-run.pl
#
# Tool used for executing a suite of .test files
#
# See the "MySQL Test framework manual" for more information
# http://dev.mysql.com/doc/mysqltest/en/index.html
#
#
##############################################################################
use strict;
use warnings;
BEGIN {
# Check that mysql-test-run.pl is started from mysql-test/
unless ( -f "mysql-test-run.pl" )
{
print "**** ERROR **** ",
"You must start mysql-test-run from the mysql-test/ directory\n";
exit(1);
}
# Check that lib exist
unless ( -d "lib/" )
{
print "**** ERROR **** ",
"Could not find the lib/ directory \n";
exit(1);
}
}
BEGIN {
# Check backward compatibility support
# By setting the environment variable MTR_VERSION
# it's possible to use a previous version of
# mysql-test-run.pl
my $version= $ENV{MTR_VERSION} || 2;
if ( $version == 1 )
{
print "=======================================================\n";
print " WARNING: Using mysql-test-run.pl version 1! \n";
print "=======================================================\n";
# Should use exec() here on *nix but this appears not to work on Windows
exit(system($^X, "lib/v1/mysql-test-run.pl", @ARGV) >> 8);
}
elsif ( $version == 2 )
{
# This is the current version, just continue
;
}
else
{
print "ERROR: Version $version of mysql-test-run does not exist!\n";
exit(1);
}
}
use lib "lib";
use Cwd;
use Getopt::Long;
use My::File::Path; # Patched version of File::Path
use File::Basename;
use File::Copy;
use File::Find;
use File::Temp qw/tempdir/;
use File::Spec::Functions qw/splitdir/;
use My::Platform;
use My::SafeProcess;
use My::ConfigFactory;
use My::Options;
use My::Find;
use My::SysInfo;
use My::CoreDump;
use mtr_cases;
use mtr_report;
use mtr_match;
use mtr_unique;
use IO::Socket::INET;
use IO::Select;
require "lib/mtr_process.pl";
require "lib/mtr_io.pl";
require "lib/mtr_gcov.pl";
require "lib/mtr_gprof.pl";
require "lib/mtr_misc.pl";
$SIG{INT}= sub { mtr_error("Got ^C signal"); };
our $mysql_version_id;
our $glob_mysql_test_dir;
our $basedir;
our $path_charsetsdir;
our $path_client_bindir;
our $path_client_libdir;
our $path_language;
our $path_current_testlog;
our $path_testlog;
our $default_vardir;
our $opt_vardir; # Path to use for var/ dir
my $path_vardir_trace; # unix formatted opt_vardir for trace files
my $opt_tmpdir; # Path to use for tmp/ dir
my $opt_tmpdir_pid;
my $opt_start;
my $opt_start_dirty;
my $opt_start_exit;
my $start_only;
END {
if ( defined $opt_tmpdir_pid and $opt_tmpdir_pid == $$ )
{
if (!$opt_start_exit)
{
# Remove the tempdir this process has created
mtr_verbose("Removing tmpdir $opt_tmpdir");
rmtree($opt_tmpdir);
}
else
{
mtr_warning("tmpdir $opt_tmpdir should be removed after the server has finished");
}
}
}
sub env_or_val($$) { defined $ENV{$_[0]} ? $ENV{$_[0]} : $_[1] }
my $path_config_file; # The generated config file, var/my.cnf
# Visual Studio produces executables in different sub-directories based on the
# configuration used to build them. To make life easier, an environment
# variable or command-line option may be specified to control which set of
# executables will be used by the test suite.
our $opt_vs_config = $ENV{'MTR_VS_CONFIG'};
my $DEFAULT_SUITES= "main,binlog,federated,rpl,rpl_ndb,ndb,innodb,innodb_plugin";
my $opt_suites;
our $opt_verbose= 0; # Verbose output, enable with --verbose
our $exe_mysql;
our $exe_mysqladmin;
our $exe_mysqltest;
our $exe_libtool;
our $opt_big_test= 0;
our @opt_combinations;
our @opt_extra_mysqld_opt;
my $opt_compress;
my $opt_ssl;
my $opt_skip_ssl;
our $opt_ssl_supported;
my $opt_ps_protocol;
my $opt_sp_protocol;
my $opt_cursor_protocol;
my $opt_view_protocol;
our $opt_debug;
our $opt_debug_server;
our @opt_cases; # The test cases names in argv
our $opt_embedded_server;
# Options used when connecting to an already running server
my %opts_extern;
sub using_extern { return (keys %opts_extern > 0);};
our $opt_fast= 0;
our $opt_force;
our $opt_mem= $ENV{'MTR_MEM'};
our $opt_gcov;
our $opt_gcov_exe= "gcov";
our $opt_gcov_err= "mysql-test-gcov.msg";
our $opt_gcov_msg= "mysql-test-gcov.err";
our $opt_gprof;
our %gprof_dirs;
our $glob_debugger= 0;
our $opt_gdb;
our $opt_client_gdb;
our $opt_ddd;
our $opt_client_ddd;
our $opt_manual_gdb;
our $opt_manual_ddd;
our $opt_manual_debug;
our $opt_debugger;
our $opt_client_debugger;
my $config; # The currently running config
my $current_config_name; # The currently running config file template
our @opt_experimentals;
our $experimental_test_cases= [];
my $baseport;
# $opt_build_thread may later be set from $opt_port_base
my $opt_build_thread= $ENV{'MTR_BUILD_THREAD'} || "auto";
my $opt_port_base= $ENV{'MTR_PORT_BASE'} || "auto";
my $build_thread= 0;
my $opt_record;
my $opt_report_features;
my $opt_skip_core;
our $opt_check_testcases= 1;
my $opt_mark_progress;
my $opt_max_connections;
my $opt_sleep;
my $opt_testcase_timeout= $ENV{MTR_TESTCASE_TIMEOUT} || 15; # minutes
my $opt_suite_timeout = $ENV{MTR_SUITE_TIMEOUT} || 300; # minutes
my $opt_shutdown_timeout= $ENV{MTR_SHUTDOWN_TIMEOUT} || 10; # seconds
my $opt_start_timeout = $ENV{MTR_START_TIMEOUT} || 180; # seconds
sub suite_timeout { return $opt_suite_timeout * 60; };
sub check_timeout { return $opt_testcase_timeout * 6; };
my $opt_wait_all;
my $opt_user_args;
my $opt_repeat= 1;
my $opt_retry= 3;
my $opt_retry_failure= env_or_val(MTR_RETRY_FAILURE => 2);
my $opt_reorder= 1;
my $opt_force_restart= 0;
my $opt_strace_client;
our $opt_user = "root";
our $opt_valgrind= 0;
my $opt_valgrind_mysqld= 0;
my $opt_valgrind_mysqltest= 0;
my @default_valgrind_args= ("--show-reachable=yes");
my @valgrind_args;
my $opt_valgrind_path;
my $opt_callgrind;
my %mysqld_logs;
my $opt_debug_sync_timeout= 300; # Default timeout for WAIT_FOR actions.
sub testcase_timeout ($) {
my ($tinfo)= @_;
if (exists $tinfo->{'case-timeout'}) {
# Return test specific timeout if *longer* that the general timeout
my $test_to= $tinfo->{'case-timeout'};
$test_to*= 10 if $opt_valgrind;
return $test_to * 60 if $test_to > $opt_testcase_timeout;
}
return $opt_testcase_timeout * 60;
}
our $opt_warnings= 1;
our $opt_include_ndbcluster= 0;
our $opt_skip_ndbcluster= 1;
my $exe_ndbd;
my $exe_ndb_mgmd;
my $exe_ndb_waiter;
our $debug_compiled_binaries;
our %mysqld_variables;
my $source_dist= 0;
my $opt_max_save_core= env_or_val(MTR_MAX_SAVE_CORE => 5);
my $opt_max_save_datadir= env_or_val(MTR_MAX_SAVE_DATADIR => 20);
my $opt_max_test_fail= env_or_val(MTR_MAX_TEST_FAIL => 10);
my $opt_parallel= $ENV{MTR_PARALLEL} || 1;
select(STDOUT);
$| = 1; # Automatically flush STDOUT
main();
sub main {
# Default, verbosity on
report_option('verbose', 0);
# This is needed for test log evaluation in "gen-build-status-page"
# in all cases where the calling tool does not log the commands
# directly before it executes them, like "make test-force-pl" in RPM builds.
mtr_report("Logging: $0 ", join(" ", @ARGV));
command_line_setup();
# --help will not reach here, so now it's safe to assume we have binaries
My::SafeProcess::find_bin();
if ( $opt_gcov ) {
gcov_prepare($basedir);
}
if (!$opt_suites) {
$opt_suites= $DEFAULT_SUITES;
# Check for any extra suites to enable based on the path name
my %extra_suites=
(
"mysql-5.1-new-ndb" => "ndb_team",
"mysql-5.1-new-ndb-merge" => "ndb_team",
"mysql-5.1-telco-6.2" => "ndb_team",
"mysql-5.1-telco-6.2-merge" => "ndb_team",
"mysql-5.1-telco-6.3" => "ndb_team",
"mysql-6.0-ndb" => "ndb_team",
);
foreach my $dir ( reverse splitdir($basedir) ) {
my $extra_suite= $extra_suites{$dir};
if (defined $extra_suite) {
mtr_report("Found extra suite: $extra_suite");
$opt_suites= "$extra_suite,$opt_suites";
last;
}
}
}
mtr_report("Collecting tests...");
my $tests= collect_test_cases($opt_reorder, $opt_suites, \@opt_cases);
if ( $opt_report_features ) {
# Put "report features" as the first test to run
my $tinfo = My::Test->new
(
name => 'report_features',
# No result_file => Prints result
path => 'include/report-features.test',
template_path => "include/default_my.cnf",
master_opt => [],
slave_opt => [],
);
unshift(@$tests, $tinfo);
}
print "vardir: $opt_vardir\n";
initialize_servers();
#######################################################################
my $num_tests= @$tests;
if ( $opt_parallel eq "auto" ) {
# Try to find a suitable value for number of workers
my $sys_info= My::SysInfo->new();
$opt_parallel= $sys_info->num_cpus();
for my $limit (2000, 1500, 1000, 500){
$opt_parallel-- if ($sys_info->min_bogomips() < $limit);
}
my $max_par= $ENV{MTR_MAX_PARALLEL} || 8;
$opt_parallel= $max_par if ($opt_parallel > $max_par);
$opt_parallel= $num_tests if ($opt_parallel > $num_tests);
$opt_parallel= 1 if (IS_WINDOWS and $sys_info->isvm());
$opt_parallel= 1 if ($opt_parallel < 1);
mtr_report("Using parallel: $opt_parallel");
}
if ($opt_parallel > 1 && $opt_start_exit) {
mtr_warning("Parallel and --start-and-exit cannot be combined\n" .
"Setting parallel to 1");
$opt_parallel= 1;
}
# Create server socket on any free port
my $server = new IO::Socket::INET
(
LocalAddr => 'localhost',
Proto => 'tcp',
Listen => $opt_parallel,
);
mtr_error("Could not create testcase server port: $!") unless $server;
my $server_port = $server->sockport();
mtr_report("Using server port $server_port");
# Create child processes
my %children;
for my $child_num (1..$opt_parallel){
my $child_pid= My::SafeProcess::Base::_safe_fork();
if ($child_pid == 0){
$server= undef; # Close the server port in child
$tests= {}; # Don't need the tests list in child
# Use subdir of var and tmp unless only one worker
if ($opt_parallel > 1) {
set_vardir("$opt_vardir/$child_num");
$opt_tmpdir= "$opt_tmpdir/$child_num";
}
run_worker($server_port, $child_num);
exit(1);
}
$children{$child_pid}= 1;
}
#######################################################################
mtr_report();
mtr_print_thick_line();
mtr_print_header();
my $completed= run_test_server($server, $tests, $opt_parallel);
exit(0) if $opt_start_exit;
# Send Ctrl-C to any children still running
kill("INT", keys(%children));
# Wait for childs to exit
foreach my $pid (keys %children)
{
my $ret_pid= waitpid($pid, 0);
if ($ret_pid != $pid){
mtr_report("Unknown process $ret_pid exited");
}
else {
delete $children{$ret_pid};
}
}
if ( not defined @$completed ) {
mtr_error("Test suite aborted");
}
if ( @$completed != $num_tests){
if ($opt_force){
# All test should have been run, print any that are still in $tests
#foreach my $test ( @$tests ){
# $test->print_test();
#}
}
# Not all tests completed, failure
mtr_report();
mtr_report("Only ", int(@$completed), " of $num_tests completed.");
mtr_error("Not all tests completed");
}
mtr_print_line();
if ( $opt_gcov ) {
gcov_collect($basedir, $opt_gcov_exe,
$opt_gcov_msg, $opt_gcov_err);
}
mtr_report_stats("Completed", $completed);
exit(0);
}
sub run_test_server ($$$) {
my ($server, $tests, $childs) = @_;
my $num_saved_cores= 0; # Number of core files saved in vardir/log/ so far.
my $num_saved_datadir= 0; # Number of datadirs saved in vardir/log/ so far.
my $num_failed_test= 0; # Number of tests failed so far
# Scheduler variables
my $max_ndb= $childs / 2;
$max_ndb = 4 if $max_ndb > 4;
$max_ndb = 1 if $max_ndb < 1;
my $num_ndb_tests= 0;
my $completed= [];
my %running;
my $result;
my $exe_mysqld= find_mysqld($basedir) || ""; # Used as hint to CoreDump
my $suite_timeout= start_timer(suite_timeout());
my $s= IO::Select->new();
$s->add($server);
while (1) {
my @ready = $s->can_read(1); # Wake up once every second
foreach my $sock (@ready) {
if ($sock == $server) {
# New client connected
my $child= $sock->accept();
mtr_verbose("Client connected");
$s->add($child);
print $child "HELLO\n";
}
else {
my $line= <$sock>;
if (!defined $line) {
# Client disconnected
mtr_verbose("Child closed socket");
$s->remove($sock);
if (--$childs == 0){
return $completed;
}
next;
}
chomp($line);
if ($line eq 'TESTRESULT'){
$result= My::Test::read_test($sock);
# $result->print_test();
# Report test status
mtr_report_test($result);
if ( $result->is_failed() ) {
# Save the workers "savedir" in var/log
my $worker_savedir= $result->{savedir};
my $worker_savename= basename($worker_savedir);
my $savedir= "$opt_vardir/log/$worker_savename";
if ($opt_max_save_datadir > 0 &&
$num_saved_datadir >= $opt_max_save_datadir)
{
mtr_report(" - skipping '$worker_savedir/'");
rmtree($worker_savedir);
}
else {
mtr_report(" - saving '$worker_savedir/' to '$savedir/'");
rename($worker_savedir, $savedir);
# Move any core files from e.g. mysqltest
foreach my $coref (glob("core*"), glob("*.dmp"))
{
mtr_report(" - found '$coref', moving it to '$savedir'");
move($coref, $savedir);
}
if ($opt_max_save_core > 0) {
# Limit number of core files saved
find({ no_chdir => 1,
wanted => sub {
my $core_file= $File::Find::name;
my $core_name= basename($core_file);
if ($core_name =~ /^core/ or # Starting with core
(IS_WINDOWS and $core_name =~ /\.dmp$/)){
# Ending with .dmp
mtr_report(" - found '$core_name'",
"($num_saved_cores/$opt_max_save_core)");
My::CoreDump->show($core_file, $exe_mysqld);
if ($num_saved_cores >= $opt_max_save_core) {
mtr_report(" - deleting it, already saved",
"$opt_max_save_core");
unlink("$core_file");
}
++$num_saved_cores;
}
}
},
$savedir);
}
}
$num_saved_datadir++;
$num_failed_test++ unless ($result->{retries} ||
$result->{exp_fail});
if ( !$opt_force ) {
# Test has failed, force is off
push(@$completed, $result);
return $completed unless $result->{'dont_kill_server'};
# Prevent kill of server, to get valgrind report
print $sock "BYE\n";
next;
}
elsif ($opt_max_test_fail > 0 and
$num_failed_test >= $opt_max_test_fail) {
push(@$completed, $result);
mtr_report_stats("Too many failed", $completed, 1);
mtr_report("Too many tests($num_failed_test) failed!",
"Terminating...");
return undef;
}
}
# Retry test run after test failure
my $retries= $result->{retries} || 2;
my $test_has_failed= $result->{failures} || 0;
if ($test_has_failed and $retries <= $opt_retry){
# Test should be run one more time unless it has failed
# too many times already
my $tname= $result->{name};
my $failures= $result->{failures};
if ($opt_retry > 1 and $failures >= $opt_retry_failure){
mtr_report("\nTest $tname has failed $failures times,",
"no more retries!\n");
}
else {
mtr_report("\nRetrying test $tname, ".
"attempt($retries/$opt_retry)...\n");
delete($result->{result});
$result->{retries}= $retries+1;
$result->write_test($sock, 'TESTCASE');
next;
}
}
# Repeat test $opt_repeat number of times
my $repeat= $result->{repeat} || 1;
# Don't repeat if test was skipped
if ($repeat < $opt_repeat && $result->{'result'} ne 'MTR_RES_SKIPPED')
{
$result->{retries}= 0;
$result->{rep_failures}++ if $result->{failures};
$result->{failures}= 0;
delete($result->{result});
$result->{repeat}= $repeat+1;
$result->write_test($sock, 'TESTCASE');
next;
}
# Remove from list of running
mtr_error("'", $result->{name},"' is not known to be running")
unless delete $running{$result->key()};
# Update scheduler variables
$num_ndb_tests-- if ($result->{ndb_test});
# Save result in completed list
push(@$completed, $result);
}
elsif ($line eq 'START'){
; # Send first test
}
else {
mtr_error("Unknown response: '$line' from client");
}
# Find next test to schedule
# - Try to use same configuration as worker used last time
# - Limit number of parallel ndb tests
my $next;
my $second_best;
for(my $i= 0; $i <= @$tests; $i++)
{
my $t= $tests->[$i];
last unless defined $t;
if (run_testcase_check_skip_test($t)){
# Move the test to completed list
#mtr_report("skip - Moving test $i to completed");
push(@$completed, splice(@$tests, $i, 1));
# Since the test at pos $i was taken away, next
# test will also be at $i -> redo
redo;
}
# Limit number of parallell NDB tests
if ($t->{ndb_test} and $num_ndb_tests >= $max_ndb){
#mtr_report("Skipping, num ndb is already at max, $num_ndb_tests");
next;
}
# Second best choice is the first that does not fulfill
# any of the above conditions
if (!defined $second_best){
#mtr_report("Setting second_best to $i");
$second_best= $i;
}
# Smart allocation of next test within this thread.
if ($opt_reorder and $opt_parallel > 1 and defined $result)
{
my $wid= $result->{worker};
# Reserved for other thread, try next
next if (defined $t->{reserved} and $t->{reserved} != $wid);
if (! defined $t->{reserved})
{
# Force-restart not relevant when comparing *next* test
$t->{criteria} =~ s/force-restart$/no-restart/;
my $criteria= $t->{criteria};
# Reserve similar tests for this worker, but not too many
my $maxres= (@$tests - $i) / $opt_parallel + 1;
for (my $j= $i+1; $j <= $i + $maxres; $j++)
{
my $tt= $tests->[$j];
last unless defined $tt;
last if $tt->{criteria} ne $criteria;
$tt->{reserved}= $wid;
}
}
}
# At this point we have found next suitable test
$next= splice(@$tests, $i, 1);
last;
}
# Use second best choice if no other test has been found
if (!$next and defined $second_best){
#mtr_report("Take second best choice $second_best");
mtr_error("Internal error, second best too large($second_best)")
if $second_best > $#$tests;
$next= splice(@$tests, $second_best, 1);
delete $next->{reserved};
}
if ($next) {
# We don't need this any more
delete $next->{criteria};
$next->write_test($sock, 'TESTCASE');
$running{$next->key()}= $next;
$num_ndb_tests++ if ($next->{ndb_test});
}
else {
# No more test, tell child to exit
#mtr_report("Saying BYE to child");
print $sock "BYE\n";
}
}
}
# ----------------------------------------------------
# Check if test suite timer expired
# ----------------------------------------------------
if ( has_expired($suite_timeout) )
{
mtr_report_stats("Timeout", $completed, 1);
mtr_report("Test suite timeout! Terminating...");
return undef;
}
}
}
sub run_worker ($) {
my ($server_port, $thread_num)= @_;
$SIG{INT}= sub { exit(1); };
# Connect to server
my $server = new IO::Socket::INET
(
PeerAddr => 'localhost',
PeerPort => $server_port,
Proto => 'tcp'
);
mtr_error("Could not connect to server at port $server_port: $!")
unless $server;
# --------------------------------------------------------------------------
# Set worker name
# --------------------------------------------------------------------------
report_option('name',"worker[$thread_num]");
# --------------------------------------------------------------------------
# Set different ports per thread
# --------------------------------------------------------------------------
set_build_thread_ports($thread_num);
# --------------------------------------------------------------------------
# Turn off verbosity in workers, unless explicitly specified
# --------------------------------------------------------------------------
report_option('verbose', undef) if ($opt_verbose == 0);
environment_setup();
# Read hello from server which it will send when shared
# resources have been setup
my $hello= <$server>;
setup_vardir();
check_running_as_root();
if ( using_extern() ) {
create_config_file_for_extern(%opts_extern);
}
# Ask server for first test
print $server "START\n";
while(my $line= <$server>){
chomp($line);
if ($line eq 'TESTCASE'){
my $test= My::Test::read_test($server);
#$test->print_test();
# Clear comment and logfile, to avoid
# reusing them from previous test
delete($test->{'comment'});
delete($test->{'logfile'});
# A sanity check. Should this happen often we need to look at it.
if (defined $test->{reserved} && $test->{reserved} != $thread_num) {
my $tres= $test->{reserved};
mtr_warning("Test reserved for w$tres picked up by w$thread_num");
}
$test->{worker} = $thread_num if $opt_parallel > 1;
run_testcase($test);
#$test->{result}= 'MTR_RES_PASSED';
# Send it back, now with results set
#$test->print_test();
$test->write_test($server, 'TESTRESULT');
}
elsif ($line eq 'BYE'){
mtr_report("Server said BYE");
stop_all_servers($opt_shutdown_timeout);
my $valgrind_reports= 0;
if ($opt_valgrind_mysqld) {
$valgrind_reports= valgrind_exit_reports();
}
if ( $opt_gprof ) {
gprof_collect (find_mysqld($basedir), keys %gprof_dirs);
}
exit($valgrind_reports);
}
else {
mtr_error("Could not understand server, '$line'");
}
}
stop_all_servers();
exit(1);
}
sub ignore_option {
my ($opt, $value)= @_;
mtr_report("Ignoring option '$opt'");
}
# Setup any paths that are $opt_vardir related
sub set_vardir {
my ($vardir)= @_;
$opt_vardir= $vardir;
$path_vardir_trace= $opt_vardir;
# Chop off any "c:", DBUG likes a unix path ex: c:/src/... => /src/...
$path_vardir_trace=~ s/^\w://;
# Location of my.cnf that all clients use
$path_config_file= "$opt_vardir/my.cnf";
$path_testlog= "$opt_vardir/log/mysqltest.log";
$path_current_testlog= "$opt_vardir/log/current_test";
}
sub command_line_setup {
my $opt_comment;
my $opt_usage;
my $opt_list_options;
# Read the command line options
# Note: Keep list in sync with usage at end of this file
Getopt::Long::Configure("pass_through");
my %options=(
# Control what engine/variation to run
'embedded-server' => \$opt_embedded_server,
'ps-protocol' => \$opt_ps_protocol,
'sp-protocol' => \$opt_sp_protocol,
'view-protocol' => \$opt_view_protocol,
'cursor-protocol' => \$opt_cursor_protocol,
'ssl|with-openssl' => \$opt_ssl,
'skip-ssl' => \$opt_skip_ssl,
'compress' => \$opt_compress,
'vs-config=s' => \$opt_vs_config,
# Max number of parallel threads to use
'parallel=s' => \$opt_parallel,
# Config file to use as template for all tests
'defaults-file=s' => \&collect_option,
# Extra config file to append to all generated configs
'defaults-extra-file=s' => \&collect_option,
# Control what test suites or cases to run
'force' => \$opt_force,
'with-ndbcluster-only' => \&collect_option,
'include-ndbcluster' => \$opt_include_ndbcluster,
'skip-ndbcluster|skip-ndb' => \$opt_skip_ndbcluster,
'suite|suites=s' => \$opt_suites,
'skip-rpl' => \&collect_option,
'skip-test=s' => \&collect_option,
'do-test=s' => \&collect_option,
'start-from=s' => \&collect_option,
'big-test' => \$opt_big_test,
'combination=s' => \@opt_combinations,
'skip-combinations' => \&collect_option,
'experimental=s' => \@opt_experimentals,
# skip-im is deprecated and silently ignored
'skip-im' => \&ignore_option,
# Specify ports
'build-thread|mtr-build-thread=i' => \$opt_build_thread,
'port-base|mtr-port-base=i' => \$opt_port_base,
# Test case authoring
'record' => \$opt_record,
'check-testcases!' => \$opt_check_testcases,
'mark-progress' => \$opt_mark_progress,
# Extra options used when starting mysqld
'mysqld=s' => \@opt_extra_mysqld_opt,
# Run test on running server
'extern=s' => \%opts_extern, # Append to hash
# Debugging
'debug' => \$opt_debug,
'debug-server' => \$opt_debug_server,
'gdb' => \$opt_gdb,
'client-gdb' => \$opt_client_gdb,
'manual-gdb' => \$opt_manual_gdb,
'manual-debug' => \$opt_manual_debug,
'ddd' => \$opt_ddd,
'client-ddd' => \$opt_client_ddd,
'manual-ddd' => \$opt_manual_ddd,
'debugger=s' => \$opt_debugger,
'client-debugger=s' => \$opt_client_debugger,
'strace-client:s' => \$opt_strace_client,
'max-save-core=i' => \$opt_max_save_core,
'max-save-datadir=i' => \$opt_max_save_datadir,
'max-test-fail=i' => \$opt_max_test_fail,
# Coverage, profiling etc
'gcov' => \$opt_gcov,
'gprof' => \$opt_gprof,
'valgrind|valgrind-all' => \$opt_valgrind,
'valgrind-mysqltest' => \$opt_valgrind_mysqltest,
'valgrind-mysqld' => \$opt_valgrind_mysqld,
'valgrind-options=s' => sub {
my ($opt, $value)= @_;
# Deprecated option unless it's what we know pushbuild uses
if ($value eq "--gen-suppressions=all --show-reachable=yes") {
push(@valgrind_args, $_) for (split(' ', $value));
return;
}
die("--valgrind-options=s is deprecated. Use ",
"--valgrind-option=s, to be specified several",
" times if necessary");
},
'valgrind-option=s' => \@valgrind_args,
'valgrind-path=s' => \$opt_valgrind_path,
'callgrind' => \$opt_callgrind,
'debug-sync-timeout=i' => \$opt_debug_sync_timeout,
# Directories
'tmpdir=s' => \$opt_tmpdir,
'vardir=s' => \$opt_vardir,
'mem' => \$opt_mem,
'client-bindir=s' => \$path_client_bindir,
'client-libdir=s' => \$path_client_libdir,
# Misc
'report-features' => \$opt_report_features,
'comment=s' => \$opt_comment,
'fast' => \$opt_fast,
'force-restart' => \$opt_force_restart,
'reorder!' => \$opt_reorder,
'enable-disabled' => \&collect_option,
'verbose+' => \$opt_verbose,
'verbose-restart' => \&report_option,
'sleep=i' => \$opt_sleep,
'start-dirty' => \$opt_start_dirty,
'start-and-exit' => \$opt_start_exit,
'start' => \$opt_start,
'user-args' => \$opt_user_args,
'wait-all' => \$opt_wait_all,
'print-testcases' => \&collect_option,
'repeat=i' => \$opt_repeat,
'retry=i' => \$opt_retry,
'retry-failure=i' => \$opt_retry_failure,
'timer!' => \&report_option,
'user=s' => \$opt_user,
'testcase-timeout=i' => \$opt_testcase_timeout,
'suite-timeout=i' => \$opt_suite_timeout,
'shutdown-timeout=i' => \$opt_shutdown_timeout,
'warnings!' => \$opt_warnings,
'timestamp' => \&report_option,
'timediff' => \&report_option,
'max-connections=i' => \$opt_max_connections,
'help|h' => \$opt_usage,
# list-options is internal, not listed in help
'list-options' => \$opt_list_options,
);
GetOptions(%options) or usage("Can't read options");
usage("") if $opt_usage;
list_options(\%options) if $opt_list_options;
# --------------------------------------------------------------------------
# Setup verbosity
# --------------------------------------------------------------------------
if ($opt_verbose != 0){
report_option('verbose', $opt_verbose);
}
if ( -d "../sql" )
{
$source_dist= 1;
}
# Find the absolute path to the test directory
$glob_mysql_test_dir= cwd();
if ($glob_mysql_test_dir =~ / /)
{
die("Working directory \"$glob_mysql_test_dir\" contains space\n".
"Bailing out, cannot function properly with space in path");
}
if (IS_CYGWIN)
{
# Use mixed path format i.e c:/path/to/
$glob_mysql_test_dir= mixed_path($glob_mysql_test_dir);
}
# In most cases, the base directory we find everything relative to,
# is the parent directory of the "mysql-test" directory. For source
# distributions, TAR binary distributions and some other packages.
$basedir= dirname($glob_mysql_test_dir);
# In the RPM case, binaries and libraries are installed in the
# default system locations, instead of having our own private base
# directory. And we install "/usr/share/mysql-test". Moving up one
# more directory relative to "mysql-test" gives us a usable base
# directory for RPM installs.
if ( ! $source_dist and ! -d "$basedir/bin" )
{
$basedir= dirname($basedir);
}
# Look for the client binaries directory
if ($path_client_bindir)
{
# --client-bindir=path set on command line, check that the path exists
$path_client_bindir= mtr_path_exists($path_client_bindir);
}
else
{
$path_client_bindir= mtr_path_exists("$basedir/client_release",
"$basedir/client_debug",
vs_config_dirs('client', ''),
"$basedir/client",
"$basedir/bin");
}
# Look for language files and charsetsdir, use same share
$path_language= mtr_path_exists("$basedir/share/mysql/english",
"$basedir/sql/share/english",
"$basedir/share/english");
my $path_share= dirname($path_language);
$path_charsetsdir= mtr_path_exists("$path_share/charsets");
# --debug implies we run debug server
$opt_debug_server= 1 if $opt_debug;
if (using_extern())
{
# Connect to the running mysqld and find out what it supports
collect_mysqld_features_from_running_server();
}
else
{
# Run the mysqld to find out what features are available
collect_mysqld_features();
}
if ( $opt_comment )
{
mtr_report();
mtr_print_thick_line('#');
mtr_report("# $opt_comment");
mtr_print_thick_line('#');
}
if ( @opt_experimentals )
{
# $^O on Windows considered not generic enough
my $plat= (IS_WINDOWS) ? 'windows' : $^O;
# read the list of experimental test cases from the files specified on
# the command line
$experimental_test_cases = [];
foreach my $exp_file (@opt_experimentals)
{
open(FILE, "<", $exp_file)
or mtr_error("Can't read experimental file: $exp_file");
mtr_report("Using experimental file: $exp_file");
while(<FILE>) {
chomp;
# remove comments (# foo) at the beginning of the line, or after a
# blank at the end of the line
s/(\s+|^)#.*$//;
# If @ platform specifier given, use this entry only if it contains
# @<platform> or @!<xxx> where xxx != platform
if (/\@.*/)
{
next if (/\@!$plat/);
next unless (/\@$plat/ or /\@!/);
# Then remove @ and everything after it
s/\@.*$//;
}
# remove whitespace
s/^\s+//;
s/\s+$//;
# if nothing left, don't need to remember this line
if ( $_ eq "" ) {
next;
}
# remember what is left as the name of another test case that should be
# treated as experimental
print " - $_\n";
push @$experimental_test_cases, $_;
}
close FILE;
}
}
foreach my $arg ( @ARGV )
{
if ( $arg =~ /^--skip-/ )
{
push(@opt_extra_mysqld_opt, $arg);
}
elsif ( $arg =~ /^--$/ )
{
# It is an effect of setting 'pass_through' in option processing
# that the lone '--' separating options from arguments survives,
# simply ignore it.
}
elsif ( $arg =~ /^-/ )
{
usage("Invalid option \"$arg\"");
}
else
{
push(@opt_cases, $arg);
}
}
# --------------------------------------------------------------------------
# Find out type of logging that are being used
# --------------------------------------------------------------------------
foreach my $arg ( @opt_extra_mysqld_opt )
{
if ( $arg =~ /binlog[-_]format=(\S+)/ )
{
# Save this for collect phase
collect_option('binlog-format', $1);
mtr_report("Using binlog format '$1'");
}
}
# --------------------------------------------------------------------------
# Find out default storage engine being used(if any)
# --------------------------------------------------------------------------
foreach my $arg ( @opt_extra_mysqld_opt )
{
if ( $arg =~ /default-storage-engine=(\S+)/ )
{
# Save this for collect phase
collect_option('default-storage-engine', $1);
mtr_report("Using default engine '$1'")
}
}
if (IS_WINDOWS and defined $opt_mem) {
mtr_report("--mem not supported on Windows, ignored");
$opt_mem= undef;
}
if ($opt_port_base ne "auto")
{
if (my $rem= $opt_port_base % 10)
{
mtr_warning ("Port base $opt_port_base rounded down to multiple of 10");
$opt_port_base-= $rem;
}
$opt_build_thread= $opt_port_base / 10 - 1000;
}
# --------------------------------------------------------------------------
# Check if we should speed up tests by trying to run on tmpfs
# --------------------------------------------------------------------------
if ( defined $opt_mem)
{
mtr_error("Can't use --mem and --vardir at the same time ")
if $opt_vardir;
mtr_error("Can't use --mem and --tmpdir at the same time ")
if $opt_tmpdir;
# Search through list of locations that are known
# to be "fast disks" to find a suitable location
# Use --mem=<dir> as first location to look.
my @tmpfs_locations= ($opt_mem, "/dev/shm", "/tmp");
foreach my $fs (@tmpfs_locations)
{
if ( -d $fs )
{
my $template= "var_${opt_build_thread}_XXXX";
$opt_mem= tempdir( $template, DIR => $fs, CLEANUP => 0);
last;
}
}
}
# --------------------------------------------------------------------------
# Set the "var/" directory, the base for everything else
# --------------------------------------------------------------------------
$default_vardir= "$glob_mysql_test_dir/var";
if ( ! $opt_vardir )
{
$opt_vardir= $default_vardir;
}
# We make the path absolute, as the server will do a chdir() before usage
unless ( $opt_vardir =~ m,^/, or
(IS_WINDOWS and $opt_vardir =~ m,^[a-z]:/,i) )
{
# Make absolute path, relative test dir
$opt_vardir= "$glob_mysql_test_dir/$opt_vardir";
}
set_vardir($opt_vardir);
# --------------------------------------------------------------------------
# Set the "tmp" directory
# --------------------------------------------------------------------------
if ( ! $opt_tmpdir )
{
$opt_tmpdir= "$opt_vardir/tmp" unless $opt_tmpdir;
if (check_socket_path_length("$opt_tmpdir/mysql_testsocket.sock"))
{
mtr_report("Too long tmpdir path '$opt_tmpdir'",
" creating a shorter one...");
# Create temporary directory in standard location for temporary files
$opt_tmpdir= tempdir( TMPDIR => 1, CLEANUP => 0 );
mtr_report(" - using tmpdir: '$opt_tmpdir'\n");
# Remember pid that created dir so it's removed by correct process
$opt_tmpdir_pid= $$;
}
}
$opt_tmpdir =~ s,/+$,,; # Remove ending slash if any
# --------------------------------------------------------------------------
# fast option
# --------------------------------------------------------------------------
if ($opt_fast){
$opt_shutdown_timeout= 0; # Kill processes instead of nice shutdown
}
# --------------------------------------------------------------------------
# Check parallel value
# --------------------------------------------------------------------------
if ($opt_parallel ne "auto" && $opt_parallel < 1)
{
mtr_error("0 or negative parallel value makes no sense, use 'auto' or positive number");
}
# --------------------------------------------------------------------------
# Record flag
# --------------------------------------------------------------------------
if ( $opt_record and ! @opt_cases )
{
mtr_error("Will not run in record mode without a specific test case");
}
if ( $opt_record ) {
# Use only one worker with --record
$opt_parallel= 1;
}
# --------------------------------------------------------------------------
# Embedded server flag
# --------------------------------------------------------------------------
if ( $opt_embedded_server )
{
if ( IS_WINDOWS )
{
# Add the location for libmysqld.dll to the path.
my $separator= ";";
my $lib_mysqld=
mtr_path_exists(vs_config_dirs('libmysqld',''));
if ( IS_CYGWIN )
{
$lib_mysqld= posix_path($lib_mysqld);
$separator= ":";
}
$ENV{'PATH'}= "$ENV{'PATH'}".$separator.$lib_mysqld;
}
$opt_skip_ndbcluster= 1; # Turn off use of NDB cluster
$opt_skip_ssl= 1; # Turn off use of SSL
# Turn off use of bin log
push(@opt_extra_mysqld_opt, "--skip-log-bin");
if ( using_extern() )
{
mtr_error("Can't use --extern with --embedded-server");
}
if ($opt_gdb)
{
mtr_warning("Silently converting --gdb to --client-gdb in embedded mode");
$opt_client_gdb= $opt_gdb;
$opt_gdb= undef;
}
if ($opt_ddd)
{
mtr_warning("Silently converting --ddd to --client-ddd in embedded mode");
$opt_client_ddd= $opt_ddd;
$opt_ddd= undef;
}
if ($opt_debugger)
{
mtr_warning("Silently converting --debugger to --client-debugger in embedded mode");
$opt_client_debugger= $opt_debugger;
$opt_debugger= undef;
}
if ( $opt_gdb || $opt_ddd || $opt_manual_gdb || $opt_manual_ddd ||
$opt_manual_debug || $opt_debugger )
{
mtr_error("You need to use the client debug options for the",
"embedded server. Ex: --client-gdb");
}
}
# --------------------------------------------------------------------------
# Big test flags
# --------------------------------------------------------------------------
if ( $opt_big_test )
{
$ENV{'BIG_TEST'}= 1;
}
# --------------------------------------------------------------------------
# Gcov flag
# --------------------------------------------------------------------------
if ( ($opt_gcov or $opt_gprof) and ! $source_dist )
{
mtr_error("Coverage test needs the source - please use source dist");
}
# --------------------------------------------------------------------------
# Check debug related options
# --------------------------------------------------------------------------
if ( $opt_gdb || $opt_client_gdb || $opt_ddd || $opt_client_ddd ||
$opt_manual_gdb || $opt_manual_ddd || $opt_manual_debug ||
$opt_debugger || $opt_client_debugger )
{
# Indicate that we are using debugger
$glob_debugger= 1;
if ( using_extern() )
{
mtr_error("Can't use --extern when using debugger");
}
# Set one week timeout (check-testcase timeout will be 1/10th)
$opt_testcase_timeout= 7 * 24 * 60;
$opt_suite_timeout= 7 * 24 * 60;
# One day to shutdown
$opt_shutdown_timeout= 24 * 60;
# One day for PID file creation (this is given in seconds not minutes)
$opt_start_timeout= 24 * 60 * 60;
}
# --------------------------------------------------------------------------
# Modified behavior with --start options
# --------------------------------------------------------------------------
if ($opt_start or $opt_start_dirty or $opt_start_exit) {
collect_option ('quick-collect', 1);
$start_only= 1;
}
# --------------------------------------------------------------------------
# Check use of user-args
# --------------------------------------------------------------------------
if ($opt_user_args) {
mtr_error("--user-args only valid with --start options")
unless $start_only;
mtr_error("--user-args cannot be combined with named suites or tests")
if $opt_suites || @opt_cases;
}
# --------------------------------------------------------------------------
# Check use of wait-all
# --------------------------------------------------------------------------
if ($opt_wait_all && ! $start_only)
{
mtr_error("--wait-all can only be used with --start options");
}
# --------------------------------------------------------------------------
# Check timeout arguments
# --------------------------------------------------------------------------
mtr_error("Invalid value '$opt_testcase_timeout' supplied ".
"for option --testcase-timeout")
if ($opt_testcase_timeout <= 0);
mtr_error("Invalid value '$opt_suite_timeout' supplied ".
"for option --testsuite-timeout")
if ($opt_suite_timeout <= 0);
# --------------------------------------------------------------------------
# Check valgrind arguments
# --------------------------------------------------------------------------
if ( $opt_valgrind or $opt_valgrind_path or @valgrind_args)
{
mtr_report("Turning on valgrind for all executables");
$opt_valgrind= 1;
$opt_valgrind_mysqld= 1;
$opt_valgrind_mysqltest= 1;
# Increase the timeouts when running with valgrind
$opt_testcase_timeout*= 10;
$opt_suite_timeout*= 6;
$opt_start_timeout*= 10;
}
elsif ( $opt_valgrind_mysqld )
{
mtr_report("Turning on valgrind for mysqld(s) only");
$opt_valgrind= 1;
}
elsif ( $opt_valgrind_mysqltest )
{
mtr_report("Turning on valgrind for mysqltest and mysql_client_test only");
$opt_valgrind= 1;
}
if ( $opt_callgrind )
{
mtr_report("Turning on valgrind with callgrind for mysqld(s)");
$opt_valgrind= 1;
$opt_valgrind_mysqld= 1;
# Set special valgrind options unless options passed on command line
push(@valgrind_args, "--trace-children=yes")
unless @valgrind_args;
}
if ( $opt_valgrind )
{
# Set valgrind_options to default unless already defined
push(@valgrind_args, @default_valgrind_args)
unless @valgrind_args;
# Don't add --quiet; you will loose the summary reports.
mtr_report("Running valgrind with options \"",
join(" ", @valgrind_args), "\"");
}
mtr_report("Checking supported features...");
check_ndbcluster_support(\%mysqld_variables);
check_ssl_support(\%mysqld_variables);
check_debug_support(\%mysqld_variables);
executable_setup();
}
#
# To make it easier for different devs to work on the same host,
# an environment variable can be used to control all ports. A small
# number is to be used, 0 - 16 or similar.
#
# Note the MASTER_MYPORT has to be set the same in all 4.x and 5.x
# versions of this script, else a 4.0 test run might conflict with a
# 5.1 test run, even if different MTR_BUILD_THREAD is used. This means
# all port numbers might not be used in this version of the script.
#
# Also note the limitation of ports we are allowed to hand out. This
# differs between operating systems and configuration, see
# http://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html
# But a fairly safe range seems to be 5001 - 32767
#
sub set_build_thread_ports($) {
my $thread= shift || 0;
if ( lc($opt_build_thread) eq 'auto' ) {
my $found_free = 0;
$build_thread = 300; # Start attempts from here
while (! $found_free)
{
$build_thread= mtr_get_unique_id($build_thread, 349);
if ( !defined $build_thread ) {
mtr_error("Could not get a unique build thread id");
}
$found_free= check_ports_free($build_thread);
# If not free, release and try from next number
if (! $found_free) {
mtr_release_unique_id();
$build_thread++;
}
}
}
else
{
$build_thread = $opt_build_thread + $thread - 1;
if (! check_ports_free($build_thread)) {
# Some port was not free(which one has already been printed)
mtr_error("Some port(s) was not free")
}
}
$ENV{MTR_BUILD_THREAD}= $build_thread;
# Calculate baseport
$baseport= $build_thread * 10 + 10000;
if ( $baseport < 5001 or $baseport + 9 >= 32767 )
{
mtr_error("MTR_BUILD_THREAD number results in a port",
"outside 5001 - 32767",
"($baseport - $baseport + 9)");
}
mtr_report("Using MTR_BUILD_THREAD $build_thread,",
"with reserved ports $baseport..".($baseport+9));
}
sub collect_mysqld_features {
my $found_variable_list_start= 0;
my $use_tmpdir;
if ( defined $opt_tmpdir and -d $opt_tmpdir){
# Create the tempdir in $opt_tmpdir
$use_tmpdir= $opt_tmpdir;
}
my $tmpdir= tempdir(CLEANUP => 0, # Directory removed by this function
DIR => $use_tmpdir);
#
# Execute "mysqld --no-defaults --help --verbose" to get a
# list of all features and settings
#
# --no-defaults and --skip-grant-tables are to avoid loading
# system-wide configs and plugins
#
# --datadir must exist, mysqld will chdir into it
#
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--no-defaults");
mtr_add_arg($args, "--datadir=%s", mixed_path($tmpdir));
mtr_add_arg($args, "--language=%s", $path_language);
mtr_add_arg($args, "--skip-grant-tables");
mtr_add_arg($args, "--verbose");
mtr_add_arg($args, "--help");
# Need --user=root if running as *nix root user
if (!IS_WINDOWS and $> == 0)
{
mtr_add_arg($args, "--user=root");
}
my $exe_mysqld= find_mysqld($basedir);
my $cmd= join(" ", $exe_mysqld, @$args);
my $list= `$cmd`;
foreach my $line (split('\n', $list))
{
# First look for version
if ( !$mysql_version_id )
{
# Look for version
my $exe_name= basename($exe_mysqld);
mtr_verbose("exe_name: $exe_name");
if ( $line =~ /^\S*$exe_name\s\sVer\s([0-9]*)\.([0-9]*)\.([0-9]*)/ )
{
#print "Major: $1 Minor: $2 Build: $3\n";
$mysql_version_id= $1*10000 + $2*100 + $3;
#print "mysql_version_id: $mysql_version_id\n";
mtr_report("MySQL Version $1.$2.$3");
}
}
else
{
if (!$found_variable_list_start)
{
# Look for start of variables list
if ( $line =~ /[\-]+\s[\-]+/ )
{
$found_variable_list_start= 1;
}
}
else
{
# Put variables into hash
if ( $line =~ /^([\S]+)[ \t]+(.*?)\r?$/ )
{
# print "$1=\"$2\"\n";
$mysqld_variables{$1}= $2;
}
else
{
# The variable list is ended with a blank line
if ( $line =~ /^[\s]*$/ )
{
last;
}
else
{
# Send out a warning, we should fix the variables that has no
# space between variable name and it's value
# or should it be fixed width column parsing? It does not
# look like that in function my_print_variables in my_getopt.c
mtr_warning("Could not parse variable list line : $line");
}
}
}
}
}
rmtree($tmpdir);
mtr_error("Could not find version of MySQL") unless $mysql_version_id;
mtr_error("Could not find variabes list") unless $found_variable_list_start;
}
sub collect_mysqld_features_from_running_server ()
{
my $mysql= mtr_exe_exists("$path_client_bindir/mysql");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--no-defaults");
mtr_add_arg($args, "--user=%s", $opt_user);
while (my ($option, $value)= each( %opts_extern )) {
mtr_add_arg($args, "--$option=$value");
}
mtr_add_arg($args, "--silent"); # Tab separated output
mtr_add_arg($args, "-e '%s'", "use mysql; SHOW VARIABLES");
my $cmd= "$mysql " . join(' ', @$args);
mtr_verbose("cmd: $cmd");
my $list = `$cmd` or
mtr_error("Could not connect to extern server using command: '$cmd'");
foreach my $line (split('\n', $list ))
{
# Put variables into hash
if ( $line =~ /^([\S]+)[ \t]+(.*?)\r?$/ )
{
# print "$1=\"$2\"\n";
$mysqld_variables{$1}= $2;
}
}
# "Convert" innodb flag
$mysqld_variables{'innodb'}= "ON"
if ($mysqld_variables{'have_innodb'} eq "YES");
# Parse version
my $version_str= $mysqld_variables{'version'};
if ( $version_str =~ /^([0-9]*)\.([0-9]*)\.([0-9]*)/ )
{
#print "Major: $1 Minor: $2 Build: $3\n";
$mysql_version_id= $1*10000 + $2*100 + $3;
#print "mysql_version_id: $mysql_version_id\n";
mtr_report("MySQL Version $1.$2.$3");
}
mtr_error("Could not find version of MySQL") unless $mysql_version_id;
}
sub find_mysqld {
my ($mysqld_basedir)= @_;
my @mysqld_names= ("mysqld", "mysqld-max-nt", "mysqld-max",
"mysqld-nt");
if ( $opt_debug_server ){
# Put mysqld-debug first in the list of binaries to look for
mtr_verbose("Adding mysqld-debug first in list of binaries to look for");
unshift(@mysqld_names, "mysqld-debug");
}
return my_find_bin($mysqld_basedir,
["sql", "libexec", "sbin", "bin"],
[@mysqld_names]);
}
sub executable_setup () {
#
# Check if libtool is available in this distribution/clone
# we need it when valgrinding or debugging non installed binary
# Otherwise valgrind will valgrind the libtool wrapper or bash
# and gdb will not find the real executable to debug
#
if ( -x "../libtool")
{
$exe_libtool= "../libtool";
if ($opt_valgrind or $glob_debugger)
{
mtr_report("Using \"$exe_libtool\" when running valgrind or debugger");
}
}
# Look for the client binaries
$exe_mysqladmin= mtr_exe_exists("$path_client_bindir/mysqladmin");
$exe_mysql= mtr_exe_exists("$path_client_bindir/mysql");
if ( ! $opt_skip_ndbcluster )
{
$exe_ndbd=
my_find_bin($basedir,
["storage/ndb/src/kernel", "libexec", "sbin", "bin"],
"ndbd");
$exe_ndb_mgmd=
my_find_bin($basedir,
["storage/ndb/src/mgmsrv", "libexec", "sbin", "bin"],
"ndb_mgmd");
$exe_ndb_waiter=
my_find_bin($basedir,
["storage/ndb/tools/", "bin"],
"ndb_waiter");
}
# Look for mysqltest executable
if ( $opt_embedded_server )
{
$exe_mysqltest=
mtr_exe_exists(vs_config_dirs('libmysqld/examples','mysqltest_embedded'),
"$basedir/libmysqld/examples/mysqltest_embedded",
"$path_client_bindir/mysqltest_embedded");
}
else
{
$exe_mysqltest= mtr_exe_exists("$path_client_bindir/mysqltest");
}
}
sub client_debug_arg($$) {
my ($args, $client_name)= @_;
# Workaround for Bug #50627: drop any debug opt
return if $client_name =~ /^mysqlbinlog/;
if ( $opt_debug ) {
mtr_add_arg($args,
"--loose-debug=d:t:A,%s/log/%s.trace",
$path_vardir_trace, $client_name)
}
}
sub mysql_fix_arguments () {
return "" if ( IS_WINDOWS );
my $exe=
mtr_script_exists("$basedir/scripts/mysql_fix_privilege_tables",
"$path_client_bindir/mysql_fix_privilege_tables");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--basedir=%s", $basedir);
mtr_add_arg($args, "--bindir=%s", $path_client_bindir);
mtr_add_arg($args, "--verbose");
return mtr_args2str($exe, @$args);
}
sub client_arguments ($;$) {
my $client_name= shift;
my $group_suffix= shift;
my $client_exe= mtr_exe_exists("$path_client_bindir/$client_name");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
if (defined($group_suffix)) {
mtr_add_arg($args, "--defaults-group-suffix=%s", $group_suffix);
client_debug_arg($args, "$client_name-$group_suffix");
}
else
{
client_debug_arg($args, $client_name);
}
return mtr_args2str($client_exe, @$args);
}
sub mysqlslap_arguments () {
my $exe= mtr_exe_maybe_exists("$path_client_bindir/mysqlslap");
if ( $exe eq "" ) {
# mysqlap was not found
if (defined $mysql_version_id and $mysql_version_id >= 50100 ) {
mtr_error("Could not find the mysqlslap binary");
}
return ""; # Don't care about mysqlslap
}
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
client_debug_arg($args, "mysqlslap");
return mtr_args2str($exe, @$args);
}
sub mysqldump_arguments ($) {
my($group_suffix) = @_;
my $exe= mtr_exe_exists("$path_client_bindir/mysqldump");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $group_suffix);
client_debug_arg($args, "mysqldump-$group_suffix");
return mtr_args2str($exe, @$args);
}
sub mysql_client_test_arguments(){
my $exe;
# mysql_client_test executable may _not_ exist
if ( $opt_embedded_server ) {
$exe= mtr_exe_maybe_exists(
vs_config_dirs('libmysqld/examples','mysql_client_test_embedded'),
"$basedir/libmysqld/examples/mysql_client_test_embedded",
"$basedir/bin/mysql_client_test_embedded");
} else {
$exe= mtr_exe_maybe_exists(vs_config_dirs('tests', 'mysql_client_test'),
"$basedir/tests/mysql_client_test",
"$basedir/bin/mysql_client_test");
}
my $args;
mtr_init_args(\$args);
if ( $opt_valgrind_mysqltest ) {
valgrind_arguments($args, \$exe);
}
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--testcase");
mtr_add_arg($args, "--vardir=$opt_vardir");
client_debug_arg($args,"mysql_client_test");
return mtr_args2str($exe, @$args);
}
#
# Set environment to be used by childs of this process for
# things that are constant during the whole lifetime of mysql-test-run
#
sub environment_setup {
umask(022);
my @ld_library_paths;
if ($path_client_libdir)
{
# Use the --client-libdir passed on commandline
push(@ld_library_paths, "$path_client_libdir");
}
else
{
# Setup LD_LIBRARY_PATH so the libraries from this distro/clone
# are used in favor of the system installed ones
if ( $source_dist )
{
push(@ld_library_paths, "$basedir/libmysql/.libs/",
"$basedir/libmysql_r/.libs/",
"$basedir/zlib/.libs/");
}
else
{
push(@ld_library_paths, "$basedir/lib", "$basedir/lib/mysql");
}
}
# --------------------------------------------------------------------------
# Add the path where libndbclient can be found
# --------------------------------------------------------------------------
if ( !$opt_skip_ndbcluster )
{
push(@ld_library_paths, "$basedir/storage/ndb/src/.libs");
}
# --------------------------------------------------------------------------
# Add the path where mysqld will find udf_example.so
# --------------------------------------------------------------------------
my $lib_udf_example=
mtr_file_exists(vs_config_dirs('sql', 'udf_example.dll'),
"$basedir/sql/.libs/udf_example.so",);
if ( $lib_udf_example )
{
push(@ld_library_paths, dirname($lib_udf_example));
}
$ENV{'UDF_EXAMPLE_LIB'}=
($lib_udf_example ? basename($lib_udf_example) : "");
$ENV{'UDF_EXAMPLE_LIB_OPT'}= "--plugin-dir=".
($lib_udf_example ? dirname($lib_udf_example) : "");
# --------------------------------------------------------------------------
# Add the path where mysqld will find ha_example.so
# --------------------------------------------------------------------------
if ($mysql_version_id >= 50100) {
my $plugin_filename;
if (IS_WINDOWS)
{
$plugin_filename = "ha_example.dll";
}
else
{
$plugin_filename = "ha_example.so";
}
my $lib_example_plugin=
mtr_file_exists(vs_config_dirs('storage/example',$plugin_filename),
"$basedir/storage/example/.libs/".$plugin_filename,
"$basedir/lib/mysql/plugin/".$plugin_filename);
$ENV{'EXAMPLE_PLUGIN'}=
($lib_example_plugin ? basename($lib_example_plugin) : "");
$ENV{'EXAMPLE_PLUGIN_OPT'}= "--plugin-dir=".
($lib_example_plugin ? dirname($lib_example_plugin) : "");
$ENV{'HA_EXAMPLE_SO'}="'".$plugin_filename."'";
$ENV{'EXAMPLE_PLUGIN_LOAD'}="--plugin_load=EXAMPLE=".$plugin_filename;
}
# ----------------------------------------------------
# Add the path where mysqld will find mypluglib.so
# ----------------------------------------------------
my $lib_simple_parser=
mtr_file_exists(vs_config_dirs('plugin/fulltext', 'mypluglib.dll'),
"$basedir/plugin/fulltext/.libs/mypluglib.so",);
$ENV{'SIMPLE_PARSER'}=
($lib_simple_parser ? basename($lib_simple_parser) : "");
$ENV{'SIMPLE_PARSER_OPT'}= "--plugin-dir=".
($lib_simple_parser ? dirname($lib_simple_parser) : "");
# --------------------------------------------------------------------------
# Valgrind need to be run with debug libraries otherwise it's almost
# impossible to add correct supressions, that means if "/usr/lib/debug"
# is available, it should be added to
# LD_LIBRARY_PATH
#
# But pthread is broken in libc6-dbg on Debian <= 3.1 (see Debian
# bug 399035, http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=399035),
# so don't change LD_LIBRARY_PATH on that platform.
# --------------------------------------------------------------------------
my $debug_libraries_path= "/usr/lib/debug";
my $deb_version;
if ( $opt_valgrind and -d $debug_libraries_path and
(! -e '/etc/debian_version' or
($deb_version=
mtr_grab_file('/etc/debian_version')) !~ /^[0-9]+\.[0-9]$/ or
$deb_version > 3.1 ) )
{
push(@ld_library_paths, $debug_libraries_path);
}
$ENV{'LD_LIBRARY_PATH'}= join(":", @ld_library_paths,
$ENV{'LD_LIBRARY_PATH'} ?
split(':', $ENV{'LD_LIBRARY_PATH'}) : ());
mtr_debug("LD_LIBRARY_PATH: $ENV{'LD_LIBRARY_PATH'}");
$ENV{'DYLD_LIBRARY_PATH'}= join(":", @ld_library_paths,
$ENV{'DYLD_LIBRARY_PATH'} ?
split(':', $ENV{'DYLD_LIBRARY_PATH'}) : ());
mtr_debug("DYLD_LIBRARY_PATH: $ENV{'DYLD_LIBRARY_PATH'}");
# The environment variable used for shared libs on AIX
$ENV{'SHLIB_PATH'}= join(":", @ld_library_paths,
$ENV{'SHLIB_PATH'} ?
split(':', $ENV{'SHLIB_PATH'}) : ());
mtr_debug("SHLIB_PATH: $ENV{'SHLIB_PATH'}");
# The environment variable used for shared libs on hp-ux
$ENV{'LIBPATH'}= join(":", @ld_library_paths,
$ENV{'LIBPATH'} ?
split(':', $ENV{'LIBPATH'}) : ());
mtr_debug("LIBPATH: $ENV{'LIBPATH'}");
$ENV{'CHARSETSDIR'}= $path_charsetsdir;
$ENV{'UMASK'}= "0660"; # The octal *string*
$ENV{'UMASK_DIR'}= "0770"; # The octal *string*
#
# MySQL tests can produce output in various character sets
# (especially, ctype_xxx.test). To avoid confusing Perl
# with output which is incompatible with the current locale
# settings, we reset the current values of LC_ALL and LC_CTYPE to "C".
# For details, please see
# Bug#27636 tests fails if LC_* variables set to *_*.UTF-8
#
$ENV{'LC_ALL'}= "C";
$ENV{'LC_CTYPE'}= "C";
$ENV{'LC_COLLATE'}= "C";
$ENV{'USE_RUNNING_SERVER'}= using_extern();
$ENV{'MYSQL_TEST_DIR'}= $glob_mysql_test_dir;
$ENV{'DEFAULT_MASTER_PORT'}= $mysqld_variables{'master-port'} || 3306;
$ENV{'MYSQL_TMP_DIR'}= $opt_tmpdir;
$ENV{'MYSQLTEST_VARDIR'}= $opt_vardir;
if (IS_WINDOWS)
{
$ENV{'SECURE_LOAD_PATH'}= $glob_mysql_test_dir."\\std_data";
}
else
{
$ENV{'SECURE_LOAD_PATH'}= $glob_mysql_test_dir."/std_data";
}
# ----------------------------------------------------
# Setup env for NDB
# ----------------------------------------------------
if ( ! $opt_skip_ndbcluster )
{
$ENV{'NDB_MGM'}=
my_find_bin($basedir,
["storage/ndb/src/mgmclient", "bin"],
"ndb_mgm");
$ENV{'NDB_TOOLS_DIR'}=
my_find_dir($basedir,
["storage/ndb/tools", "bin"]);
$ENV{'NDB_EXAMPLES_DIR'}=
my_find_dir($basedir,
["storage/ndb/ndbapi-examples", "bin"]);
$ENV{'NDB_EXAMPLES_BINARY'}=
my_find_bin($basedir,
["storage/ndb/ndbapi-examples/ndbapi_simple", "bin"],
"ndbapi_simple", NOT_REQUIRED);
my $path_ndb_testrun_log= "$opt_vardir/log/ndb_testrun.log";
$ENV{'NDB_TOOLS_OUTPUT'}= $path_ndb_testrun_log;
$ENV{'NDB_EXAMPLES_OUTPUT'}= $path_ndb_testrun_log;
}
# ----------------------------------------------------
# mysql clients
# ----------------------------------------------------
$ENV{'MYSQL_CHECK'}= client_arguments("mysqlcheck");
$ENV{'MYSQL_DUMP'}= mysqldump_arguments(".1");
$ENV{'MYSQL_DUMP_SLAVE'}= mysqldump_arguments(".2");
$ENV{'MYSQL_SLAP'}= mysqlslap_arguments();
$ENV{'MYSQL_IMPORT'}= client_arguments("mysqlimport");
$ENV{'MYSQL_SHOW'}= client_arguments("mysqlshow");
$ENV{'MYSQL_BINLOG'}= client_arguments("mysqlbinlog");
$ENV{'MYSQL'}= client_arguments("mysql");
$ENV{'MYSQL_SLAVE'}= client_arguments("mysql", ".2");
$ENV{'MYSQL_UPGRADE'}= client_arguments("mysql_upgrade");
$ENV{'MYSQLADMIN'}= native_path($exe_mysqladmin);
$ENV{'MYSQL_CLIENT_TEST'}= mysql_client_test_arguments();
$ENV{'MYSQL_FIX_SYSTEM_TABLES'}= mysql_fix_arguments();
$ENV{'EXE_MYSQL'}= $exe_mysql;
# ----------------------------------------------------
# bug25714 executable may _not_ exist in
# some versions, test using it should be skipped
# ----------------------------------------------------
my $exe_bug25714=
mtr_exe_maybe_exists(vs_config_dirs('tests', 'bug25714'),
"$basedir/tests/bug25714");
$ENV{'MYSQL_BUG25714'}= native_path($exe_bug25714);
# ----------------------------------------------------
# mysql_fix_privilege_tables.sql
# ----------------------------------------------------
my $file_mysql_fix_privilege_tables=
mtr_file_exists("$basedir/scripts/mysql_fix_privilege_tables.sql",
"$basedir/share/mysql_fix_privilege_tables.sql",
"$basedir/share/mysql/mysql_fix_privilege_tables.sql");
$ENV{'MYSQL_FIX_PRIVILEGE_TABLES'}= $file_mysql_fix_privilege_tables;
# ----------------------------------------------------
# my_print_defaults
# ----------------------------------------------------
my $exe_my_print_defaults=
mtr_exe_exists(vs_config_dirs('extra', 'my_print_defaults'),
"$path_client_bindir/my_print_defaults",
"$basedir/extra/my_print_defaults");
$ENV{'MYSQL_MY_PRINT_DEFAULTS'}= native_path($exe_my_print_defaults);
# ----------------------------------------------------
# Setup env so childs can execute myisampack and myisamchk
# ----------------------------------------------------
$ENV{'MYISAMCHK'}= native_path(mtr_exe_exists(
vs_config_dirs('storage/myisam', 'myisamchk'),
vs_config_dirs('myisam', 'myisamchk'),
"$path_client_bindir/myisamchk",
"$basedir/storage/myisam/myisamchk",
"$basedir/myisam/myisamchk"));
$ENV{'MYISAMPACK'}= native_path(mtr_exe_exists(
vs_config_dirs('storage/myisam', 'myisampack'),
vs_config_dirs('myisam', 'myisampack'),
"$path_client_bindir/myisampack",
"$basedir/storage/myisam/myisampack",
"$basedir/myisam/myisampack"));
# ----------------------------------------------------
# mysqlhotcopy
# ----------------------------------------------------
my $mysqlhotcopy=
mtr_pl_maybe_exists("$basedir/scripts/mysqlhotcopy") ||
mtr_pl_maybe_exists("$path_client_bindir/mysqlhotcopy");
if ($mysqlhotcopy)
{
$ENV{'MYSQLHOTCOPY'}= $mysqlhotcopy;
}
# ----------------------------------------------------
# perror
# ----------------------------------------------------
my $exe_perror= mtr_exe_exists(vs_config_dirs('extra', 'perror'),
"$basedir/extra/perror",
"$path_client_bindir/perror");
$ENV{'MY_PERROR'}= native_path($exe_perror);
# Create an environment variable to make it possible
# to detect that valgrind is being used from test cases
$ENV{'VALGRIND_TEST'}= $opt_valgrind;
# Add dir of this perl to aid mysqltest in finding perl
my $perldir= dirname($^X);
my $pathsep= ":";
$pathsep= ";" if IS_WINDOWS && ! IS_CYGWIN;
$ENV{'PATH'}= "$ENV{'PATH'}".$pathsep.$perldir;
}
#
# Remove var and any directories in var/ created by previous
# tests
#
sub remove_stale_vardir () {
mtr_report("Removing old var directory...");
# Safety!
mtr_error("No, don't remove the vardir when running with --extern")
if using_extern();
mtr_verbose("opt_vardir: $opt_vardir");
if ( $opt_vardir eq $default_vardir )
{
#
# Running with "var" in mysql-test dir
#
if ( -l $opt_vardir)
{
# var is a symlink
if ( $opt_mem )
{
# Remove the directory which the link points at
mtr_verbose("Removing " . readlink($opt_vardir));
rmtree(readlink($opt_vardir));
# Remove the "var" symlink
mtr_verbose("unlink($opt_vardir)");
unlink($opt_vardir);
}
else
{
# Some users creates a soft link in mysql-test/var to another area
# - allow it, but remove all files in it
mtr_report(" - WARNING: Using the 'mysql-test/var' symlink");
# Make sure the directory where it points exist
mtr_error("The destination for symlink $opt_vardir does not exist")
if ! -d readlink($opt_vardir);
foreach my $bin ( glob("$opt_vardir/*") )
{
mtr_verbose("Removing bin $bin");
rmtree($bin);
}
}
}
else
{
# Remove the entire "var" dir
mtr_verbose("Removing $opt_vardir/");
rmtree("$opt_vardir/");
}
if ( $opt_mem )
{
# A symlink from var/ to $opt_mem will be set up
# remove the $opt_mem dir to assure the symlink
# won't point at an old directory
mtr_verbose("Removing $opt_mem");
rmtree($opt_mem);
}
}
else
{
#
# Running with "var" in some other place
#
# Remove the var/ dir in mysql-test dir if any
# this could be an old symlink that shouldn't be there
mtr_verbose("Removing $default_vardir");
rmtree($default_vardir);
# Remove the "var" dir
mtr_verbose("Removing $opt_vardir/");
rmtree("$opt_vardir/");
}
# Remove the "tmp" dir
mtr_verbose("Removing $opt_tmpdir/");
rmtree("$opt_tmpdir/");
}
#
# Create var and the directories needed in var
#
sub setup_vardir() {
mtr_report("Creating var directory '$opt_vardir'...");
if ( $opt_vardir eq $default_vardir )
{
#
# Running with "var" in mysql-test dir
#
if ( -l $opt_vardir )
{
# it's a symlink
# Make sure the directory where it points exist
mtr_error("The destination for symlink $opt_vardir does not exist")
if ! -d readlink($opt_vardir);
}
elsif ( $opt_mem )
{
# Runinng with "var" as a link to some "memory" location, normally tmpfs
mtr_verbose("Creating $opt_mem");
mkpath($opt_mem);
mtr_report(" - symlinking 'var' to '$opt_mem'");
symlink($opt_mem, $opt_vardir);
}
}
if ( ! -d $opt_vardir )
{
mtr_verbose("Creating $opt_vardir");
mkpath($opt_vardir);
}
# Ensure a proper error message if vardir couldn't be created
unless ( -d $opt_vardir and -w $opt_vardir )
{
mtr_error("Writable 'var' directory is needed, use the " .
"'--vardir=<path>' option");
}
mkpath("$opt_vardir/log");
mkpath("$opt_vardir/run");
# Create var/tmp and tmp - they might be different
mkpath("$opt_vardir/tmp");
mkpath($opt_tmpdir) if ($opt_tmpdir ne "$opt_vardir/tmp");
# On some operating systems, there is a limit to the length of a
# UNIX domain socket's path far below PATH_MAX.
# Don't allow that to happen
if (check_socket_path_length("$opt_tmpdir/testsocket.sock")){
mtr_error("Socket path '$opt_tmpdir' too long, it would be ",
"truncated and thus not possible to use for connection to ",
"MySQL Server. Set a shorter with --tmpdir=<path> option");
}
# copy all files from std_data into var/std_data
# and make them world readable
copytree("$glob_mysql_test_dir/std_data", "$opt_vardir/std_data", "0022");
# Remove old log files
foreach my $name (glob("r/*.progress r/*.log r/*.warnings"))
{
unlink($name);
}
}
#
# Check if running as root
# i.e a file can be read regardless what mode we set it to
#
sub check_running_as_root () {
my $test_file= "$opt_vardir/test_running_as_root.txt";
mtr_tofile($test_file, "MySQL");
chmod(oct("0000"), $test_file);
my $result="";
if (open(FILE,"<",$test_file))
{
$result= join('', <FILE>);
close FILE;
}
# Some filesystems( for example CIFS) allows reading a file
# although mode was set to 0000, but in that case a stat on
# the file will not return 0000
my $file_mode= (stat($test_file))[2] & 07777;
mtr_verbose("result: $result, file_mode: $file_mode");
if ($result eq "MySQL" && $file_mode == 0)
{
mtr_warning("running this script as _root_ will cause some " .
"tests to be skipped");
$ENV{'MYSQL_TEST_ROOT'}= "YES";
}
chmod(oct("0755"), $test_file);
unlink($test_file);
}
sub check_ssl_support ($) {
my $mysqld_variables= shift;
if ($opt_skip_ssl)
{
mtr_report(" - skipping SSL");
$opt_ssl_supported= 0;
$opt_ssl= 0;
return;
}
if ( ! $mysqld_variables->{'ssl'} )
{
if ( $opt_ssl)
{
mtr_error("Couldn't find support for SSL");
return;
}
mtr_report(" - skipping SSL, mysqld not compiled with SSL");
$opt_ssl_supported= 0;
$opt_ssl= 0;
return;
}
mtr_report(" - SSL connections supported");
$opt_ssl_supported= 1;
}
sub check_debug_support ($) {
my $mysqld_variables= shift;
if ( ! $mysqld_variables->{'debug'} )
{
#mtr_report(" - binaries are not debug compiled");
$debug_compiled_binaries= 0;
if ( $opt_debug_server )
{
mtr_error("Can't use --debug[-server], binary does not support it");
}
return;
}
mtr_report(" - binaries are debug compiled");
$debug_compiled_binaries= 1;
}
#
# Helper function to handle configuration-based subdirectories which Visual
# Studio uses for storing binaries. If opt_vs_config is set, this returns
# a path based on that setting; if not, it returns paths for the default
# /release/ and /debug/ subdirectories.
#
# $exe can be undefined, if the directory itself will be used
#
sub vs_config_dirs ($$) {
my ($path_part, $exe) = @_;
$exe = "" if not defined $exe;
# Don't look in these dirs when not on windows
return () unless IS_WINDOWS;
if ($opt_vs_config)
{
return ("$basedir/$path_part/$opt_vs_config/$exe");
}
return ("$basedir/$path_part/release/$exe",
"$basedir/$path_part/relwithdebinfo/$exe",
"$basedir/$path_part/debug/$exe");
}
sub check_ndbcluster_support ($) {
my $mysqld_variables= shift;
if ($opt_include_ndbcluster)
{
$opt_skip_ndbcluster= 0;
}
if ($opt_skip_ndbcluster)
{
mtr_report(" - skipping ndbcluster");
return;
}
if ( ! $mysqld_variables{'ndb-connectstring'} )
{
mtr_report(" - skipping ndbcluster, mysqld not compiled with ndbcluster");
$opt_skip_ndbcluster= 2;
return;
}
mtr_report(" - using ndbcluster when necessary, mysqld supports it");
return;
}
sub ndbcluster_wait_started($$){
my $cluster= shift;
my $ndb_waiter_extra_opt= shift;
my $path_waitlog= join('/', $opt_vardir, $cluster->name(), "ndb_waiter.log");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $cluster->suffix());
mtr_add_arg($args, "--timeout=%d", $opt_start_timeout);
if ($ndb_waiter_extra_opt)
{
mtr_add_arg($args, "$ndb_waiter_extra_opt");
}
# Start the ndb_waiter which will connect to the ndb_mgmd
# and poll it for state of the ndbd's, will return when
# all nodes in the cluster is started
my $res= My::SafeProcess->run
(
name => "ndb_waiter ".$cluster->name(),
path => $exe_ndb_waiter,
args => \$args,
output => $path_waitlog,
error => $path_waitlog,
append => 1,
);
# Check that ndb_mgmd(s) are still alive
foreach my $ndb_mgmd ( in_cluster($cluster, ndb_mgmds()) )
{
my $proc= $ndb_mgmd->{proc};
if ( ! $proc->wait_one(0) )
{
mtr_warning("$proc died");
return 2;
}
}
# Check that all started ndbd(s) are still alive
foreach my $ndbd ( in_cluster($cluster, ndbds()) )
{
my $proc= $ndbd->{proc};
next unless defined $proc;
if ( ! $proc->wait_one(0) )
{
mtr_warning("$proc died");
return 3;
}
}
if ($res)
{
mtr_verbose("ndbcluster_wait_started failed");
return 1;
}
return 0;
}
sub ndb_mgmd_wait_started($) {
my ($cluster)= @_;
my $retries= 100;
while ($retries)
{
my $result= ndbcluster_wait_started($cluster, "--no-contact");
if ($result == 0)
{
# ndb_mgmd is started
mtr_verbose("ndb_mgmd is started");
return 0;
}
elsif ($result > 1)
{
mtr_warning("Cluster process failed while waiting for start");
return $result;
}
mtr_milli_sleep(100);
$retries--;
}
return 1;
}
sub ndb_mgmd_start ($$) {
my ($cluster, $ndb_mgmd)= @_;
mtr_verbose("ndb_mgmd_start");
my $dir= $ndb_mgmd->value("DataDir");
mkpath($dir) unless -d $dir;
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $cluster->suffix());
mtr_add_arg($args, "--mycnf");
mtr_add_arg($args, "--nodaemon");
my $path_ndb_mgmd_log= "$dir/ndb_mgmd.log";
$ndb_mgmd->{'proc'}= My::SafeProcess->new
(
name => $ndb_mgmd->after('cluster_config.'),
path => $exe_ndb_mgmd,
args => \$args,
output => $path_ndb_mgmd_log,
error => $path_ndb_mgmd_log,
append => 1,
verbose => $opt_verbose,
);
mtr_verbose("Started $ndb_mgmd->{proc}");
# FIXME Should not be needed
# Unfortunately the cluster nodes will fail to start
# if ndb_mgmd has not started properly
if (ndb_mgmd_wait_started($cluster))
{
mtr_warning("Failed to wait for start of ndb_mgmd");
return 1;
}
return 0;
}
sub ndbd_start {
my ($cluster, $ndbd)= @_;
mtr_verbose("ndbd_start");
my $dir= $ndbd->value("DataDir");
mkpath($dir) unless -d $dir;
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $cluster->suffix());
mtr_add_arg($args, "--nodaemon");
# > 5.0 { 'character-sets-dir' => \&fix_charset_dir },
my $path_ndbd_log= "$dir/ndbd.log";
my $proc= My::SafeProcess->new
(
name => $ndbd->after('cluster_config.'),
path => $exe_ndbd,
args => \$args,
output => $path_ndbd_log,
error => $path_ndbd_log,
append => 1,
verbose => $opt_verbose,
);
mtr_verbose("Started $proc");
$ndbd->{proc}= $proc;
return;
}
sub ndbcluster_start ($) {
my $cluster= shift;
mtr_verbose("ndbcluster_start '".$cluster->name()."'");
foreach my $ndb_mgmd ( in_cluster($cluster, ndb_mgmds()) )
{
next if started($ndb_mgmd);
ndb_mgmd_start($cluster, $ndb_mgmd);
}
foreach my $ndbd ( in_cluster($cluster, ndbds()) )
{
next if started($ndbd);
ndbd_start($cluster, $ndbd);
}
return 0;
}
sub create_config_file_for_extern {
my %opts=
(
socket => '/tmp/mysqld.sock',
port => 3306,
user => $opt_user,
password => '',
@_
);
mtr_report("Creating my.cnf file for extern server...");
my $F= IO::File->new($path_config_file, "w")
or mtr_error("Can't write to $path_config_file: $!");
print $F "[client]\n";
while (my ($option, $value)= each( %opts )) {
print $F "$option= $value\n";
mtr_report(" $option= $value");
}
print $F <<EOF
# binlog reads from [client] and [mysqlbinlog]
[mysqlbinlog]
character-sets-dir= $path_charsetsdir
local-load= $opt_tmpdir
# mysql_fix_privilege_tables.sh don't read from [client]
[mysql_fix_privilege_tables]
socket = $opts{'socket'}
port = $opts{'port'}
user = $opts{'user'}
password = $opts{'password'}
EOF
;
$F= undef; # Close file
}
#
# Kill processes left from previous runs, normally
# there should be none so make sure to warn
# if there is one
#
sub kill_leftovers ($) {
my $rundir= shift;
return unless ( -d $rundir );
mtr_report("Checking leftover processes...");
# Scan the "run" directory for process id's to kill
opendir(RUNDIR, $rundir)
or mtr_error("kill_leftovers, can't open dir \"$rundir\": $!");
while ( my $elem= readdir(RUNDIR) )
{
# Only read pid from files that end with .pid
if ( $elem =~ /.*[.]pid$/ )
{
my $pidfile= "$rundir/$elem";
next unless -f $pidfile;
my $pid= mtr_fromfile($pidfile);
unlink($pidfile);
unless ($pid=~ /^(\d+)/){
# The pid was not a valid number
mtr_warning("Got invalid pid '$pid' from '$elem'");
next;
}
mtr_report(" - found old pid $pid in '$elem', killing it...");
my $ret= kill("KILL", $pid);
if ($ret == 0) {
mtr_report(" process did not exist!");
next;
}
my $check_counter= 100;
while ($ret > 0 and $check_counter--) {
mtr_milli_sleep(100);
$ret= kill(0, $pid);
}
mtr_report($check_counter ? " ok!" : " failed!");
}
else
{
mtr_warning("Found non pid file '$elem' in '$rundir'")
if -f "$rundir/$elem";
}
}
closedir(RUNDIR);
}
#
# Check that all the ports that are going to
# be used are free
#
sub check_ports_free ($)
{
my $bthread= shift;
my $portbase = $bthread * 10 + 10000;
for ($portbase..$portbase+9){
if (mtr_ping_port($_)){
mtr_report(" - 'localhost:$_' was not free");
return 0; # One port was not free
}
}
return 1; # All ports free
}
sub initialize_servers {
if ( using_extern() )
{
# Running against an already started server, if the specified
# vardir does not already exist it should be created
if ( ! -d $opt_vardir )
{
setup_vardir();
}
else
{
mtr_verbose("No need to create '$opt_vardir' it already exists");
}
}
else
{
# Kill leftovers from previous run
# using any pidfiles found in var/run
kill_leftovers("$opt_vardir/run");
if ( ! $opt_start_dirty )
{
remove_stale_vardir();
setup_vardir();
mysql_install_db(default_mysqld(), "$opt_vardir/install.db");
}
}
}
#
# Remove all newline characters expect after semicolon
#
sub sql_to_bootstrap {
my ($sql) = @_;
my @lines= split(/\n/, $sql);
my $result= "\n";
my $delimiter= ';';
foreach my $line (@lines) {
# Change current delimiter if line starts with "delimiter"
if ( $line =~ /^delimiter (.*)/ ) {
my $new= $1;
# Remove old delimiter from end of new
$new=~ s/\Q$delimiter\E$//;
$delimiter = $new;
mtr_debug("changed delimiter to $delimiter");
# No need to add the delimiter to result
next;
}
# Add newline if line ends with $delimiter
# and convert the current delimiter to semicolon
if ( $line =~ /\Q$delimiter\E$/ ){
$line =~ s/\Q$delimiter\E$/;/;
$result.= "$line\n";
mtr_debug("Added default delimiter");
next;
}
# Remove comments starting with --
if ( $line =~ /^\s*--/ ) {
mtr_debug("Discarded $line");
next;
}
# Replace @HOSTNAME with localhost
$line=~ s/\'\@HOSTNAME\@\'/localhost/;
# Default, just add the line without newline
# but with a space as separator
$result.= "$line ";
}
return $result;
}
sub default_mysqld {
# Generate new config file from template
my $config= My::ConfigFactory->new_config
( {
basedir => $basedir,
testdir => $glob_mysql_test_dir,
template_path => "include/default_my.cnf",
vardir => $opt_vardir,
tmpdir => $opt_tmpdir,
baseport => 0,
user => $opt_user,
password => '',
}
);
my $mysqld= $config->group('mysqld.1')
or mtr_error("Couldn't find mysqld.1 in default config");
return $mysqld;
}
sub mysql_install_db {
my ($mysqld, $datadir)= @_;
my $install_datadir= $datadir || $mysqld->value('datadir');
my $install_basedir= $mysqld->value('basedir');
my $install_lang= $mysqld->value('language');
my $install_chsdir= $mysqld->value('character-sets-dir');
mtr_report("Installing system database...");
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--no-defaults");
mtr_add_arg($args, "--bootstrap");
mtr_add_arg($args, "--basedir=%s", $install_basedir);
mtr_add_arg($args, "--datadir=%s", $install_datadir);
mtr_add_arg($args, "--loose-skip-innodb");
mtr_add_arg($args, "--loose-skip-falcon");
mtr_add_arg($args, "--loose-skip-ndbcluster");
mtr_add_arg($args, "--tmpdir=%s", "$opt_vardir/tmp/");
mtr_add_arg($args, "--core-file");
if ( $opt_debug )
{
mtr_add_arg($args, "--debug=d:t:i:A,%s/log/bootstrap.trace",
$path_vardir_trace);
}
mtr_add_arg($args, "--language=%s", $install_lang);
mtr_add_arg($args, "--character-sets-dir=%s", $install_chsdir);
# If DISABLE_GRANT_OPTIONS is defined when the server is compiled (e.g.,
# configure --disable-grant-options), mysqld will not recognize the
# --bootstrap or --skip-grant-tables options. The user can set
# MYSQLD_BOOTSTRAP to the full path to a mysqld which does accept
# --bootstrap, to accommodate this.
my $exe_mysqld_bootstrap =
$ENV{'MYSQLD_BOOTSTRAP'} || find_mysqld($install_basedir);
# ----------------------------------------------------------------------
# export MYSQLD_BOOTSTRAP_CMD variable containing <path>/mysqld <args>
# ----------------------------------------------------------------------
$ENV{'MYSQLD_BOOTSTRAP_CMD'}= "$exe_mysqld_bootstrap " . join(" ", @$args);
# ----------------------------------------------------------------------
# Create the bootstrap.sql file
# ----------------------------------------------------------------------
my $bootstrap_sql_file= "$opt_vardir/tmp/bootstrap.sql";
my $path_sql= my_find_file($install_basedir,
["mysql", "sql/share", "share/mysql",
"share", "scripts"],
"mysql_system_tables.sql",
NOT_REQUIRED);
if (-f $path_sql )
{
my $sql_dir= dirname($path_sql);
# Use the mysql database for system tables
mtr_tofile($bootstrap_sql_file, "use mysql\n");
# Add the offical mysql system tables
# for a production system
mtr_appendfile_to_file("$sql_dir/mysql_system_tables.sql",
$bootstrap_sql_file);
# Add the mysql system tables initial data
# for a production system
mtr_appendfile_to_file("$sql_dir/mysql_system_tables_data.sql",
$bootstrap_sql_file);
# Add test data for timezone - this is just a subset, on a real
# system these tables will be populated either by mysql_tzinfo_to_sql
# or by downloading the timezone table package from our website
mtr_appendfile_to_file("$sql_dir/mysql_test_data_timezone.sql",
$bootstrap_sql_file);
# Fill help tables, just an empty file when running from bk repo
# but will be replaced by a real fill_help_tables.sql when
# building the source dist
mtr_appendfile_to_file("$sql_dir/fill_help_tables.sql",
$bootstrap_sql_file);
}
else
{
# Install db from init_db.sql that exist in early 5.1 and 5.0
# versions of MySQL
my $init_file= "$install_basedir/mysql-test/lib/init_db.sql";
mtr_report(" - from '$init_file'");
my $text= mtr_grab_file($init_file) or
mtr_error("Can't open '$init_file': $!");
mtr_tofile($bootstrap_sql_file,
sql_to_bootstrap($text));
}
# Remove anonymous users
mtr_tofile($bootstrap_sql_file,
"DELETE FROM mysql.user where user= '';\n");
# Create mtr database
mtr_tofile($bootstrap_sql_file,
"CREATE DATABASE mtr;\n");
# Add help tables and data for warning detection and supression
mtr_tofile($bootstrap_sql_file,
sql_to_bootstrap(mtr_grab_file("include/mtr_warnings.sql")));
# Add procedures for checking server is restored after testcase
mtr_tofile($bootstrap_sql_file,
sql_to_bootstrap(mtr_grab_file("include/mtr_check.sql")));
# Log bootstrap command
my $path_bootstrap_log= "$opt_vardir/log/bootstrap.log";
mtr_tofile($path_bootstrap_log,
"$exe_mysqld_bootstrap " . join(" ", @$args) . "\n");
# Create directories mysql and test
mkpath("$install_datadir/mysql");
mkpath("$install_datadir/test");
if ( My::SafeProcess->run
(
name => "bootstrap",
path => $exe_mysqld_bootstrap,
args => \$args,
input => $bootstrap_sql_file,
output => $path_bootstrap_log,
error => $path_bootstrap_log,
append => 1,
verbose => $opt_verbose,
) != 0)
{
mtr_error("Error executing mysqld --bootstrap\n" .
"Could not install system database from $bootstrap_sql_file\n" .
"see $path_bootstrap_log for errors");
}
}
sub run_testcase_check_skip_test($)
{
my ($tinfo)= @_;
# ----------------------------------------------------------------------
# If marked to skip, just print out and return.
# Note that a test case not marked as 'skip' can still be
# skipped later, because of the test case itself in cooperation
# with the mysqltest program tells us so.
# ----------------------------------------------------------------------
if ( $tinfo->{'skip'} )
{
mtr_report_test_skipped($tinfo) unless $start_only;
return 1;
}
return 0;
}
sub run_query {
my ($tinfo, $mysqld, $query)= @_;
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $mysqld->after('mysqld'));
mtr_add_arg($args, "-e %s", $query);
my $res= My::SafeProcess->run
(
name => "run_query -> ".$mysqld->name(),
path => $exe_mysql,
args => \$args,
output => '/dev/null',
error => '/dev/null'
);
return $res
}
sub do_before_run_mysqltest($)
{
my $tinfo= shift;
# Remove old files produced by mysqltest
my $base_file= mtr_match_extension($tinfo->{result_file},
"result"); # Trim extension
if (defined $base_file ){
unlink("$base_file.reject");
unlink("$base_file.progress");
unlink("$base_file.log");
unlink("$base_file.warnings");
}
if ( $mysql_version_id < 50000 ) {
# Set environment variable NDB_STATUS_OK to 1
# if script decided to run mysqltest cluster _is_ installed ok
$ENV{'NDB_STATUS_OK'} = "1";
} elsif ( $mysql_version_id < 50100 ) {
# Set environment variable NDB_STATUS_OK to YES
# if script decided to run mysqltest cluster _is_ installed ok
$ENV{'NDB_STATUS_OK'} = "YES";
}
}
#
# Check all server for sideffects
#
# RETURN VALUE
# 0 ok
# 1 Check failed
# >1 Fatal errro
sub check_testcase($$)
{
my ($tinfo, $mode)= @_;
my $tname= $tinfo->{name};
# Start the mysqltest processes in parallel to save time
# also makes it possible to wait for any process to exit during the check
my %started;
foreach my $mysqld ( mysqlds() )
{
# Skip if server has been restarted with additional options
if ( defined $mysqld->{'proc'} && ! exists $mysqld->{'restart_opts'} )
{
my $proc= start_check_testcase($tinfo, $mode, $mysqld);
$started{$proc->pid()}= $proc;
}
}
# Return immediately if no check proceess was started
return 0 unless ( keys %started );
my $timeout= start_timer(check_timeout());
while (1){
my $result;
my $proc= My::SafeProcess->wait_any_timeout($timeout);
mtr_report("Got $proc");
if ( delete $started{$proc->pid()} ) {
my $err_file= $proc->user_data();
my $base_file= mtr_match_extension($err_file, "err"); # Trim extension
# One check testcase process returned
my $res= $proc->exit_status();
if ( $res == 0){
# Check completed without problem
# Remove the .err file the check generated
unlink($err_file);
# Remove the .result file the check generated
if ( $mode eq 'after' ){
unlink("$base_file.result");
}
if ( keys(%started) == 0){
# All checks completed
return 0;
}
# Wait for next process to exit
next;
}
else
{
if ( $mode eq "after" and $res == 1 )
{
# Test failed, grab the report mysqltest has created
my $report= mtr_grab_file($err_file);
$tinfo->{check}.=
"\nMTR's internal check of the test case '$tname' failed.
This means that the test case does not preserve the state that existed
before the test case was executed. Most likely the test case did not
do a proper clean-up. It could also be caused by the previous test run
by this thread, if the server wasn't restarted.
This is the diff of the states of the servers before and after the
test case was executed:\n";
$tinfo->{check}.= $report;
# Check failed, mark the test case with that info
$tinfo->{'check_testcase_failed'}= 1;
$result= 1;
}
elsif ( $res )
{
my $report= mtr_grab_file($err_file);
$tinfo->{comment}.=
"Could not execute 'check-testcase' $mode ".
"testcase '$tname' (res: $res):\n";
$tinfo->{comment}.= $report;
$result= 2;
}
# Remove the .result file the check generated
unlink("$base_file.result");
}
}
elsif ( $proc->{timeout} ) {
$tinfo->{comment}.= "Timeout for 'check-testcase' expired after "
.check_timeout()." seconds";
$result= 4;
}
else {
# Unknown process returned, most likley a crash, abort everything
$tinfo->{comment}=
"The server $proc crashed while running ".
"'check testcase $mode test'".
get_log_from_proc($proc, $tinfo->{name});
$result= 3;
}
# Kill any check processes still running
map($_->kill(), values(%started));
mtr_warning("Check-testcase failed, this could also be caused by the" .
" previous test run by this worker thread")
if $result > 1 && $mode eq "before";
return $result;
}
mtr_error("INTERNAL_ERROR: check_testcase");
}
# Start run mysqltest on one server
#
# RETURN VALUE
# 0 OK
# 1 Check failed
#
sub start_run_one ($$) {
my ($mysqld, $run)= @_;
my $name= "$run-".$mysqld->name();
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $mysqld->after('mysqld'));
mtr_add_arg($args, "--silent");
mtr_add_arg($args, "--skip-safemalloc");
mtr_add_arg($args, "--test-file=%s", "include/$run.test");
my $errfile= "$opt_vardir/tmp/$name.err";
my $proc= My::SafeProcess->new
(
name => $name,
path => $exe_mysqltest,
error => $errfile,
output => $errfile,
args => \$args,
user_data => $errfile,
verbose => $opt_verbose,
);
mtr_verbose("Started $proc");
return $proc;
}
#
# Run script on all servers, collect results
#
# RETURN VALUE
# 0 ok
# 1 Failure
sub run_on_all($$)
{
my ($tinfo, $run)= @_;
# Start the mysqltest processes in parallel to save time
# also makes it possible to wait for any process to exit during the check
# and to have a timeout process
my %started;
foreach my $mysqld ( mysqlds() )
{
if ( defined $mysqld->{'proc'} )
{
my $proc= start_run_one($mysqld, $run);
$started{$proc->pid()}= $proc;
}
}
# Return immediately if no check proceess was started
return 0 unless ( keys %started );
my $timeout= start_timer(check_timeout());
while (1){
my $result;
my $proc= My::SafeProcess->wait_any_timeout($timeout);
mtr_report("Got $proc");
if ( delete $started{$proc->pid()} ) {
# One mysqltest process returned
my $err_file= $proc->user_data();
my $res= $proc->exit_status();
# Append the report from .err file
$tinfo->{comment}.= " == $err_file ==\n";
$tinfo->{comment}.= mtr_grab_file($err_file);
$tinfo->{comment}.= "\n";
# Remove the .err file
unlink($err_file);
if ( keys(%started) == 0){
# All completed
return 0;
}
# Wait for next process to exit
next;
}
elsif ($proc->{timeout}) {
$tinfo->{comment}.= "Timeout for '$run' expired after "
.check_timeout()." seconds";
}
else {
# Unknown process returned, most likley a crash, abort everything
$tinfo->{comment}.=
"The server $proc crashed while running '$run'".
get_log_from_proc($proc, $tinfo->{name});
}
# Kill any check processes still running
map($_->kill(), values(%started));
return 1;
}
mtr_error("INTERNAL_ERROR: run_on_all");
}
sub mark_log {
my ($log, $tinfo)= @_;
my $log_msg= "CURRENT_TEST: $tinfo->{name}\n";
mtr_tofile($log, $log_msg);
}
sub find_testcase_skipped_reason($)
{
my ($tinfo)= @_;
# Set default message
$tinfo->{'comment'}= "Detected by testcase(no log file)";
# Open the test log file
my $F= IO::File->new($path_current_testlog)
or return;
my $reason;
while ( my $line= <$F> )
{
# Look for "reason: <reason for skipping test>"
if ( $line =~ /reason: (.*)/ )
{
$reason= $1;
}
}
if ( ! $reason )
{
mtr_warning("Could not find reason for skipping test in $path_current_testlog");
$reason= "Detected by testcase(reason unknown) ";
}
$tinfo->{'comment'}= $reason;
}
sub find_analyze_request
{
# Open the test log file
my $F= IO::File->new($path_current_testlog)
or return;
my $analyze;
while ( my $line= <$F> )
{
# Look for "reason: <reason for skipping test>"
if ( $line =~ /analyze: (.*)/ )
{
$analyze= $1;
}
}
return $analyze;
}
# The test can leave a file in var/tmp/ to signal
# that all servers should be restarted
sub restart_forced_by_test($)
{
my $file = shift;
my $restart = 0;
foreach my $mysqld ( mysqlds() )
{
my $datadir = $mysqld->value('datadir');
my $force_restart_file = "$datadir/mtr/$file";
if ( -f $force_restart_file )
{
mtr_verbose("Restart of servers forced by test");
$restart = 1;
last;
}
}
return $restart;
}
# Return timezone value of tinfo or default value
sub timezone {
my ($tinfo)= @_;
return $tinfo->{timezone} || "GMT-3";
}
# Storage for changed environment variables
my %old_env;
#
# Run a single test case
#
# RETURN VALUE
# 0 OK
# > 0 failure
#
sub run_testcase ($) {
my $tinfo= shift;
mtr_verbose("Running test:", $tinfo->{name});
# Allow only alpanumerics pluss _ - + . in combination names,
# or anything beginning with -- (the latter comes from --combination)
my $combination= $tinfo->{combination};
if ($combination && $combination !~ /^\w[-\w\.\+]+$/
&& $combination !~ /^--/)
{
mtr_error("Combination '$combination' contains illegal characters");
}
# -------------------------------------------------------
# Init variables that can change between each test case
# -------------------------------------------------------
my $timezone= timezone($tinfo);
$ENV{'TZ'}= $timezone;
mtr_verbose("Setting timezone: $timezone");
if ( ! using_extern() )
{
my @restart= servers_need_restart($tinfo);
if ( @restart != 0) {
stop_servers($tinfo, @restart );
}
if ( started(all_servers()) == 0 )
{
# Remove old datadirs
clean_datadir() unless $opt_start_dirty;
# Restore old ENV
while (my ($option, $value)= each( %old_env )) {
if (defined $value){
mtr_verbose("Restoring $option to $value");
$ENV{$option}= $value;
} else {
mtr_verbose("Removing $option");
delete($ENV{$option});
}
}
%old_env= ();
mtr_verbose("Generating my.cnf from '$tinfo->{template_path}'");
# Generate new config file from template
$config= My::ConfigFactory->new_config
( {
basedir => $basedir,
testdir => $glob_mysql_test_dir,
template_path => $tinfo->{template_path},
extra_template_path => $tinfo->{extra_template_path},
vardir => $opt_vardir,
tmpdir => $opt_tmpdir,
baseport => $baseport,
#hosts => [ 'host1', 'host2' ],
user => $opt_user,
password => '',
ssl => $opt_ssl_supported,
embedded => $opt_embedded_server,
}
);
# Write the new my.cnf
$config->save($path_config_file);
# Remember current config so a restart can occur when a test need
# to use a different one
$current_config_name= $tinfo->{template_path};
#
# Set variables in the ENV section
#
foreach my $option ($config->options_in_group("ENV"))
{
# Save old value to restore it before next time
$old_env{$option->name()}= $ENV{$option->name()};
mtr_verbose($option->name(), "=",$option->value());
$ENV{$option->name()}= $option->value();
}
}
# Write start of testcase to log
mark_log($path_current_testlog, $tinfo);
if (start_servers($tinfo))
{
report_failure_and_restart($tinfo);
return 1;
}
}
# --------------------------------------------------------------------
# If --start or --start-dirty given, stop here to let user manually
# run tests
# If --wait-all is also given, do the same, but don't die if one
# server exits
# ----------------------------------------------------------------------
if ( $start_only )
{
mtr_print("\nStarted", started(all_servers()));
mtr_print("Using config for test", $tinfo->{name});
mtr_print("Port and socket path for server(s):");
foreach my $mysqld ( mysqlds() )
{
mtr_print ($mysqld->name() . " " . $mysqld->value('port') .
" " . $mysqld->value('socket'));
}
if ( $opt_start_exit )
{
mtr_print("Server(s) started, not waiting for them to finish");
if (IS_WINDOWS)
{
POSIX::_exit(0); # exit hangs here in ActiveState Perl
}
else
{
exit(0);
}
}
mtr_print("Waiting for server(s) to exit...");
if ( $opt_wait_all ) {
My::SafeProcess->wait_all();
mtr_print( "All servers exited" );
exit(1);
}
else {
my $proc= My::SafeProcess->wait_any();
if ( grep($proc eq $_, started(all_servers())) )
{
mtr_print("Server $proc died");
exit(1);
}
mtr_print("Unknown process $proc died");
exit(1);
}
}
my $test_timeout= start_timer(testcase_timeout($tinfo));
do_before_run_mysqltest($tinfo);
if ( $opt_check_testcases and check_testcase($tinfo, "before") ){
# Failed to record state of server or server crashed
report_failure_and_restart($tinfo);
return 1;
}
my $test= start_mysqltest($tinfo);
# Set only when we have to keep waiting after expectedly died server
my $keep_waiting_proc = 0;
while (1)
{
my $proc;
if ($keep_waiting_proc)
{
# Any other process exited?
$proc = My::SafeProcess->check_any();
if ($proc)
{
mtr_verbose ("Found exited process $proc");
}
else
{
$proc = $keep_waiting_proc;
# Also check if timer has expired, if so cancel waiting
if ( has_expired($test_timeout) )
{
$keep_waiting_proc = 0;
}
}
}
if (! $keep_waiting_proc)
{
$proc= My::SafeProcess->wait_any_timeout($test_timeout);
}
# Will be restored if we need to keep waiting
$keep_waiting_proc = 0;
unless ( defined $proc )
{
mtr_error("wait_any failed");
}
mtr_verbose("Got $proc");
# ----------------------------------------------------
# Was it the test program that exited
# ----------------------------------------------------
if ($proc eq $test)
{
my $res= $test->exit_status();
if ($res == 0 and $opt_warnings and check_warnings($tinfo) )
{
# Test case suceeded, but it has produced unexpected
# warnings, continue in $res == 1
$res= 1;
}
if ( $res == 0 )
{
my $check_res;
if ( restart_forced_by_test('force_restart') )
{
stop_all_servers($opt_shutdown_timeout);
}
elsif ( $opt_check_testcases and
$check_res= check_testcase($tinfo, "after"))
{
if ($check_res == 1) {
# Test case had sideeffects, not fatal error, just continue
stop_all_servers($opt_shutdown_timeout);
mtr_report("Resuming tests...\n");
}
else {
# Test case check failed fatally, probably a server crashed
report_failure_and_restart($tinfo);
return 1;
}
}
mtr_report_test_passed($tinfo);
}
elsif ( $res == 62 )
{
# Testcase itself tell us to skip this one
$tinfo->{skip_detected_by_test}= 1;
# Try to get reason from test log file
find_testcase_skipped_reason($tinfo);
mtr_report_test_skipped($tinfo);
# Restart if skipped due to missing perl, it may have had side effects
if ( restart_forced_by_test('force_restart_if_skipped') ||
$tinfo->{'comment'} =~ /^perl not found/ )
{
stop_all_servers($opt_shutdown_timeout);
}
}
elsif ( $res == 65 )
{
# Testprogram killed by signal
$tinfo->{comment}=
"testprogram crashed(returned code $res)";
report_failure_and_restart($tinfo);
}
elsif ( $res == 1 )
{
# Check if the test tool requests that
# an analyze script should be run
my $analyze= find_analyze_request();
if ($analyze){
run_on_all($tinfo, "analyze-$analyze");
}
# Wait a bit and see if a server died, if so report that instead
mtr_milli_sleep(100);
my $srvproc= My::SafeProcess::check_any();
if ($srvproc && grep($srvproc eq $_, started(all_servers()))) {
$proc= $srvproc;
goto SRVDIED;
}
# Test case failure reported by mysqltest
report_failure_and_restart($tinfo);
}
else
{
# mysqltest failed, probably crashed
$tinfo->{comment}=
"mysqltest failed with unexpected return code $res\n";
report_failure_and_restart($tinfo);
}
# Save info from this testcase run to mysqltest.log
if( -f $path_current_testlog)
{
mtr_appendfile_to_file($path_current_testlog, $path_testlog);
unlink($path_current_testlog);
}
return ($res == 62) ? 0 : $res;
}
# ----------------------------------------------------
# Check if it was an expected crash
# ----------------------------------------------------
my $check_crash = check_expected_crash_and_restart($proc);
if ($check_crash)
{
# Keep waiting if it returned 2, if 1 don't wait or stop waiting.
$keep_waiting_proc = 0 if $check_crash == 1;
$keep_waiting_proc = $proc if $check_crash == 2;
next;
}
SRVDIED:
# ----------------------------------------------------
# Stop the test case timer
# ----------------------------------------------------
$test_timeout= 0;
# ----------------------------------------------------
# Check if it was a server that died
# ----------------------------------------------------
if ( grep($proc eq $_, started(all_servers())) )
{
# Server failed, probably crashed
$tinfo->{comment}=
"Server $proc failed during test run" .
get_log_from_proc($proc, $tinfo->{name});
# ----------------------------------------------------
# It's not mysqltest that has exited, kill it
# ----------------------------------------------------
$test->kill();
report_failure_and_restart($tinfo);
return 1;
}
# Try to dump core for mysqltest and all servers
foreach my $proc ($test, started(all_servers()))
{
mtr_print("Trying to dump core for $proc");
if ($proc->dump_core())
{
$proc->wait_one(20);
}
}
# ----------------------------------------------------
# It's not mysqltest that has exited, kill it
# ----------------------------------------------------
$test->kill();
# ----------------------------------------------------
# Check if testcase timer expired
# ----------------------------------------------------
if ( $proc->{timeout} )
{
my $log_file_name= $opt_vardir."/log/".$tinfo->{shortname}.".log";
$tinfo->{comment}=
"Test case timeout after ".testcase_timeout($tinfo).
" seconds\n\n";
# Add 20 last executed commands from test case log file
if (-e $log_file_name)
{
$tinfo->{comment}.=
"== $log_file_name == \n".
mtr_lastlinesfromfile($log_file_name, 20)."\n";
}
$tinfo->{'timeout'}= testcase_timeout($tinfo); # Mark as timeout
run_on_all($tinfo, 'analyze-timeout');
report_failure_and_restart($tinfo);
return 1;
}
mtr_error("Unhandled process $proc exited");
}
mtr_error("Should never come here");
}
# Extract server log from after the last occurrence of named test
# Return as an array of lines
#
sub extract_server_log ($$) {
my ($error_log, $tname) = @_;
# Open the servers .err log file and read all lines
# belonging to current tets into @lines
my $Ferr = IO::File->new($error_log)
or mtr_error("Could not open file '$error_log' for reading: $!");
my @lines;
my $found_test= 0; # Set once we've found the log of this test
while ( my $line = <$Ferr> )
{
if ($found_test)
{
# If test wasn't last after all, discard what we found, test again.
if ( $line =~ /^CURRENT_TEST:/)
{
@lines= ();
$found_test= $line =~ /^CURRENT_TEST: $tname/;
}
else
{
push(@lines, $line);
}
}
else
{
# Search for beginning of test, until found
$found_test= 1 if ($line =~ /^CURRENT_TEST: $tname/);
}
}
$Ferr = undef; # Close error log file
# mysql_client_test.test sends a COM_DEBUG packet to the server
# to provoke a SAFEMALLOC leak report, ignore any warnings
# between "Begin/end safemalloc memory dump"
if ( grep(/Begin safemalloc memory dump:/, @lines) > 0)
{
my $discard_lines= 1;
foreach my $line ( @lines )
{
if ($line =~ /Begin safemalloc memory dump:/){
$discard_lines = 1;
} elsif ($line =~ /End safemalloc memory dump./){
$discard_lines = 0;
}
if ($discard_lines){
$line = "ignored";
}
}
}
return @lines;
}
# Get log from server identified from its $proc object, from named test
# Return as a single string
#
sub get_log_from_proc ($$) {
my ($proc, $name)= @_;
my $srv_log= "";
foreach my $mysqld (mysqlds()) {
if ($mysqld->{proc} eq $proc) {
my @srv_lines= extract_server_log($mysqld->value('#log-error'), $name);
$srv_log= "\nServer log from this test:\n" .
"----------SERVER LOG START-----------\n". join ("", @srv_lines) .
"----------SERVER LOG END-------------\n";
last;
}
}
return $srv_log;
}
# Perform a rough examination of the servers
# error log and write all lines that look
# suspicious into $error_log.warnings
#
sub extract_warning_lines ($$) {
my ($error_log, $tname) = @_;
my @lines= extract_server_log($error_log, $tname);
# Write all suspicious lines to $error_log.warnings file
my $warning_log = "$error_log.warnings";
my $Fwarn = IO::File->new($warning_log, "w")
or die("Could not open file '$warning_log' for writing: $!");
print $Fwarn "Suspicious lines from $error_log\n";
my @patterns =
(
qr/^Warning:|mysqld: Warning|\[Warning\]/,
qr/^Error:|\[ERROR\]/,
qr/^==\d+==\s+\S/, # valgrind errors
qr/InnoDB: Warning|InnoDB: Error/,
qr/^safe_mutex:|allocated at line/,
qr/missing DBUG_RETURN/,
qr/Attempting backtrace/,
qr/Assertion .* failed/,
);
my $skip_valgrind= 0;
foreach my $line ( @lines )
{
if ($opt_valgrind_mysqld) {
# Skip valgrind summary from tests where server has been restarted
# Should this contain memory leaks, the final report will find it
# Use a generic pattern for summaries
$skip_valgrind= 1 if $line =~ /^==\d+== [A-Z ]+ SUMMARY:/;
$skip_valgrind= 0 unless $line =~ /^==\d+==/;
next if $skip_valgrind;
}
foreach my $pat ( @patterns )
{
if ( $line =~ /$pat/ )
{
print $Fwarn $line;
last;
}
}
}
$Fwarn = undef; # Close file
}
# Run include/check-warnings.test
#
# RETURN VALUE
# 0 OK
# 1 Check failed
#
sub start_check_warnings ($$) {
my $tinfo= shift;
my $mysqld= shift;
my $name= "warnings-".$mysqld->name();
my $log_error= $mysqld->value('#log-error');
# To be communicated to the test
$ENV{MTR_LOG_ERROR}= $log_error;
extract_warning_lines($log_error, $tinfo->{name});
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $mysqld->after('mysqld'));
mtr_add_arg($args, "--skip-safemalloc");
mtr_add_arg($args, "--test-file=%s", "include/check-warnings.test");
if ( $opt_embedded_server )
{
# Get the args needed for the embedded server
# and append them to args prefixed
# with --sever-arg=
my $mysqld= $config->group('embedded')
or mtr_error("Could not get [embedded] section");
my $mysqld_args;
mtr_init_args(\$mysqld_args);
my $extra_opts= get_extra_opts($mysqld, $tinfo);
mysqld_arguments($mysqld_args, $mysqld, $extra_opts);
mtr_add_arg($args, "--server-arg=%s", $_) for @$mysqld_args;
}
my $errfile= "$opt_vardir/tmp/$name.err";
my $proc= My::SafeProcess->new
(
name => $name,
path => $exe_mysqltest,
error => $errfile,
output => $errfile,
args => \$args,
user_data => $errfile,
verbose => $opt_verbose,
);
mtr_verbose("Started $proc");
return $proc;
}
#
# Loop through our list of processes and check the error log
# for unexepcted errors and warnings
#
sub check_warnings ($) {
my ($tinfo)= @_;
my $res= 0;
my $tname= $tinfo->{name};
# Clear previous warnings
delete($tinfo->{warnings});
# Start the mysqltest processes in parallel to save time
# also makes it possible to wait for any process to exit during the check
my %started;
foreach my $mysqld ( mysqlds() )
{
if ( defined $mysqld->{'proc'} )
{
my $proc= start_check_warnings($tinfo, $mysqld);
$started{$proc->pid()}= $proc;
}
}
# Return immediately if no check proceess was started
return 0 unless ( keys %started );
my $timeout= start_timer(check_timeout());
while (1){
my $result= 0;
my $proc= My::SafeProcess->wait_any_timeout($timeout);
mtr_report("Got $proc");
if ( delete $started{$proc->pid()} ) {
# One check warning process returned
my $res= $proc->exit_status();
my $err_file= $proc->user_data();
if ( $res == 0 or $res == 62 ){
if ( $res == 0 ) {
# Check completed with problem
my $report= mtr_grab_file($err_file);
# Log to var/log/warnings file
mtr_tofile("$opt_vardir/log/warnings",
$tname."\n".$report);
$tinfo->{'warnings'}.= $report;
$result= 1;
}
if ( $res == 62 ) {
# Test case was ok and called "skip"
# Remove the .err file the check generated
unlink($err_file);
}
if ( keys(%started) == 0){
# All checks completed
return $result;
}
# Wait for next process to exit
next;
}
else
{
my $report= mtr_grab_file($err_file);
$tinfo->{comment}.=
"Could not execute 'check-warnings' for ".
"testcase '$tname' (res: $res):\n";
$tinfo->{comment}.= $report;
$result= 2;
}
}
elsif ( $proc->{timeout} ) {
$tinfo->{comment}.= "Timeout for 'check warnings' expired after "
.check_timeout()." seconds";
$result= 4;
}
else {
# Unknown process returned, most likley a crash, abort everything
$tinfo->{comment}=
"The server $proc crashed while running 'check warnings'".
get_log_from_proc($proc, $tinfo->{name});
$result= 3;
}
# Kill any check processes still running
map($_->kill(), values(%started));
return $result;
}
mtr_error("INTERNAL_ERROR: check_warnings");
}
#
# Loop through our list of processes and look for and entry
# with the provided pid, if found check for the file indicating
# expected crash and restart it.
#
sub check_expected_crash_and_restart {
my ($proc)= @_;
foreach my $mysqld ( mysqlds() )
{
next unless ( $mysqld->{proc} and $mysqld->{proc} eq $proc );
# Check if crash expected by looking at the .expect file
# in var/tmp
my $expect_file= "$opt_vardir/tmp/".$mysqld->name().".expect";
if ( -f $expect_file )
{
mtr_verbose("Crash was expected, file '$expect_file' exists");
for (my $waits = 0; $waits < 50; mtr_milli_sleep(100), $waits++)
{
# Race condition seen on Windows: try again until file not empty
next if -z $expect_file;
# If last line in expect file starts with "wait"
# sleep a little and try again, thus allowing the
# test script to control when the server should start
# up again. Keep trying for up to 5s at a time.
my $last_line= mtr_lastlinesfromfile($expect_file, 1);
if ($last_line =~ /^wait/ )
{
mtr_verbose("Test says wait before restart") if $waits == 0;
next;
}
# Ignore any partial or unknown command
next unless $last_line =~ /^restart/;
# If last line begins "restart:", the rest of the line is read as
# extra command line options to add to the restarted mysqld.
# Anything other than 'wait' or 'restart:' (with a colon) will
# result in a restart with original mysqld options.
if ($last_line =~ /restart:(.+)/) {
my @rest_opt= split(' ', $1);
$mysqld->{'restart_opts'}= \@rest_opt;
} else {
delete $mysqld->{'restart_opts'};
}
unlink($expect_file);
# Start server with same settings as last time
mysqld_start($mysqld, $mysqld->{'started_opts'});
return 1;
}
# Loop ran through: we should keep waiting after a re-check
return 2;
}
}
# Not an expected crash
return 0;
}
# Remove all files and subdirectories of a directory
sub clean_dir {
my ($dir)= @_;
mtr_verbose("clean_dir: $dir");
finddepth(
{ no_chdir => 1,
wanted => sub {
if (-d $_){
# A dir
if ($_ eq $dir){
# The dir to clean
return;
} else {
mtr_verbose("rmdir: '$_'");
rmdir($_) or mtr_warning("rmdir($_) failed: $!");
}
} else {
# Hopefully a file
mtr_verbose("unlink: '$_'");
unlink($_) or mtr_warning("unlink($_) failed: $!");
}
}
},
$dir);
}
sub clean_datadir {
mtr_verbose("Cleaning datadirs...");
if (started(all_servers()) != 0){
mtr_error("Trying to clean datadir before all servers stopped");
}
foreach my $cluster ( clusters() )
{
my $cluster_dir= "$opt_vardir/".$cluster->{name};
mtr_verbose(" - removing '$cluster_dir'");
rmtree($cluster_dir);
}
foreach my $mysqld ( mysqlds() )
{
my $mysqld_dir= dirname($mysqld->value('datadir'));
if (-d $mysqld_dir ) {
mtr_verbose(" - removing '$mysqld_dir'");
rmtree($mysqld_dir);
}
}
# Remove all files in tmp and var/tmp
clean_dir("$opt_vardir/tmp");
if ($opt_tmpdir ne "$opt_vardir/tmp"){
clean_dir($opt_tmpdir);
}
}
#
# Save datadir before it's removed
#
sub save_datadir_after_failure($$) {
my ($dir, $savedir)= @_;
mtr_report(" - saving '$dir'");
my $dir_name= basename($dir);
rename("$dir", "$savedir/$dir_name");
}
sub remove_ndbfs_from_ndbd_datadir {
my ($ndbd_datadir)= @_;
# Remove the ndb_*_fs directory from ndbd.X/ dir
foreach my $ndbfs_dir ( glob("$ndbd_datadir/ndb_*_fs") )
{
next unless -d $ndbfs_dir; # Skip if not a directory
rmtree($ndbfs_dir);
}
}
sub after_failure ($) {
my ($tinfo)= @_;
mtr_report("Saving datadirs...");
my $save_dir= "$opt_vardir/log/";
$save_dir.= $tinfo->{name};
# Add combination name if any
$save_dir.= "-$tinfo->{combination}"
if defined $tinfo->{combination};
# Save savedir path for server
$tinfo->{savedir}= $save_dir;
mkpath($save_dir) if ! -d $save_dir;
# Save the used my.cnf file
copy($path_config_file, $save_dir);
# Copy the tmp dir
copytree("$opt_vardir/tmp/", "$save_dir/tmp/");
if ( clusters() ) {
foreach my $cluster ( clusters() ) {
my $cluster_dir= "$opt_vardir/".$cluster->{name};
# Remove the fileystem of each ndbd
foreach my $ndbd ( in_cluster($cluster, ndbds()) )
{
my $ndbd_datadir= $ndbd->value("DataDir");
remove_ndbfs_from_ndbd_datadir($ndbd_datadir);
}
save_datadir_after_failure($cluster_dir, $save_dir);
}
}
else {
foreach my $mysqld ( mysqlds() ) {
my $data_dir= $mysqld->value('datadir');
save_datadir_after_failure(dirname($data_dir), $save_dir);
}
}
}
sub report_failure_and_restart ($) {
my $tinfo= shift;
if ($opt_valgrind_mysqld && ($tinfo->{'warnings'} || $tinfo->{'timeout'})) {
# In these cases we may want valgrind report from normal termination
$tinfo->{'dont_kill_server'}= 1;
}
# Shotdown properly if not to be killed (for valgrind)
stop_all_servers($tinfo->{'dont_kill_server'} ? $opt_shutdown_timeout : 0);
$tinfo->{'result'}= 'MTR_RES_FAILED';
my $test_failures= $tinfo->{'failures'} || 0;
$tinfo->{'failures'}= $test_failures + 1;
if ( $tinfo->{comment} )
{
# The test failure has been detected by mysql-test-run.pl
# when starting the servers or due to other error, the reason for
# failing the test is saved in "comment"
;
}
if ( !defined $tinfo->{logfile} )
{
my $logfile= $path_current_testlog;
if ( defined $logfile )
{
if ( -f $logfile )
{
# Test failure was detected by test tool and its report
# about what failed has been saved to file. Save the report
# in tinfo
$tinfo->{logfile}= mtr_fromfile($logfile);
# If no newlines in the test log:
# (it will contain the CURRENT_TEST written by mtr, so is not empty)
if ($tinfo->{logfile} !~ /\n/)
{
# Show how far it got before suddenly failing
$tinfo->{comment}.= "mysqltest failed but provided no output\n";
my $log_file_name= $opt_vardir."/log/".$tinfo->{shortname}.".log";
if (-e $log_file_name) {
$tinfo->{comment}.=
"The result from queries just before the failure was:".
"\n< snip >\n".
mtr_lastlinesfromfile($log_file_name, 20)."\n";
}
}
}
else
{
# The test tool report didn't exist, display an
# error message
$tinfo->{logfile}= "Could not open test tool report '$logfile'";
}
}
}
after_failure($tinfo);
mtr_report_test($tinfo);
}
sub run_sh_script {
my ($script)= @_;
return 0 unless defined $script;
mtr_verbose("Running '$script'");
my $ret= system("/bin/sh $script") >> 8;
return $ret;
}
sub mysqld_stop {
my $mysqld= shift or die "usage: mysqld_stop(<mysqld>)";
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--no-defaults");
mtr_add_arg($args, "--character-sets-dir=%s", $mysqld->value('character-sets-dir'));
mtr_add_arg($args, "--user=%s", $opt_user);
mtr_add_arg($args, "--password=");
mtr_add_arg($args, "--port=%d", $mysqld->value('port'));
mtr_add_arg($args, "--host=%s", $mysqld->value('#host'));
mtr_add_arg($args, "--connect_timeout=20");
mtr_add_arg($args, "--protocol=tcp");
mtr_add_arg($args, "shutdown");
My::SafeProcess->run
(
name => "mysqladmin shutdown ".$mysqld->name(),
path => $exe_mysqladmin,
args => \$args,
error => "/dev/null",
);
}
sub mysqld_arguments ($$$) {
my $args= shift;
my $mysqld= shift;
my $extra_opts= shift;
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
# When mysqld is run by a root user(euid is 0), it will fail
# to start unless we specify what user to run as, see BUG#30630
my $euid= $>;
if (!IS_WINDOWS and $euid == 0 and
(grep(/^--user/, @$extra_opts)) == 0) {
mtr_add_arg($args, "--user=root");
}
if ( $opt_valgrind_mysqld )
{
mtr_add_arg($args, "--skip-safemalloc");
if ( $mysql_version_id < 50100 )
{
mtr_add_arg($args, "--skip-bdb");
}
}
if ( $mysql_version_id >= 50106 && !$opt_user_args)
{
# Turn on logging to file
mtr_add_arg($args, "--log-output=file");
}
# Check if "extra_opt" contains skip-log-bin
my $skip_binlog= grep(/^(--|--loose-)skip-log-bin/, @$extra_opts);
# Indicate to mysqld it will be debugged in debugger
if ( $glob_debugger )
{
mtr_add_arg($args, "--gdb");
}
my $found_skip_core= 0;
foreach my $arg ( @$extra_opts )
{
# Allow --skip-core-file to be set in <testname>-[master|slave].opt file
if ($arg eq "--skip-core-file")
{
$found_skip_core= 1;
}
elsif ($skip_binlog and mtr_match_prefix($arg, "--binlog-format"))
{
; # Dont add --binlog-format when running without binlog
}
elsif ($arg eq "--loose-skip-log-bin" and
$mysqld->option("log-slave-updates"))
{
; # Dont add --skip-log-bin when mysqld have --log-slave-updates in config
}
else
{
mtr_add_arg($args, "%s", $arg);
}
}
$opt_skip_core = $found_skip_core;
if ( !$found_skip_core && !$opt_user_args )
{
mtr_add_arg($args, "%s", "--core-file");
}
# Enable the debug sync facility, set default wait timeout.
# Facility stays disabled if timeout value is zero.
mtr_add_arg($args, "--loose-debug-sync-timeout=%s",
$opt_debug_sync_timeout) unless $opt_user_args;
return $args;
}
sub mysqld_start ($$) {
my $mysqld= shift;
my $extra_opts= shift;
mtr_verbose(My::Options::toStr("mysqld_start", @$extra_opts));
my $exe= find_mysqld($mysqld->value('basedir'));
my $wait_for_pid_file= 1;
mtr_error("Internal error: mysqld should never be started for embedded")
if $opt_embedded_server;
my $args;
mtr_init_args(\$args);
if ( $opt_valgrind_mysqld )
{
valgrind_arguments($args, \$exe);
}
mtr_add_arg($args, "--defaults-group-suffix=%s", $mysqld->after('mysqld'));
# Add any additional options from an in-test restart
my @all_opts= @$extra_opts;
if (exists $mysqld->{'restart_opts'}) {
push (@all_opts, @{$mysqld->{'restart_opts'}});
mtr_verbose(My::Options::toStr("mysqld_start restart",
@{$mysqld->{'restart_opts'}}));
}
mysqld_arguments($args,$mysqld,\@all_opts);
if ( $opt_debug )
{
mtr_add_arg($args, "--debug=d:t:i:A,%s/log/%s.trace",
$path_vardir_trace, $mysqld->name());
}
if (IS_WINDOWS)
{
# Trick the server to send output to stderr, with --console
mtr_add_arg($args, "--console");
}
if ( $opt_gdb || $opt_manual_gdb )
{
gdb_arguments(\$args, \$exe, $mysqld->name());
}
elsif ( $opt_ddd || $opt_manual_ddd )
{
ddd_arguments(\$args, \$exe, $mysqld->name());
}
elsif ( $opt_debugger )
{
debugger_arguments(\$args, \$exe, $mysqld->name());
}
elsif ( $opt_manual_debug )
{
print "\nStart " .$mysqld->name()." in your debugger\n" .
"dir: $glob_mysql_test_dir\n" .
"exe: $exe\n" .
"args: " . join(" ", @$args) . "\n\n" .
"Waiting ....\n";
# Indicate the exe should not be started
$exe= undef;
}
else
{
# Default to not wait until pid file has been created
$wait_for_pid_file= 0;
}
# Remove the old pidfile if any
unlink($mysqld->value('pid-file'));
my $output= $mysqld->value('#log-error');
# Remember this log file for valgrind error report search
$mysqld_logs{$output}= 1 if $opt_valgrind;
# Remember data dir for gmon.out files if using gprof
$gprof_dirs{$mysqld->value('datadir')}= 1 if $opt_gprof;
if ( defined $exe )
{
$mysqld->{'proc'}= My::SafeProcess->new
(
name => $mysqld->name(),
path => $exe,
args => \$args,
output => $output,
error => $output,
append => 1,
verbose => $opt_verbose,
nocore => $opt_skip_core,
host => undef,
shutdown => sub { mysqld_stop($mysqld) },
);
mtr_verbose("Started $mysqld->{proc}");
}
if ( $wait_for_pid_file &&
!sleep_until_file_created($mysqld->value('pid-file'),
$opt_start_timeout,
$mysqld->{'proc'}))
{
my $mname= $mysqld->name();
mtr_error("Failed to start mysqld $mname with command $exe");
}
# Remember options used when starting
$mysqld->{'started_opts'}= $extra_opts;
return;
}
sub stop_all_servers () {
my $shutdown_timeout = $_[0] or 0;
mtr_verbose("Stopping all servers...");
# Kill all started servers
My::SafeProcess::shutdown($shutdown_timeout,
started(all_servers()));
# Remove pidfiles
foreach my $server ( all_servers() )
{
my $pid_file= $server->if_exist('pid-file');
unlink($pid_file) if defined $pid_file;
}
# Mark servers as stopped
map($_->{proc}= undef, all_servers());
}
# Find out if server should be restarted for this test
sub server_need_restart {
my ($tinfo, $server)= @_;
if ( using_extern() )
{
mtr_verbose_restart($server, "no restart for --extern server");
return 0;
}
if ( $tinfo->{'force_restart'} ) {
mtr_verbose_restart($server, "forced in .opt file");
return 1;
}
if ( $opt_force_restart ) {
mtr_verbose_restart($server, "forced restart turned on");
return 1;
}
if ( $tinfo->{template_path} ne $current_config_name)
{
mtr_verbose_restart($server, "using different config file");
return 1;
}
if ( $tinfo->{'master_sh'} || $tinfo->{'slave_sh'} )
{
mtr_verbose_restart($server, "sh script to run");
return 1;
}
if ( ! started($server) )
{
mtr_verbose_restart($server, "not started");
return 1;
}
my $started_tinfo= $server->{'started_tinfo'};
if ( defined $started_tinfo )
{
# Check if timezone of test that server was started
# with differs from timezone of next test
if ( timezone($started_tinfo) ne timezone($tinfo) )
{
mtr_verbose_restart($server, "different timezone");
return 1;
}
}
my $is_mysqld= grep ($server eq $_, mysqlds());
if ($is_mysqld)
{
# Check that running process was started with same options
# as the current test requires
my $extra_opts= get_extra_opts($server, $tinfo);
my $started_opts= $server->{'started_opts'};
# Also, always restart if server had been restarted with additional
# options within test.
if (!My::Options::same($started_opts, $extra_opts) ||
exists $server->{'restart_opts'})
{
my $use_dynamic_option_switch= 0;
if (!$use_dynamic_option_switch)
{
mtr_verbose_restart($server, "running with different options '" .
join(" ", @{$extra_opts}) . "' != '" .
join(" ", @{$started_opts}) . "'" );
return 1;
}
mtr_verbose(My::Options::toStr("started_opts", @$started_opts));
mtr_verbose(My::Options::toStr("extra_opts", @$extra_opts));
# Get diff and check if dynamic switch is possible
my @diff_opts= My::Options::diff($started_opts, $extra_opts);
mtr_verbose(My::Options::toStr("diff_opts", @diff_opts));
my $query= My::Options::toSQL(@diff_opts);
mtr_verbose("Attempting dynamic switch '$query'");
if (run_query($tinfo, $server, $query)){
mtr_verbose("Restart: running with different options '" .
join(" ", @{$extra_opts}) . "' != '" .
join(" ", @{$started_opts}) . "'" );
return 1;
}
# Remember the dynamically set options
$server->{'started_opts'}= $extra_opts;
}
}
# Default, no restart
return 0;
}
sub servers_need_restart($) {
my ($tinfo)= @_;
return grep { server_need_restart($tinfo, $_); } all_servers();
}
#
# Return list of specific servers
# - there is no servers in an empty config
#
sub _like { return $config ? $config->like($_[0]) : (); }
sub mysqlds { return _like('mysqld.'); }
sub ndbds { return _like('cluster_config.ndbd.');}
sub ndb_mgmds { return _like('cluster_config.ndb_mgmd.'); }
sub clusters { return _like('mysql_cluster.'); }
sub all_servers { return ( mysqlds(), ndb_mgmds(), ndbds() ); }
#
# Filter a list of servers and return only those that are part
# of the specified cluster
#
sub in_cluster {
my ($cluster)= shift;
# Return only processes for a specific cluster
return grep { $_->suffix() eq $cluster->suffix() } @_;
}
#
# Filter a list of servers and return the SafeProcess
# for only those that are started or stopped
#
sub started { return grep(defined $_, map($_->{proc}, @_)); }
sub stopped { return grep(!defined $_, map($_->{proc}, @_)); }
sub envsubst {
my $string= shift;
if ( ! defined $ENV{$string} )
{
mtr_error(".opt file references '$string' which is not set");
}
return $ENV{$string};
}
sub get_extra_opts {
# No extra options if --user-args
return \@opt_extra_mysqld_opt if $opt_user_args;
my ($mysqld, $tinfo)= @_;
my $opts=
$mysqld->option("#!use-slave-opt") ?
$tinfo->{slave_opt} : $tinfo->{master_opt};
# Expand environment variables
foreach my $opt ( @$opts )
{
$opt =~ s/\$\{(\w+)\}/envsubst($1)/ge;
$opt =~ s/\$(\w+)/envsubst($1)/ge;
}
return $opts;
}
sub stop_servers($$) {
my ($tinfo, @servers)= @_;
# Remember if we restarted for this test case (count restarts)
$tinfo->{'restarted'}= 1;
if ( join('|', @servers) eq join('|', all_servers()) )
{
# All servers are going down, use some kind of order to
# avoid too many warnings in the log files
mtr_report("Restarting all servers");
# mysqld processes
My::SafeProcess::shutdown( $opt_shutdown_timeout, started(mysqlds()) );
# cluster processes
My::SafeProcess::shutdown( $opt_shutdown_timeout,
started(ndbds(), ndb_mgmds()) );
}
else
{
mtr_report("Restarting ", started(@servers));
# Stop only some servers
My::SafeProcess::shutdown( $opt_shutdown_timeout,
started(@servers) );
}
foreach my $server (@servers)
{
# Mark server as stopped
$server->{proc}= undef;
# Forget history
delete $server->{'started_tinfo'};
delete $server->{'started_opts'};
delete $server->{'started_cnf'};
}
}
#
# start_servers
#
# Start servers not already started
#
# RETURN
# 0 OK
# 1 Start failed
#
sub start_servers($) {
my ($tinfo)= @_;
# Make sure the safe_process also exits from now on
# Could not be done before, as we don't want this for the bootstrap
if ($opt_start_exit) {
My::SafeProcess->start_exit();
}
# Start clusters
foreach my $cluster ( clusters() )
{
ndbcluster_start($cluster);
}
# Start mysqlds
foreach my $mysqld ( mysqlds() )
{
if ( $mysqld->{proc} )
{
# Already started
# Write start of testcase to log file
mark_log($mysqld->value('#log-error'), $tinfo);
next;
}
my $datadir= $mysqld->value('datadir');
if ($opt_start_dirty)
{
# Don't delete anything if starting dirty
;
}
else
{
my @options= ('log-bin', 'relay-log');
foreach my $option_name ( @options ) {
next unless $mysqld->option($option_name);
my $file_name= $mysqld->value($option_name);
next unless
defined $file_name and
-e $file_name;
mtr_debug(" -removing '$file_name'");
unlink($file_name) or die ("unable to remove file '$file_name'");
}
if (-d $datadir ) {
mtr_verbose(" - removing '$datadir'");
rmtree($datadir);
}
}
my $mysqld_basedir= $mysqld->value('basedir');
if ( $basedir eq $mysqld_basedir )
{
if (! $opt_start_dirty) # If dirty, keep possibly grown system db
{
# Copy datadir from installed system db
for my $path ( "$opt_vardir", "$opt_vardir/..") {
my $install_db= "$path/install.db";
copytree($install_db, $datadir)
if -d $install_db;
}
mtr_error("Failed to copy system db to '$datadir'")
unless -d $datadir;
}
}
else
{
mysql_install_db($mysqld); # For versional testing
mtr_error("Failed to install system db to '$datadir'")
unless -d $datadir;
}
# Create the servers tmpdir
my $tmpdir= $mysqld->value('tmpdir');
mkpath($tmpdir) unless -d $tmpdir;
# Write start of testcase to log file
mark_log($mysqld->value('#log-error'), $tinfo);
# Run <tname>-master.sh
if ($mysqld->option('#!run-master-sh') and
run_sh_script($tinfo->{master_sh}) )
{
$tinfo->{'comment'}= "Failed to execute '$tinfo->{master_sh}'";
return 1;
}
# Run <tname>-slave.sh
if ($mysqld->option('#!run-slave-sh') and
run_sh_script($tinfo->{slave_sh}))
{
$tinfo->{'comment'}= "Failed to execute '$tinfo->{slave_sh}'";
return 1;
}
if (!$opt_embedded_server)
{
my $extra_opts= get_extra_opts($mysqld, $tinfo);
mysqld_start($mysqld,$extra_opts);
# Save this test case information, so next can examine it
$mysqld->{'started_tinfo'}= $tinfo;
}
}
# Wait for clusters to start
foreach my $cluster ( clusters() )
{
if (ndbcluster_wait_started($cluster, ""))
{
# failed to start
$tinfo->{'comment'}= "Start of '".$cluster->name()."' cluster failed";
return 1;
}
}
# Wait for mysqlds to start
foreach my $mysqld ( mysqlds() )
{
next if !started($mysqld);
if (sleep_until_file_created($mysqld->value('pid-file'),
$opt_start_timeout,
$mysqld->{'proc'}) == 0) {
$tinfo->{comment}=
"Failed to start ".$mysqld->name();
my $logfile= $mysqld->value('#log-error');
if ( defined $logfile and -f $logfile )
{
my @srv_lines= extract_server_log($logfile, $tinfo->{name});
$tinfo->{logfile}= "Server log is:\n" . join ("", @srv_lines);
}
else
{
$tinfo->{logfile}= "Could not open server logfile: '$logfile'";
}
return 1;
}
}
return 0;
}
#
# Run include/check-testcase.test
# Before a testcase, run in record mode and save result file to var/tmp
# After testcase, run and compare with the recorded file, they should be equal!
#
# RETURN VALUE
# The newly started process
#
sub start_check_testcase ($$$) {
my $tinfo= shift;
my $mode= shift;
my $mysqld= shift;
my $name= "check-".$mysqld->name();
# Replace dots in name with underscore to avoid that mysqltest
# misinterpret's what the filename extension is :(
$name=~ s/\./_/g;
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--defaults-group-suffix=%s", $mysqld->after('mysqld'));
mtr_add_arg($args, "--skip-safemalloc");
mtr_add_arg($args, "--result-file=%s", "$opt_vardir/tmp/$name.result");
mtr_add_arg($args, "--test-file=%s", "include/check-testcase.test");
mtr_add_arg($args, "--verbose");
if ( $mode eq "before" )
{
mtr_add_arg($args, "--record");
}
my $errfile= "$opt_vardir/tmp/$name.err";
my $proc= My::SafeProcess->new
(
name => $name,
path => $exe_mysqltest,
error => $errfile,
output => $errfile,
args => \$args,
user_data => $errfile,
verbose => $opt_verbose,
);
mtr_report("Started $proc");
return $proc;
}
sub run_mysqltest ($) {
my $proc= start_mysqltest(@_);
$proc->wait();
}
sub start_mysqltest ($) {
my ($tinfo)= @_;
my $exe= $exe_mysqltest;
my $args;
mtr_init_args(\$args);
mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
mtr_add_arg($args, "--silent");
mtr_add_arg($args, "--skip-safemalloc");
mtr_add_arg($args, "--tmpdir=%s", $opt_tmpdir);
mtr_add_arg($args, "--character-sets-dir=%s", $path_charsetsdir);
mtr_add_arg($args, "--logdir=%s/log", $opt_vardir);
# Log line number and time for each line in .test file
mtr_add_arg($args, "--mark-progress")
if $opt_mark_progress;
mtr_add_arg($args, "--database=test");
if ( $opt_ps_protocol )
{
mtr_add_arg($args, "--ps-protocol");
}
if ( $opt_sp_protocol )
{
mtr_add_arg($args, "--sp-protocol");
}
if ( $opt_view_protocol )
{
mtr_add_arg($args, "--view-protocol");
}
if ( $opt_cursor_protocol )
{
mtr_add_arg($args, "--cursor-protocol");
}
if ( $opt_strace_client )
{
$exe= $opt_strace_client || "strace";
mtr_add_arg($args, "-o");
mtr_add_arg($args, "%s/log/mysqltest.strace", $opt_vardir);
mtr_add_arg($args, "$exe_mysqltest");
}
mtr_add_arg($args, "--timer-file=%s/log/timer", $opt_vardir);
if ( $opt_compress )
{
mtr_add_arg($args, "--compress");
}
if ( $opt_sleep )
{
mtr_add_arg($args, "--sleep=%d", $opt_sleep);
}
if ( $opt_ssl )
{
# Turn on SSL for _all_ test cases if option --ssl was used
mtr_add_arg($args, "--ssl");
}
if ( $opt_max_connections ) {
mtr_add_arg($args, "--max-connections=%d", $opt_max_connections);
}
if ( $opt_embedded_server )
{
# Get the args needed for the embedded server
# and append them to args prefixed
# with --sever-arg=
my $mysqld= $config->group('embedded')
or mtr_error("Could not get [embedded] section");
my $mysqld_args;
mtr_init_args(\$mysqld_args);
my $extra_opts= get_extra_opts($mysqld, $tinfo);
mysqld_arguments($mysqld_args, $mysqld, $extra_opts);
mtr_add_arg($args, "--server-arg=%s", $_) for @$mysqld_args;
if (IS_WINDOWS)
{
# Trick the server to send output to stderr, with --console
mtr_add_arg($args, "--server-arg=--console");
}
}
# ----------------------------------------------------------------------
# export MYSQL_TEST variable containing <path>/mysqltest <args>
# ----------------------------------------------------------------------
$ENV{'MYSQL_TEST'}= mtr_args2str($exe_mysqltest, @$args);
# ----------------------------------------------------------------------
# Add arguments that should not go into the MYSQL_TEST env var
# ----------------------------------------------------------------------
if ( $opt_valgrind_mysqltest )
{
# Prefix the Valgrind options to the argument list.
# We do this here, since we do not want to Valgrind the nested invocations
# of mysqltest; that would mess up the stderr output causing test failure.
my @args_saved = @$args;
mtr_init_args(\$args);
valgrind_arguments($args, \$exe);
mtr_add_arg($args, "%s", $_) for @args_saved;
}
mtr_add_arg($args, "--test-file=%s", $tinfo->{'path'});
# Number of lines of resut to include in failure report
mtr_add_arg($args, "--tail-lines=20");
if ( defined $tinfo->{'result_file'} ) {
mtr_add_arg($args, "--result-file=%s", $tinfo->{'result_file'});
}
client_debug_arg($args, "mysqltest");
if ( $opt_record )
{
mtr_add_arg($args, "--record");
# When recording to a non existing result file
# the name of that file is in "record_file"
if ( defined $tinfo->{'record_file'} ) {
mtr_add_arg($args, "--result-file=%s", $tinfo->{record_file});
}
}
if ( $opt_client_gdb )
{
gdb_arguments(\$args, \$exe, "client");
}
elsif ( $opt_client_ddd )
{
ddd_arguments(\$args, \$exe, "client");
}
elsif ( $opt_client_debugger )
{
debugger_arguments(\$args, \$exe, "client");
}
my $proc= My::SafeProcess->new
(
name => "mysqltest",
path => $exe,
args => \$args,
append => 1,
error => $path_current_testlog,
verbose => $opt_verbose,
);
mtr_verbose("Started $proc");
return $proc;
}
#
# Modify the exe and args so that program is run in gdb in xterm
#
sub gdb_arguments {
my $args= shift;
my $exe= shift;
my $type= shift;
# Write $args to gdb init file
my $str= join " ", map { s/"/\\"/g; "\"$_\""; } @$$args;
my $gdb_init_file= "$opt_vardir/tmp/gdbinit.$type";
# Remove the old gdbinit file
unlink($gdb_init_file);
if ( $type eq "client" )
{
# write init file for client
mtr_tofile($gdb_init_file,
"set args $str\n" .
"break main\n");
}
else
{
# write init file for mysqld
mtr_tofile($gdb_init_file,
"set args $str\n" .
"break mysql_parse\n" .
"commands 1\n" .
"disable 1\n" .
"end\n" .
"run");
}
if ( $opt_manual_gdb )
{
print "\nTo start gdb for $type, type in another window:\n";
print "gdb -cd $glob_mysql_test_dir -x $gdb_init_file $$exe\n";
# Indicate the exe should not be started
$$exe= undef;
return;
}
$$args= [];
mtr_add_arg($$args, "-title");
mtr_add_arg($$args, "$type");
mtr_add_arg($$args, "-e");
if ( $exe_libtool )
{
mtr_add_arg($$args, $exe_libtool);
mtr_add_arg($$args, "--mode=execute");
}
mtr_add_arg($$args, "gdb");
mtr_add_arg($$args, "-x");
mtr_add_arg($$args, "$gdb_init_file");
mtr_add_arg($$args, "$$exe");
$$exe= "xterm";
}
#
# Modify the exe and args so that program is run in ddd
#
sub ddd_arguments {
my $args= shift;
my $exe= shift;
my $type= shift;
# Write $args to ddd init file
my $str= join " ", map { s/"/\\"/g; "\"$_\""; } @$$args;
my $gdb_init_file= "$opt_vardir/tmp/gdbinit.$type";
# Remove the old gdbinit file
unlink($gdb_init_file);
if ( $type eq "client" )
{
# write init file for client
mtr_tofile($gdb_init_file,
"set args $str\n" .
"break main\n");
}
else
{
# write init file for mysqld
mtr_tofile($gdb_init_file,
"file $$exe\n" .
"set args $str\n" .
"break mysql_parse\n" .
"commands 1\n" .
"disable 1\n" .
"end");
}
if ( $opt_manual_ddd )
{
print "\nTo start ddd for $type, type in another window:\n";
print "ddd -cd $glob_mysql_test_dir -x $gdb_init_file $$exe\n";
# Indicate the exe should not be started
$$exe= undef;
return;
}
my $save_exe= $$exe;
$$args= [];
if ( $exe_libtool )
{
$$exe= $exe_libtool;
mtr_add_arg($$args, "--mode=execute");
mtr_add_arg($$args, "ddd");
}
else
{
$$exe= "ddd";
}
mtr_add_arg($$args, "--command=$gdb_init_file");
mtr_add_arg($$args, "$save_exe");
}
#
# Modify the exe and args so that program is run in the selected debugger
#
sub debugger_arguments {
my $args= shift;
my $exe= shift;
my $debugger= $opt_debugger || $opt_client_debugger;
if ( $debugger =~ /vcexpress|vc|devenv/ )
{
# vc[express] /debugexe exe arg1 .. argn
# Add name of the exe and /debugexe before args
unshift(@$$args, "$$exe");
unshift(@$$args, "/debugexe");
# Set exe to debuggername
$$exe= $debugger;
}
elsif ( $debugger =~ /windbg/ )
{
# windbg exe arg1 .. argn
# Add name of the exe before args
unshift(@$$args, "$$exe");
# Set exe to debuggername
$$exe= $debugger;
}
elsif ( $debugger eq "dbx" )
{
# xterm -e dbx -r exe arg1 .. argn
unshift(@$$args, $$exe);
unshift(@$$args, "-r");
unshift(@$$args, $debugger);
unshift(@$$args, "-e");
$$exe= "xterm";
}
else
{
mtr_error("Unknown argument \"$debugger\" passed to --debugger");
}
}
#
# Modify the exe and args so that program is run in valgrind
#
sub valgrind_arguments {
my $args= shift;
my $exe= shift;
if ( $opt_callgrind)
{
mtr_add_arg($args, "--tool=callgrind");
mtr_add_arg($args, "--base=$opt_vardir/log");
}
else
{
mtr_add_arg($args, "--tool=memcheck"); # From >= 2.1.2 needs this option
mtr_add_arg($args, "--leak-check=yes");
mtr_add_arg($args, "--num-callers=16");
mtr_add_arg($args, "--suppressions=%s/valgrind.supp", $glob_mysql_test_dir)
if -f "$glob_mysql_test_dir/valgrind.supp";
}
# Add valgrind options, can be overriden by user
mtr_add_arg($args, '%s', $_) for (@valgrind_args);
mtr_add_arg($args, $$exe);
$$exe= $opt_valgrind_path || "valgrind";
if ($exe_libtool)
{
# Add "libtool --mode-execute" before the test to execute
# if running in valgrind(to avoid valgrinding bash)
unshift(@$args, "--mode=execute", $$exe);
$$exe= $exe_libtool;
}
}
#
# Search server logs for valgrind reports printed at mysqld termination
#
sub valgrind_exit_reports() {
my $found_err= 0;
foreach my $log_file (keys %mysqld_logs)
{
my @culprits= ();
my $valgrind_rep= "";
my $found_report= 0;
my $err_in_report= 0;
my $LOGF = IO::File->new($log_file)
or mtr_error("Could not open file '$log_file' for reading: $!");
while ( my $line = <$LOGF> )
{
if ($line =~ /^CURRENT_TEST: (.+)$/)
{
my $testname= $1;
# If we have a report, report it if needed and start new list of tests
if ($found_report)
{
if ($err_in_report)
{
mtr_print ("Valgrind report from $log_file after tests:\n",
@culprits);
mtr_print_line();
print ("$valgrind_rep\n");
$err_in_report= 0;
}
# Make ready to collect new report
@culprits= ();
$found_report= 0;
$valgrind_rep= "";
}
push (@culprits, $testname);
next;
}
# This line marks the start of a valgrind report
$found_report= 1 if $line =~ /^==\d+== .* SUMMARY:/;
if ($found_report) {
$line=~ s/^==\d+== //;
$valgrind_rep .= $line;
$err_in_report= 1 if $line =~ /ERROR SUMMARY: [1-9]/;
$err_in_report= 1 if $line =~ /definitely lost: [1-9]/;
$err_in_report= 1 if $line =~ /possibly lost: [1-9]/;
}
}
$LOGF= undef;
if ($err_in_report) {
mtr_print ("Valgrind report from $log_file after tests:\n", @culprits);
mtr_print_line();
print ("$valgrind_rep\n");
$found_err= 1;
}
}
return $found_err;
}
#
# Usage
#
sub usage ($) {
my ($message)= @_;
if ( $message )
{
print STDERR "$message\n";
}
print <<HERE;
$0 [ OPTIONS ] [ TESTCASE ]
Options to control what engine/variation to run
embedded-server Use the embedded server, i.e. no mysqld daemons
ps-protocol Use the binary protocol between client and server
cursor-protocol Use the cursor protocol between client and server
(implies --ps-protocol)
view-protocol Create a view to execute all non updating queries
sp-protocol Create a stored procedure to execute all queries
compress Use the compressed protocol between client and server
ssl Use ssl protocol between client and server
skip-ssl Dont start server with support for ssl connections
vs-config Visual Studio configuration used to create executables
(default: MTR_VS_CONFIG environment variable)
defaults-file=<config template> Use fixed config template for all
tests
defaults-extra-file=<config template> Extra config template to add to
all generated configs
combination=<opt> Use at least twice to run tests with specified
options to mysqld
skip-combinations Ignore combination file (or options)
Options to control directories to use
tmpdir=DIR The directory where temporary files are stored
(default: ./var/tmp).
vardir=DIR The directory where files generated from the test run
is stored (default: ./var). Specifying a ramdisk or
tmpfs will speed up tests.
mem Run testsuite in "memory" using tmpfs or ramdisk
Attempts to find a suitable location
using a builtin list of standard locations
for tmpfs (/dev/shm)
The option can also be set using environment
variable MTR_MEM=[DIR]
client-bindir=PATH Path to the directory where client binaries are located
client-libdir=PATH Path to the directory where client libraries are located
Options to control what test suites or cases to run
force Continue to run the suite after failure
with-ndbcluster-only Run only tests that include "ndb" in the filename
skip-ndb[cluster] Skip all tests that need cluster. Default.
include-ndb[cluster] Enable all tests that need cluster
do-test=PREFIX or REGEX
Run test cases which name are prefixed with PREFIX
or fulfills REGEX
skip-test=PREFIX or REGEX
Skip test cases which name are prefixed with PREFIX
or fulfills REGEX
start-from=PREFIX Run test cases starting test prefixed with PREFIX where
prefix may be suite.testname or just testname
suite[s]=NAME1,..,NAMEN
Collect tests in suites from the comma separated
list of suite names.
The default is: "$DEFAULT_SUITES"
skip-rpl Skip the replication test cases.
big-test Also run tests marked as "big"
enable-disabled Run also tests marked as disabled
print-testcases Don't run the tests but print details about all the
selected tests, in the order they would be run.
Options that specify ports
mtr-port-base=# Base for port numbers, ports from this number to
port-base=# number+9 are reserved. Should be divisible by 10;
if not it will be rounded down. May be set with
environment variable MTR_PORT_BASE. If this value is
set and is not "auto", it overrides build-thread.
mtr-build-thread=# Specify unique number to calculate port number(s) from.
build-thread=# Can be set in environment variable MTR_BUILD_THREAD.
Set MTR_BUILD_THREAD="auto" to automatically aquire
a build thread id that is unique to current host
Options for test case authoring
record TESTNAME (Re)genereate the result file for TESTNAME
check-testcases Check testcases for sideeffects
mark-progress Log line number and elapsed time to <testname>.progress
Options that pass on options
mysqld=ARGS Specify additional arguments to "mysqld"
Options to run test on running server
extern option=value Run only the tests against an already started server
the options to use for connection to the extern server
must be specified using name-value pair notation
For example:
./$0 --extern socket=/tmp/mysqld.sock
Options for debugging the product
client-ddd Start mysqltest client in ddd
client-debugger=NAME Start mysqltest in the selected debugger
client-gdb Start mysqltest client in gdb
ddd Start mysqld in ddd
debug Dump trace output for all servers and client programs
debug-server Use debug version of server, but without turning on
tracing
debugger=NAME Start mysqld in the selected debugger
gdb Start the mysqld(s) in gdb
manual-debug Let user manually start mysqld in debugger, before
running test(s)
manual-gdb Let user manually start mysqld in gdb, before running
test(s)
manual-ddd Let user manually start mysqld in ddd, before running
test(s)
strace-client[=path] Create strace output for mysqltest client, optionally
specifying name and path to the trace program to use.
Example: $0 --strace-client=ktrace
max-save-core Limit the number of core files saved (to avoid filling
up disks for heavily crashing server). Defaults to
$opt_max_save_core, set to 0 for no limit. Set
it's default with MTR_MAX_SAVE_CORE
max-save-datadir Limit the number of datadir saved (to avoid filling
up disks for heavily crashing server). Defaults to
$opt_max_save_datadir, set to 0 for no limit. Set
it's default with MTR_MAX_SAVE_DATDIR
max-test-fail Limit the number of test failurs before aborting
the current test run. Defaults to
$opt_max_test_fail, set to 0 for no limit. Set
it's default with MTR_MAX_TEST_FAIL
Options for valgrind
valgrind Run the "mysqltest" and "mysqld" executables using
valgrind with default options
valgrind-all Synonym for --valgrind
valgrind-mysqltest Run the "mysqltest" and "mysql_client_test" executable
with valgrind
valgrind-mysqld Run the "mysqld" executable with valgrind
valgrind-options=ARGS Deprecated, use --valgrind-option
valgrind-option=ARGS Option to give valgrind, replaces default option(s),
can be specified more then once
valgrind-path=<EXE> Path to the valgrind executable
callgrind Instruct valgrind to use callgrind
Misc options
user=USER User for connecting to mysqld(default: $opt_user)
comment=STR Write STR to the output
timer Show test case execution time.
verbose More verbose output(use multiple times for even more)
verbose-restart Write when and why servers are restarted
start Only initialize and start the servers, using the
startup settings for the first specified test case
Example:
$0 --start alias &
start-and-exit Same as --start, but mysql-test-run terminates and
leaves just the server running
start-dirty Only start the servers (without initialization) for
the first specified test case
user-args In combination with start* and no test name, drops
arguments to mysqld except those speficied with
--mysqld (if any)
wait-all If --start or --start-dirty option is used, wait for all
servers to exit before finishing the process
fast Run as fast as possible, dont't wait for servers
to shutdown etc.
force-restart Always restart servers between tests
parallel=N Run tests in N parallel threads (default=1)
Use parallel=auto for auto-setting of N
repeat=N Run each test N number of times
retry=N Retry tests that fail N times, limit number of failures
to $opt_retry_failure
retry-failure=N Limit number of retries for a failed test
reorder Reorder tests to get fewer server restarts
help Get this help text
testcase-timeout=MINUTES Max test case run time (default $opt_testcase_timeout)
suite-timeout=MINUTES Max test suite run time (default $opt_suite_timeout)
shutdown-timeout=SECONDS Max number of seconds to wait for server shutdown
before killing servers (default $opt_shutdown_timeout)
warnings Scan the log files for warnings. Use --nowarnings
to turn off.
sleep=SECONDS Passed to mysqltest, will be used as fixed sleep time
debug-sync-timeout=NUM Set default timeout for WAIT_FOR debug sync
actions. Disable facility with NUM=0.
gcov Collect coverage information after the test.
The result is a gcov file per source and header file.
gprof Collect profiling information using gprof.
experimental=<file> Refer to list of tests considered experimental;
failures will be marked exp-fail instead of fail.
report-features First run a "test" that reports mysql features
timestamp Print timestamp before each test report line
timediff With --timestamp, also print time passed since
*previous* test started
max-connections=N Max number of open connection to server in mysqltest
Some options that control enabling a feature for normal test runs,
can be turned off by prepending 'no' to the option, e.g. --notimer.
This applies to reorder, timer, check-testcases and warnings.
HERE
exit(1);
}
sub list_options ($) {
my $hash= shift;
for (keys %$hash) {
s/([:=].*|[+!])$//;
s/\|/\n--/g;
print "--$_\n" unless /list-options/;
}
exit(1);
}
|
suhailsherif/MySQL-5.1-
|
mysql-test/mysql-test-run.pl
|
Perl
|
gpl-2.0
| 160,808
|
//Copyright (c) 2008-2010 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/qvm/q.hpp>
#include <boost/qvm/quat.hpp>
#include "test_qvm_quaternion.hpp"
#include "gold.hpp"
namespace
{
template <class T,class U> struct same_type_tester;
template <class T> struct same_type_tester<T,T> { };
template <class T,class U> void test_same_type( T, U ) { same_type_tester<T,U>(); }
void
test()
{
using namespace boost::qvm::sfinae;
test_qvm::quaternion<Q1> const x(42,2);
{
test_qvm::quaternion<Q1> const y(42,1);
test_same_type(x,x+y);
test_qvm::quaternion<Q1> r=x+y;
test_qvm::add_v(r.b,x.b,y.b);
BOOST_QVM_TEST_EQ(r.a,r.b);
}
{
test_qvm::quaternion<Q1> const y(42,1);
test_qvm::quaternion<Q2> r=qref(x)+y;
test_qvm::add_v(r.b,x.b,y.b);
BOOST_QVM_TEST_EQ(r.a,r.b);
}
{
test_qvm::quaternion<Q1> const y(42,1);
test_qvm::quaternion<Q2> r=x+qref(y);
test_qvm::add_v(r.b,x.b,y.b);
BOOST_QVM_TEST_EQ(r.a,r.b);
}
}
}
int
main()
{
test();
return boost::report_errors();
}
|
ducis/cuda-brute-force-vision
|
cuda_vision/libs/qvm/test/plus_qq_test.cpp
|
C++
|
gpl-2.0
| 1,475
|
/* Copyright (c) 2010-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.
*
*/
/*
* Qualcomm MSM Runqueue Stats and cpu utilization Interface for Userspace
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/cpu.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/notifier.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/rq_stats.h>
#include <linux/cpufreq.h>
#include <linux/kernel_stat.h>
#include <linux/tick.h>
#include <asm/smp_plat.h>
#include <linux/suspend.h>
#define MAX_LONG_SIZE 24
#define DEFAULT_RQ_POLL_JIFFIES 1
#define DEFAULT_DEF_TIMER_JIFFIES 5
struct notifier_block freq_transition;
struct notifier_block cpu_hotplug;
struct notifier_block freq_policy;
struct cpu_load_data {
cputime64_t prev_cpu_idle;
cputime64_t prev_cpu_wall;
unsigned int avg_load_maxfreq;
unsigned int samples;
unsigned int window_size;
unsigned int cur_freq;
unsigned int policy_max;
cpumask_var_t related_cpus;
struct mutex cpu_load_mutex;
};
static DEFINE_PER_CPU(struct cpu_load_data, cpuload);
static int update_average_load(unsigned int freq, unsigned int cpu)
{
int ret;
unsigned int idle_time, wall_time;
unsigned int cur_load, load_at_max_freq;
cputime64_t cur_wall_time, cur_idle_time;
struct cpu_load_data *pcpu = &per_cpu(cpuload, cpu);
struct cpufreq_policy policy;
ret = cpufreq_get_policy(&policy, cpu);
if (ret)
return -EINVAL;
cur_idle_time = get_cpu_idle_time(cpu, &cur_wall_time, 0);
wall_time = (unsigned int) (cur_wall_time - pcpu->prev_cpu_wall);
pcpu->prev_cpu_wall = cur_wall_time;
idle_time = (unsigned int) (cur_idle_time - pcpu->prev_cpu_idle);
pcpu->prev_cpu_idle = cur_idle_time;
if (unlikely(wall_time <= 0 || wall_time < idle_time))
return 0;
cur_load = 100 * (wall_time - idle_time) / wall_time;
/* Calculate the scaled load across CPU */
load_at_max_freq = (cur_load * policy.cur) / policy.max;
if (!pcpu->avg_load_maxfreq) {
/* This is the first sample in this window*/
pcpu->avg_load_maxfreq = load_at_max_freq;
pcpu->window_size = wall_time;
} else {
/*
* The is already a sample available in this window.
* Compute weighted average with prev entry, so that we get
* the precise weighted load.
*/
pcpu->avg_load_maxfreq =
((pcpu->avg_load_maxfreq * pcpu->window_size) +
(load_at_max_freq * wall_time)) /
(wall_time + pcpu->window_size);
pcpu->window_size += wall_time;
}
return 0;
}
static unsigned int report_load_at_max_freq(void)
{
int cpu;
struct cpu_load_data *pcpu;
unsigned int total_load = 0;
for_each_online_cpu(cpu) {
pcpu = &per_cpu(cpuload, cpu);
mutex_lock(&pcpu->cpu_load_mutex);
update_average_load(pcpu->cur_freq, cpu);
total_load += pcpu->avg_load_maxfreq;
pcpu->avg_load_maxfreq = 0;
mutex_unlock(&pcpu->cpu_load_mutex);
}
return total_load;
}
static int cpufreq_transition_handler(struct notifier_block *nb,
unsigned long val, void *data)
{
struct cpufreq_freqs *freqs = data;
struct cpu_load_data *this_cpu = &per_cpu(cpuload, freqs->cpu);
int j;
if (!rq_info.hotplug_enabled)
return 0;
switch (val) {
case CPUFREQ_POSTCHANGE:
for_each_cpu(j, this_cpu->related_cpus) {
struct cpu_load_data *pcpu = &per_cpu(cpuload, j);
mutex_lock(&pcpu->cpu_load_mutex);
update_average_load(freqs->old, j);
pcpu->cur_freq = freqs->new;
mutex_unlock(&pcpu->cpu_load_mutex);
}
break;
}
return 0;
}
static void update_related_cpus(void)
{
unsigned cpu;
for_each_cpu(cpu, cpu_online_mask) {
struct cpu_load_data *this_cpu = &per_cpu(cpuload, cpu);
struct cpufreq_policy cpu_policy;
cpufreq_get_policy(&cpu_policy, cpu);
cpumask_copy(this_cpu->related_cpus, cpu_policy.cpus);
}
}
static int cpu_hotplug_handler(struct notifier_block *nb,
unsigned long val, void *data)
{
unsigned int cpu = (unsigned long)data;
struct cpu_load_data *this_cpu = &per_cpu(cpuload, cpu);
if (!rq_info.hotplug_enabled)
return 0;
switch (val) {
case CPU_ONLINE:
if (!this_cpu->cur_freq)
this_cpu->cur_freq = cpufreq_quick_get(cpu);
update_related_cpus();
case CPU_ONLINE_FROZEN:
this_cpu->avg_load_maxfreq = 0;
}
return NOTIFY_OK;
}
static int system_suspend_handler(struct notifier_block *nb,
unsigned long val, void *data)
{
if (!rq_info.hotplug_enabled)
return 0;
switch (val) {
case PM_POST_HIBERNATION:
case PM_POST_SUSPEND:
case PM_POST_RESTORE:
rq_info.hotplug_disabled = 0;
break;
case PM_HIBERNATION_PREPARE:
case PM_SUSPEND_PREPARE:
rq_info.hotplug_disabled = 1;
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
static int freq_policy_handler(struct notifier_block *nb,
unsigned long event, void *data)
{
struct cpufreq_policy *policy = data;
struct cpu_load_data *this_cpu = &per_cpu(cpuload, policy->cpu);
if (event != CPUFREQ_NOTIFY)
goto out;
this_cpu->policy_max = policy->max;
pr_debug("Policy max changed from %u to %u, event %lu\n",
this_cpu->policy_max, policy->max, event);
out:
return NOTIFY_DONE;
}
static ssize_t hotplug_disable_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, MAX_LONG_SIZE, "%d\n", rq_info.hotplug_disabled);
}
static ssize_t store_hotplug_enable(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int ret;
unsigned int val;
unsigned long flags = 0;
spin_lock_irqsave(&rq_lock, flags);
ret = sscanf(buf, "%u", &val);
if (ret != 1 || val < 0 || val > 1)
return -EINVAL;
rq_info.hotplug_enabled = val;
if (rq_info.hotplug_enabled)
rq_info.hotplug_disabled = 0;
else
rq_info.hotplug_disabled = 1;
spin_unlock_irqrestore(&rq_lock, flags);
return count;
}
static ssize_t show_hotplug_enable(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, MAX_LONG_SIZE, "%d\n", rq_info.hotplug_enabled);
}
static struct kobj_attribute hotplug_disabled_attr = __ATTR_RO(hotplug_disable);
static struct kobj_attribute hotplug_enabled_attr =
__ATTR(hotplug_enable, S_IWUSR | S_IRUSR, show_hotplug_enable,
store_hotplug_enable);
static void def_work_fn(struct work_struct *work)
{
int64_t diff;
if (!rq_info.hotplug_enabled)
return;
diff = ktime_to_ns(ktime_get()) - rq_info.def_start_time;
do_div(diff, 1000 * 1000);
rq_info.def_interval = (unsigned int) diff;
/* Notify polling threads on change of value */
sysfs_notify(rq_info.kobj, NULL, "def_timer_ms");
}
static ssize_t run_queue_avg_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
unsigned int val = 0;
unsigned long flags = 0;
spin_lock_irqsave(&rq_lock, flags);
/* rq avg currently available only on one core */
val = rq_info.rq_avg;
rq_info.rq_avg = 0;
spin_unlock_irqrestore(&rq_lock, flags);
return snprintf(buf, PAGE_SIZE, "%d.%d\n", val/10, val%10);
}
static struct kobj_attribute run_queue_avg_attr = __ATTR_RO(run_queue_avg);
static ssize_t show_run_queue_poll_ms(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int ret = 0;
unsigned long flags = 0;
spin_lock_irqsave(&rq_lock, flags);
ret = snprintf(buf, MAX_LONG_SIZE, "%u\n",
jiffies_to_msecs(rq_info.rq_poll_jiffies));
spin_unlock_irqrestore(&rq_lock, flags);
return ret;
}
static ssize_t store_run_queue_poll_ms(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned int val = 0;
unsigned long flags = 0;
static DEFINE_MUTEX(lock_poll_ms);
mutex_lock(&lock_poll_ms);
spin_lock_irqsave(&rq_lock, flags);
sscanf(buf, "%u", &val);
rq_info.rq_poll_jiffies = msecs_to_jiffies(val);
spin_unlock_irqrestore(&rq_lock, flags);
mutex_unlock(&lock_poll_ms);
return count;
}
static struct kobj_attribute run_queue_poll_ms_attr =
__ATTR(run_queue_poll_ms, S_IWUSR | S_IRUSR, show_run_queue_poll_ms,
store_run_queue_poll_ms);
static ssize_t show_def_timer_ms(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, MAX_LONG_SIZE, "%u\n", rq_info.def_interval);
}
static ssize_t store_def_timer_ms(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
unsigned int val = 0;
sscanf(buf, "%u", &val);
rq_info.def_timer_jiffies = msecs_to_jiffies(val);
rq_info.def_start_time = ktime_to_ns(ktime_get());
return count;
}
static struct kobj_attribute def_timer_ms_attr =
__ATTR(def_timer_ms, S_IWUSR | S_IRUSR, show_def_timer_ms,
store_def_timer_ms);
static ssize_t show_cpu_normalized_load(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, MAX_LONG_SIZE, "%u\n",
rq_info.hotplug_enabled ? report_load_at_max_freq() : 0);
}
static struct kobj_attribute cpu_normalized_load_attr =
__ATTR(cpu_normalized_load, S_IWUSR | S_IRUSR, show_cpu_normalized_load,
NULL);
static struct attribute *rq_attrs[] = {
&cpu_normalized_load_attr.attr,
&def_timer_ms_attr.attr,
&run_queue_avg_attr.attr,
&run_queue_poll_ms_attr.attr,
&hotplug_disabled_attr.attr,
&hotplug_enabled_attr.attr,
NULL,
};
static struct attribute_group rq_attr_group = {
.attrs = rq_attrs,
};
static int init_rq_attribs(void)
{
int err;
rq_info.rq_avg = 0;
rq_info.attr_group = &rq_attr_group;
/* Create /sys/devices/system/cpu/cpu0/rq-stats/... */
rq_info.kobj = kobject_create_and_add("rq-stats",
&get_cpu_device(0)->kobj);
if (!rq_info.kobj)
return -ENOMEM;
err = sysfs_create_group(rq_info.kobj, rq_info.attr_group);
if (err)
kobject_put(rq_info.kobj);
else
kobject_uevent(rq_info.kobj, KOBJ_ADD);
return err;
}
static int __init msm_rq_stats_init(void)
{
int ret;
int i;
struct cpufreq_policy cpu_policy;
#ifndef CONFIG_SMP
/* Bail out if this is not an SMP Target */
rq_info.init = 0;
return -ENOSYS;
#endif
rq_wq = create_singlethread_workqueue("rq_stats");
BUG_ON(!rq_wq);
INIT_WORK(&rq_info.def_timer_work, def_work_fn);
spin_lock_init(&rq_lock);
rq_info.rq_poll_jiffies = DEFAULT_RQ_POLL_JIFFIES;
rq_info.def_timer_jiffies = DEFAULT_DEF_TIMER_JIFFIES;
rq_info.rq_poll_last_jiffy = 0;
rq_info.def_timer_last_jiffy = 0;
rq_info.hotplug_disabled = 1;
rq_info.hotplug_enabled = 0;
ret = init_rq_attribs();
rq_info.init = 1;
for_each_possible_cpu(i) {
struct cpu_load_data *pcpu = &per_cpu(cpuload, i);
mutex_init(&pcpu->cpu_load_mutex);
cpufreq_get_policy(&cpu_policy, i);
pcpu->policy_max = cpu_policy.max;
if (cpu_online(i))
pcpu->cur_freq = cpu_policy.cur;
cpumask_copy(pcpu->related_cpus, cpu_policy.cpus);
}
freq_transition.notifier_call = cpufreq_transition_handler;
cpu_hotplug.notifier_call = cpu_hotplug_handler;
freq_policy.notifier_call = freq_policy_handler;
cpufreq_register_notifier(&freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
register_hotcpu_notifier(&cpu_hotplug);
cpufreq_register_notifier(&freq_policy,
CPUFREQ_POLICY_NOTIFIER);
return ret;
}
late_initcall(msm_rq_stats_init);
static int __init msm_rq_stats_early_init(void)
{
#ifndef CONFIG_SMP
/* Bail out if this is not an SMP Target */
rq_info.init = 0;
return -ENOSYS;
#endif
pm_notifier(system_suspend_handler, 0);
return 0;
}
core_initcall(msm_rq_stats_early_init);
|
javilonas/Lonas_KL-SM-G901F
|
arch/arm/mach-msm/msm_rq_stats.c
|
C
|
gpl-2.0
| 11,787
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
package/module TEST
Descripción del test.
Autor: PABLO PIZARRO @ github.com/ppizarror
Fecha: AGOSTO 2016
Licencia: GPLv2
"""
__author__ = "ppizarror"
# Importación de librerías
# noinspection PyUnresolvedReferences
from _testpath import * # @UnusedWildImport
import unittest
# Constantes de los test
DISABLE_HEAVY_TESTS = True
DISABLE_HEAVY_TESTS_MSG = "Se desactivaron los tests pesados"
VERBOSE = False
# Se cargan argumentos desde la consola
if __name__ == '__main__':
from bin.arguments import argument_parser_factory
argparser = argument_parser_factory("Template Test", verbose=True, version=True,
enable_skipped_test=True).parse_args()
DISABLE_HEAVY_TESTS = argparser.enableHeavyTest
VERBOSE = argparser.verbose
# Clase UnitTest
class ModuleTest(unittest.TestCase):
def setUp(self):
"""
Inicio de los test.
:return: void
:rtype: None
"""
pass
# noinspection PyMethodMayBeStatic
def testA(self):
"""
Ejemplo de test.
:return: void
:rtype: None
"""
pass
@unittest.skipIf(DISABLE_HEAVY_TESTS, DISABLE_HEAVY_TESTS_MSG)
def testSkipped(self):
"""
Ejemplo de test saltado.
:return: void
:rtype: None
"""
pass
# Main test
if __name__ == '__main__':
runner = unittest.TextTestRunner()
itersuite = unittest.TestLoader().loadTestsFromTestCase(ModuleTest)
runner.run(itersuite)
|
ppizarror/korektor
|
test/_template.py
|
Python
|
gpl-2.0
| 1,642
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
gSerialName = '/dev/ttyS0'
gBaudrate = 9600
gTimeout = 0
gRequestByte = 1
if __name__ == "__main__":
ser = serial.Serial(
port = gSerialName,
baudrate = gBaudrate,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = gTimeout,
xonxoff = False,
rtscts = False,
writeTimeout = None,
dsrdtr = False,
interCharTimeout = None)
print 'wating for message... ',
print ser.portstr + ',',
print str(ser.timeout) + ',',
print ser.baudrate
while True:
r = ser.read(gRequestByte)
if 0 != len(r):
print repr(r)
print
ser.close()
|
yougukepp/openwrt
|
radio_tools/radio_tools/cli/serialServer.py
|
Python
|
gpl-2.0
| 822
|
/*
XEvol3D Rendering Engine . (http://gforge.osdn.net.cn/projects/xevol3d/)
Stanly.Lee 2006
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 "../xStdPch.h"
#include "xParamTable.h"
#include "xStringHash.h"
BEGIN_NAMESPACE_XEVOL3D
xParamTable::~xParamTable()
{
clear();
}
xParamTable::xParamTable()
{
}
xProperty* xParamTable::findValue(HASHVALUE valueName) const
{
xParamMap::const_iterator it = m_Values.find(valueName);
if(it == m_Values.end() )
return NULL;
return it->second;
}
xProperty* xParamTable::insertValue(const wchar_t* valueName)
{
HASHVALUE hName = toHash(valueName);
xProperty* pValue = findValue(hName);
if(pValue)
return pValue;
pValue = new xProperty( valueName );
m_Values.insert(xParamMap::value_type(hName , pValue) );
return pValue;
}
void xParamTable::setValue(const wchar_t* valueName, size_t newValue)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( (int)newValue);
}
void xParamTable::setValue(const wchar_t* valueName, int newValue)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( (int)newValue);
}
void xParamTable::setValue(const wchar_t* valueName, float newValue)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( newValue);
}
void xParamTable::setValue(const wchar_t* valueName, bool newValue)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( newValue);
}
void xParamTable::setValue(const wchar_t* valueName, const wchar_t* newValue)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( newValue);
}
void xParamTable::setValue(const wchar_t* valueName, const void* newValue , size_t dataLen)
{
xProperty* pParam = insertValue(valueName);
pParam->setValue( newValue , dataLen);
}
int xParamTable::int_value(HASHVALUE valueName) const
{
xProperty* pValue = findValue(valueName);
if(pValue == NULL)
return 0;
return pValue->int_value();
}
bool xParamTable::bool_value(HASHVALUE valueName ) const
{
xProperty* pValue = findValue(valueName);
if(pValue == NULL)
return 0;
return pValue->bool_value();
}
float xParamTable::float_value(HASHVALUE valueName) const
{
xProperty* pValue = findValue(valueName);
if(pValue == NULL)
return 0;
return pValue->float_value();
}
const wchar_t* xParamTable::string_value(HASHVALUE valueName) const
{
xProperty* pValue = findValue(valueName);
if(pValue == NULL)
return 0;
return pValue->string_value();
}
const void* xParamTable::value(HASHVALUE valueName) const
{
xProperty* pValue = findValue(valueName);
if(pValue == NULL)
return 0;
return pValue->value();
}
void xParamTable::clear()
{
for(xParamMap::iterator it = m_Values.begin(); it != m_Values.end() ; ++it)
{
xProperty* pValue = it->second;
delete pValue;
}
m_Values.clear();
}
xParamTable::HASHVALUE xParamTable::toHash(const wchar_t* pName)
{
return xStringHash(pName);
}
END_NAMESPACE_XEVOL3D
|
YOlodfssdf/evolution3d
|
xEvol3D/BaseLib/xParamTable.cpp
|
C++
|
gpl-2.0
| 3,795
|
/**
* NamespaceManager NamespaceDialog
*
* Part of BlueSpice for MediaWiki
*
* @author Robert Vogel <vogel@hallowelt.biz>
* @author Stephan Muggli <muggli@hallowelt.biz>
* @package Bluespice_Extensions
* @subpackage NamespaceManager
* @copyright Copyright (C) 2013 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later
* @filesource
*/
Ext.define( 'BS.NamespaceManager.NamespaceRemoveDialog', {
extend: 'BS.Window',
currentData: {},
selectedData: {},
afterInitComponent: function() {
var msg = mw.message( 'bs-from-something', this.nsName ).text();
this.rgNamespacenuker = Ext.create('Ext.form.RadioGroup', {
// Arrange radio buttons into two columns, distributed vertically
columns: 1,
vertical: true,
items: [
{ boxLabel: mw.message( 'bs-namespacemanager-willdelete' ).text(), name: 'rb', inputValue: '0' },
{ boxLabel: mw.message( 'bs-namespacemanager-willmove' ).text(), name: 'rb', inputValue: '1' },
{ boxLabel: mw.message( 'bs-namespacemanager-willmovesuffix', msg ).text(), name: 'rb', inputValue: '2' }
]
});
this.items = [{
html: mw.message( 'bs-namespacemanager-deletewarning' ).text()
}, {
html: mw.message( 'bs-namespacemanager-pagepresent' ).text()
},
this.rgNamespacenuker
];
this.callParent(arguments);
},
resetData: function() {
this.rgNamespacenuker.reset();
this.callParent();
},
setData: function( obj ) {
this.currentData = obj;
},
getData: function() {
this.selectedData.doarticle = this.rgNamespacenuker.getValue();
return this.selectedData;
}
} );
|
scolladogsp/wiki
|
extensions/BlueSpiceExtensions/NamespaceManager/resources/BS.NamespaceManager/NamespaceRemoveDialog.js
|
JavaScript
|
gpl-2.0
| 1,660
|
/* test.c
Implements iqueue_t tests.
Copyright:
This program is free software. See accompanying LICENSE file.
Author:
(C) 2014 Jörg Seebohn
*/
#define _GNU_SOURCE
#include "iqueue.h"
#include <errno.h>
#include <fcntl.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
// len of iqueue->sizeused
#define LENOFSIZE 256
#define TEST(COND) \
if (!(COND)) { \
fprintf(stderr, "\n%s:%d: TEST failed\n", __FILE__, __LINE__); \
exit(1); \
}
#define PASS() \
printf("."); \
fflush(stdout);
#ifdef __linux
/*
* Uses GNU malloc_stats extension.
* This function returns internal collected statistics
* about memory usage so implementing a thin wrapper
* for malloc is not necessary.
*
* Currently it is only tested on Linux platforms.
*
* What malloc_stats does:
* The GNU C lib function malloc_stats writes textual information
* to standard err in the following form:
* > Arena 0:
* > system bytes = 135168
* > in use bytes = 15000
* > Total (incl. mmap):
* > system bytes = 135168
* > in use bytes = 15000
* > max mmap regions = 0
* > max mmap bytes = 0
*
* How it is implemented:
* This function redirects standard error file descriptor
* to a pipe and reads the content of the pipe into a buffer.
* It scans backwards until the third last line is
* reached ("in use bytes") and then returns the converted
* number at the end of the line as result.
* */
int allocated_bytes(/*out*/size_t* nrofbytes)
{
int err;
int fd = -1;
int pfd[2] = { -1, -1 };
if (pipe(pfd)) {
err = errno;
perror("pipe");
goto ONERR;
}
int flags = fcntl(pfd[0], F_GETFL);
fcntl(pfd[0], F_SETFL, flags | O_NONBLOCK);
fd = dup(STDERR_FILENO);
if (fd == -1) {
err = errno;
perror("dup");
goto ONERR;
}
if (-1 == dup2(pfd[1], STDERR_FILENO)) {
err = errno;
perror("dup2");
goto ONERR;
}
malloc_stats();
char buffer[256/*must be even*/];
ssize_t len = 0;
len = read(pfd[0], buffer, sizeof(buffer));
if (len < 0) {
err = errno;
perror("read");
goto ONERR;
}
while (sizeof(buffer) == len) {
memcpy(buffer, &buffer[sizeof(buffer)/2], sizeof(buffer)/2);
len = read(pfd[0], &buffer[sizeof(buffer)/2], sizeof(buffer)/2);
if (len < 0) {
err = errno;
if (err == EWOULDBLOCK || err == EAGAIN) {
len = sizeof(buffer)/2;
break;
}
perror("read");
goto ONERR;
}
len += (int)sizeof(buffer)/2;
}
// remove last two lines
for (unsigned i = 3; i > 0 && len > 0; ) {
i -= (buffer[--len] == '\n');
}
while (len > 0
&& buffer[len-1] >= '0'
&& buffer[len-1] <= '9') {
-- len;
}
size_t used_bytes = 0;
if ( len > 0
&& buffer[len] >= '0'
&& buffer[len] <= '9' ) {
sscanf(&buffer[len], "%zu", &used_bytes);
}
if (-1 == dup2(fd, STDERR_FILENO)) {
err = errno;
perror("dup2");
goto ONERR;
}
(void) close(fd);
(void) close(pfd[0]);
(void) close(pfd[1]);
*nrofbytes = used_bytes;
return 0;
ONERR:
if (pfd[0] != -1) close(pfd[0]);
if (pfd[1] != -1) close(pfd[1]);
if (fd != -1) {
dup2(fd, STDERR_FILENO);
close(fd);
}
return err;
}
#else
// Implement allocated_bytes for your operating system here !
int allocated_bytes(size_t* nrofbytes)
{
*nrofbytes = 0;
return 0;
}
#endif
static void* thr_lock(void* param)
{
iqueue_t* queue = param;
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
cmpxchg_atomicu32(&queue->closed, 0, 1);
TEST(0 == pthread_cond_wait(&queue->writer.cond, &queue->writer.lock));
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
cmpxchg_atomicu32(&queue->closed, 1, 2);
TEST(0 == pthread_cond_wait(&queue->reader.cond, &queue->reader.lock));
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
cmpxchg_atomicu32(&queue->closed, 2, 3);
return 0;
}
static void test_initfree(void)
{
pthread_t thr;
iqueue_t* queue = 0;
// TEST new_iqueue + delete_iqueue: capacity <= LENOFSIZE
for (uint32_t capacity = 0; capacity <= LENOFSIZE; ++capacity) {
TEST(0 == new_iqueue(&queue, capacity));
TEST(0 != queue);
TEST(0 == queue->closed);
TEST(LENOFSIZE == queue->capacity);
TEST(0 == queue->iused)
for (int i = 0; i < LENOFSIZE; ++i) {
TEST(0 == queue->sizeused[0]);
}
TEST(0 == queue->readpos)
TEST(0 == queue->ifree)
for (int i = 0; i < LENOFSIZE; ++i) {
TEST(1 == queue->sizefree[0]);
}
TEST(0 == queue->writepos)
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (size_t i = 0; i < queue->capacity; ++i) {
TEST(0 == queue->msg[i]);
}
TEST(0 == delete_iqueue(&queue));
TEST(0 == queue);
}
PASS();
// TEST new_iqueue: capacity > LENOFSIZE (capacity is rounded up to next power of two)
for (uint32_t capacity = LENOFSIZE; capacity < 1024*1024; capacity *= 2) {
for (uint32_t d = 1; d < capacity; d += capacity/2) {
TEST(0 == new_iqueue(&queue, capacity+1));
TEST(0 != queue);
TEST(0 == queue->closed);
TEST(2*capacity == queue->capacity);
TEST(0 == queue->iused)
for (int i = 0; i < LENOFSIZE; ++i) {
TEST(0 == queue->sizeused[0]);
}
TEST(0 == queue->readpos)
TEST(0 == queue->ifree)
for (int i = 0; i < LENOFSIZE; ++i) {
TEST((2*capacity/LENOFSIZE) == queue->sizefree[0]);
}
TEST(0 == queue->writepos)
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (size_t i = 0; i < queue->capacity; ++i) {
TEST(0 == queue->msg[i]);
}
TEST(0 == delete_iqueue(&queue));
TEST(0 == queue);
}
}
PASS();
// TEST new_iqueue: locks
TEST(0 == new_iqueue(&queue, 0));
// test writelock + writecond
TEST(0 == pthread_create(&thr, 0, &thr_lock, queue));
for (int i = 0; i < 100000; ++i) {
if (0 != cmpxchg_atomicu32(&queue->closed, 0, 0)) break;
sched_yield();
}
// thr_lock is waiting on writecond
TEST(1 == cmpxchg_atomicu32(&queue->closed, 0, 0));
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(0 == pthread_cond_signal(&queue->writer.cond));
for (int i = 0; i < 10; ++i) {
sched_yield();
TEST(1 == cmpxchg_atomicu32(&queue->closed, 0, 0));
}
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
for (int i = 0; i < 100000; ++i) {
if (1 != cmpxchg_atomicu32(&queue->closed, 0, 0)) break;
sched_yield();
}
// thr_lock is waiting on readcond
TEST(2 == cmpxchg_atomicu32(&queue->closed, 0, 0));
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(0 == pthread_cond_signal(&queue->reader.cond));
for (int i = 0; i < 10; ++i) {
sched_yield();
TEST(2 == cmpxchg_atomicu32(&queue->closed, 0, 0));
}
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
TEST(0 == pthread_join(thr, 0));
TEST(3 == cmpxchg_atomicu32(&queue->closed, 0, 0));
TEST(0 == delete_iqueue(&queue));
TEST(0 == queue);
PASS();
// TEST new_iqueue: EINVAL
TEST(EINVAL == new_iqueue(&queue, (uint32_t)-1));
PASS();
}
static void test_query(void)
{
iqueue_t* queue = 0;
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// TEST capacity_iqueue
TEST(LENOFSIZE == capacity_iqueue(queue));
PASS();
// TEST size_iqueue
TEST(0 == size_iqueue(queue));
PASS();
// TEST capacity_iqueue: returns value from capacity
queue->capacity = 0;
TEST(0 == capacity_iqueue(queue));
for (uint16_t i = 1; i; i = (uint16_t)(i << 1)) {
queue->capacity = i;
TEST(i == capacity_iqueue(queue));
}
queue->capacity = LENOFSIZE;
PASS();
// TEST size_iqueue: returns sum of sizeused array
for (uint16_t size = 0; size <= LENOFSIZE; ++size) {
memset(queue->sizeused, 0, sizeof(queue->sizeused));
for (int si = 0; si < size; ++si) {
queue->sizeused[si] = 1;
}
// overflow values are ignored (>= queue->capacity)
for (int si = size; si < LENOFSIZE; ++si) {
queue->sizeused[si] = si & 1 ? queue->capacity : (uint32_t)-1;
}
TEST(size == size_iqueue(queue));
}
PASS();
// unprepare
TEST(0 == delete_iqueue(&queue));
}
static void* thread_simulate_read(void* param)
{
iqueue_t* queue = param;
TEST(0 == queue->reader.waitcount);
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
size_t pos = queue->writepos;
++ queue->reader.waitcount;
TEST(0 == queue->msg[pos]);
TEST(0 == pthread_cond_wait(&queue->reader.cond, &queue->reader.lock));
TEST(0 != queue->msg[pos]);
-- queue->reader.waitcount;
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
return 0;
}
static void test_trysend_single(void)
{
iqueue_t* queue = 0;
int msg[LENOFSIZE];
pthread_t thr;
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// TEST trysend_iqueue: EINVAL
TEST(EINVAL == trysend_iqueue(queue, 0));
PASS();
// TEST trysend_iqueue: EPIPE
queue->closed = 1;
TEST(EPIPE == trysend_iqueue(queue, &msg[0]));
TEST(0 == queue->msg[0]);
queue->closed = 0;
PASS();
// TEST trysend_iqueue: store into queue
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == queue->msg[i]);
TEST(0 == trysend_iqueue(queue, &msg[i]));
TEST(0 == queue->closed);
TEST(LENOFSIZE == queue->capacity);
TEST(0 == queue->iused);
TEST(0 == queue->readpos);
TEST(i == queue->ifree);
TEST((i+1) == queue->writepos);
for (unsigned si = 0; si < LENOFSIZE; ++si) {
TEST((si <= i) == queue->sizeused[si]);
TEST((si > i) == queue->sizefree[si]);
}
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
TEST(&msg[i] == queue->msg[i]);
}
PASS();
// TEST trysend_iqueue: EAGAIN
TEST(LENOFSIZE-1 == queue->ifree);
TEST(EAGAIN == trysend_iqueue(queue, &msg[1]));
TEST(LENOFSIZE-1 == queue->ifree); // wrapped around 1 time
TEST(LENOFSIZE == queue->writepos);
for (int si = 0; si < LENOFSIZE; ++si) {
TEST(&msg[si] == queue->msg[si]);
TEST(1 == queue->sizeused[si]);
TEST(0 == queue->sizefree[si]);
}
PASS();
// TEST trysend_iqueue: (ifree wraps around)
queue->ifree = LENOFSIZE-1;
queue->sizeused[LENOFSIZE-2] = 0;
queue->sizefree[LENOFSIZE-2] = 1;
queue->msg[LENOFSIZE-2] = 0;
queue->writepos = LENOFSIZE-2;
TEST(0 == trysend_iqueue(queue, &msg[LENOFSIZE-2]));
TEST(LENOFSIZE-2 == queue->ifree);
TEST(LENOFSIZE-1 == queue->writepos);
TEST(&msg[LENOFSIZE-2] == queue->msg[LENOFSIZE-2]);
TEST(1 == queue->sizeused[LENOFSIZE-2]);
TEST(0 == queue->sizefree[LENOFSIZE-2]);
// TEST trysend_iqueue: does not wakeup waiting reader
for (int si = 0; si < LENOFSIZE; ++si) {
queue->sizeused[si] = 0;
queue->sizefree[si] = 1;
queue->msg[si] = 0;
}
queue->iused = 0;
queue->ifree = 0;
for (uint32_t i = 0; i < LENOFSIZE; ++i) {
queue->writepos = i;
TEST(0 == pthread_create(&thr, 0, &thread_simulate_read, queue));
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(1 == queue->reader.waitcount);
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
TEST(0 == trysend_iqueue(queue, &msg[i]));
for (int wc = 0; wc < 100; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(1 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
// do wakeup
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(0 == pthread_cond_signal(&queue->reader.cond));
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
TEST(0 == pthread_join(thr, 0));
}
PASS();
// unprepare
TEST(0 == delete_iqueue(&queue));
}
static void* thread_call_send(void* param)
{
iqueue_t* queue = param;
TEST(0 == queue->writer.waitcount);
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
uint32_t pos = queue->writepos;
pos %= queue->capacity;
void* msg = queue->msg[pos];
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
TEST(0 == send_iqueue(queue, msg));
return 0;
}
static void test_send_single(void)
{
iqueue_t* queue = 0;
int msg[LENOFSIZE];
pthread_t thr;
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// TEST send_iqueue: EINVAL
TEST(EINVAL == send_iqueue(queue, 0));
PASS();
// TEST send_iqueue: EPIPE
queue->closed = 1;
TEST(EPIPE == send_iqueue(queue, &msg[0]));
TEST(0 == queue->msg[0]);
queue->closed = 0;
PASS();
// TEST send_iqueue: store into queue
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == queue->msg[i]);
TEST(0 == trysend_iqueue(queue, &msg[i]));
TEST(0 == queue->closed);
TEST(LENOFSIZE == queue->capacity);
TEST(0 == queue->iused);
TEST(0 == queue->readpos);
TEST(i == queue->ifree);
TEST((i+1) == queue->writepos);
for (unsigned si = 0; si < LENOFSIZE; ++si) {
TEST((si <= i) == queue->sizeused[si]);
TEST((si > i) == queue->sizefree[si]);
}
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
TEST(&msg[i] == queue->msg[i]);
}
PASS();
// TEST send_iqueue: waits (reader is simulated)
for (uint32_t i = 0; i < LENOFSIZE; ++i) {
TEST(0 == pthread_create(&thr, 0, &thread_call_send, queue));
// simulate unsolicited wakeup (send does not return)
for (int wr = 0; wr <= 5; ++wr) {
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(1 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
if (wr < 5) {
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(0 == pthread_cond_signal(&queue->writer.cond));
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
for (int wc = 0; wc < 100; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
}
}
TEST(1 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
// simulate reader
queue->readpos = i+1;
queue->msg[i] = 0;
queue->sizeused[i] = 0;
queue->sizefree[i] = 1;
// wake up writer
pthread_mutex_lock(&queue->writer.lock);
pthread_cond_signal(&queue->writer.cond);
pthread_mutex_unlock(&queue->writer.lock);
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
TEST(0 == pthread_join(thr, 0));
// writer has rewritten msg
TEST(LENOFSIZE+1+i == queue->writepos);
TEST(&msg[i] == queue->msg[i]);
TEST(1 == queue->sizeused[i]);
TEST(0 == queue->sizefree[i]);
}
PASS();
// unprepare
TEST(0 == delete_iqueue(&queue));
}
static void test_tryrecv_single(void)
{
iqueue_t* queue = 0;
int msg[LENOFSIZE];
void* rcv;
pthread_t thr;
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// TEST tryrecv_iqueue: EPIPE
queue->closed = 1;
TEST(EPIPE == tryrecv_iqueue(queue, &rcv));
queue->closed = 0;
PASS();
// fill queue
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == trysend_iqueue(queue, &msg[i]));
}
TEST(LENOFSIZE == queue->writepos);
// TEST tryrecv_iqueue: get from queue
for (uint32_t i = 0; i < LENOFSIZE; ++i) {
TEST(0 == tryrecv_iqueue(queue, &rcv));
TEST(rcv == &msg[i]);
TEST(0 == queue->closed);
TEST(LENOFSIZE == queue->capacity);
TEST(i == queue->iused);
TEST(i+1 == queue->readpos);
TEST(LENOFSIZE-1 == queue->ifree);
TEST(LENOFSIZE == queue->writepos);
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (unsigned si = 0; si < LENOFSIZE; ++si) {
TEST((si > i) == queue->sizeused[si]);
TEST((si <= i) == queue->sizefree[si]);
}
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
TEST(0 == queue->msg[i]);
}
PASS();
// TEST tryrecv_iqueue: EAGAIN
TEST(LENOFSIZE-1 == queue->iused);
TEST(EAGAIN == tryrecv_iqueue(queue, &rcv));
TEST(LENOFSIZE-1 == queue->iused); // wrapped around 1 time
TEST(LENOFSIZE == queue->readpos);
for (int si = 0; si < LENOFSIZE; ++si) {
TEST(0 == queue->msg[si]);
TEST(0 == queue->sizeused[si]);
TEST(1 == queue->sizefree[si]);
}
PASS();
// TEST tryrecv_iqueue: (iused wraps around)
queue->iused = LENOFSIZE-1;
queue->sizeused[LENOFSIZE-2] = 1;
queue->sizefree[LENOFSIZE-2] = 0;
queue->msg[LENOFSIZE-2] = &msg[LENOFSIZE-2];
queue->readpos = LENOFSIZE-2;
TEST(0 == tryrecv_iqueue(queue, &rcv));
TEST(rcv == &msg[LENOFSIZE-2]);
TEST(LENOFSIZE-2 == queue->iused);
TEST(LENOFSIZE-1 == queue->readpos);
TEST(0 == queue->msg[LENOFSIZE-2]);
TEST(0 == queue->sizeused[LENOFSIZE-2]);
TEST(1 == queue->sizefree[LENOFSIZE-2]);
// fill queue
queue->iused = 0;
queue->ifree = 0;
queue->readpos = 0;
queue->writepos = 0;
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == trysend_iqueue(queue, &msg[i]));
}
// TEST tryrecv_iqueue: does not wakeup waiting writer
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == pthread_create(&thr, 0, &thread_call_send, queue));
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(1 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
TEST(0 == tryrecv_iqueue(queue, &rcv));
TEST(rcv == &msg[i]);
for (int wc = 0; wc < 100; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(1 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
// do wakeup
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(0 == pthread_cond_signal(&queue->writer.cond));
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0));
TEST(0 == pthread_join(thr, 0));
// msg was written
TEST(LENOFSIZE+1+i == queue->writepos);
TEST(&msg[i] == queue->msg[i]);
TEST(1 == queue->sizeused[i]);
TEST(0 == queue->sizefree[i]);
}
PASS();
// unprepare
TEST(0 == delete_iqueue(&queue));
}
static void* thread_call_recv(void* param)
{
iqueue_t* queue = param;
TEST(0 == queue->reader.waitcount);
void* rcv = 0;
TEST(0 == recv_iqueue(queue, &rcv));
TEST(0 != rcv);
return 0;
}
static void test_recv_single(void)
{
iqueue_t* queue = 0;
int msg[LENOFSIZE];
void* rcv;
pthread_t thr;
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// TEST recv_iqueue: EPIPE
queue->closed = 1;
TEST(EPIPE == recv_iqueue(queue, &rcv));
queue->closed = 0;
PASS();
// fill queue
for (unsigned i = 0; i < LENOFSIZE; ++i) {
TEST(0 == trysend_iqueue(queue, &msg[i]));
}
// TEST recv_iqueue: get from queue
for (uint32_t i = 0; i < LENOFSIZE; ++i) {
TEST(0 == recv_iqueue(queue, &rcv));
TEST(rcv == &msg[i]);
TEST(0 == queue->closed);
TEST(LENOFSIZE == queue->capacity);
TEST(i == queue->iused);
TEST(i+1 == queue->readpos);
TEST(LENOFSIZE-1 == queue->ifree);
TEST(LENOFSIZE == queue->writepos);
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (unsigned si = 0; si < LENOFSIZE; ++si) {
TEST((si > i) == queue->sizeused[si]);
TEST((si <= i) == queue->sizefree[si]);
}
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
TEST(0 == queue->msg[i]);
}
PASS();
// TEST recv_iqueue: waits (writer is simulated)
for (uint32_t i = 0; i < LENOFSIZE; ++i) {
TEST(0 == pthread_create(&thr, 0, &thread_call_recv, queue));
// simulate unsolicited wakeup (recv does not return)
for (int wr = 0; wr <= 5; ++wr) {
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(1 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
if (wr < 5) {
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(0 == pthread_cond_signal(&queue->reader.cond));
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
for (int wc = 0; wc < 100; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
}
}
TEST(1 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
// simulate writer
queue->writepos = i+1;
queue->msg[i] = &msg[i];
queue->sizeused[i] = 1;
queue->sizefree[i] = 0;
// wake up reader
pthread_mutex_lock(&queue->reader.lock);
pthread_cond_signal(&queue->reader.cond);
pthread_mutex_unlock(&queue->reader.lock);
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(0 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
TEST(0 == pthread_join(thr, 0));
// reader has removed msg
TEST(LENOFSIZE+1+i == queue->readpos);
TEST(0 == queue->msg[i]);
}
PASS();
// unprepare
TEST(0 == delete_iqueue(&queue));
}
static void* thread_epipe_send(void* queue)
{
int msg;
int err = send_iqueue(queue, &msg);
if (err != EPIPE) {
printf("wrong err = %d\n", err);
}
TEST(EPIPE == err);
return 0;
}
static void* thread_epipe_recv(void* queue)
{
void* msg = 0;
int err = recv_iqueue(queue, &msg);
if (err != EPIPE) {
printf("wrong err = %d\n", err);
}
TEST(EPIPE == err);
return 0;
}
static void test_close(void)
{
iqueue_t* queue = 0;
int msg[LENOFSIZE];
pthread_t thr[100];
// TEST close_iqueue: sets closed
TEST(0 == new_iqueue(&queue, 1));
close_iqueue(queue);
TEST(1 == queue->closed);
TEST(0 == delete_iqueue(&queue));
PASS();
// TEST close_iqueue: wakes up waiting reader and writer
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// fill queue
for (int i = 0; i < LENOFSIZE; ++i) {
TEST(0 == send_iqueue(queue, &msg[i]));
}
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (unsigned i = 0; i < 50; ++i) {
TEST(0 == pthread_create(&thr[i], 0, &thread_epipe_send, queue));
}
for (int wc = 0; wc < 100000; ++wc) { // wait until started
sched_yield();
if (50 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(50 == queue->writer.waitcount);
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
// read msg without waking up writers
for (int i = 0; i < LENOFSIZE; ++i) {
void* rcv;
TEST(0 == tryrecv_iqueue(queue, &rcv));
TEST(rcv == &msg[i]);
}
// simulate no waiting writers
TEST(50 == cmpxchg_atomicsize(&queue->writer.waitcount, 50, 0));
for (int i = 0; i < 50; ++i) {
TEST(0 == pthread_create(&thr[50+i], 0, &thread_epipe_recv, queue));
}
// wait until all threads wait
for (int i = 0; i < 100000; ++i) {
sched_yield();
if (50 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(50 == queue->reader.waitcount);
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
// test
TEST(50 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
TEST(0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 50));
close_iqueue(queue);
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (int i = 0; i < 100; ++i) {
TEST(0 == pthread_join(thr[i], 0));
}
TEST(0 == delete_iqueue(&queue));
PASS();
// TEST delete_iqueue: wakes up waiting reader and writer
// prepare
TEST(0 == new_iqueue(&queue, LENOFSIZE));
// fill queue
for (int i = 0; i < LENOFSIZE; ++i) {
TEST(0 == send_iqueue(queue, &msg[i]));
}
for (unsigned i = 0; i < 50; ++i) {
TEST(0 == pthread_create(&thr[i], 0, &thread_epipe_send, queue));
}
for (int wc = 0; wc < 100000; ++wc) { // wait until started
sched_yield();
if (50 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 0)) break;
}
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(50 == queue->writer.waitcount);
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
// read msg without waking up writers
for (int i = 0; i < LENOFSIZE; ++i) {
void* rcv;
TEST(0 == tryrecv_iqueue(queue, &rcv));
TEST(rcv == &msg[i]);
}
// simulate no waiting writers
TEST(50 == cmpxchg_atomicsize(&queue->writer.waitcount, 50, 0));
for (int i = 0; i < 50; ++i) {
TEST(0 == pthread_create(&thr[50+i], 0, &thread_epipe_recv, queue));
}
for (int i = 0; i < 100000; ++i) { // wait until all threads wait
sched_yield();
if (50 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0)) break;
}
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(50 == queue->reader.waitcount);
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
// test
TEST(50 == cmpxchg_atomicsize(&queue->reader.waitcount, 0, 0));
TEST(0 == cmpxchg_atomicsize(&queue->writer.waitcount, 0, 50));
TEST(0 == delete_iqueue(&queue));
for (int i = 0; i < 100; ++i) {
TEST(0 == pthread_join(thr[i], 0));
}
PASS();
}
static void* thread_callwaitsignal(void* signal)
{
wait_iqsignal(signal);
return 0;
}
static void test_iqsignal(void)
{
iqsignal_t signal;
pthread_t thr[100];
// TEST init_iqsignal
memset(&signal, 255, sizeof(signal));
TEST(0 == init_iqsignal(&signal));
TEST(0 == signal.waitcount);
TEST(0 == signal.signalcount);
PASS();
// TEST signalcount_iqsignal
for (size_t i = 1; i; i <<= 1) {
signal.signalcount = i;
TEST(i == signalcount_iqsignal(&signal));
}
signal.signalcount = 0;
TEST(0 == signalcount_iqsignal(&signal));
PASS();
// TEST signal_iqsignal: add 1 to signalcount
for (size_t i = 1; i < 1000; ++i) {
signal_iqsignal(&signal);
TEST(i == signal.signalcount);
}
PASS();
// TEST wait_iqsignal: signalcount != 0
for (size_t i = 1; i; i <<= 1) {
signal.signalcount = i;
wait_iqsignal(&signal);
TEST(i == signal.signalcount);
TEST(0 == signal.waitcount);
}
PASS();
// TEST clearsignal_iqsignal
for (size_t i = 1; i; i <<= 1) {
signal.signalcount = i;
TEST(i == clearsignal_iqsignal(&signal));
TEST(0 == signal.signalcount);
TEST(0 == signal.waitcount);
}
TEST(0 == clearsignal_iqsignal(&signal));
TEST(0 == signal.signalcount);
TEST(0 == signal.waitcount);
PASS();
// TEST wait_iqsignal: wait
for (unsigned i = 0; i < 100; ++i) {
TEST(0 == pthread_create(&thr[i], 0, &thread_callwaitsignal, &signal));
}
for (int wc = 0; wc < 100000; ++wc) {
sched_yield();
if (100 == cmpxchg_atomicsize(&signal.waitcount, 0, 0)) break;
}
// all threads are waiting
TEST(100 == cmpxchg_atomicsize(&signal.waitcount, 0, 0));
PASS();
// TEST signal_iqsignal: wakeup all waiting threads
signal_iqsignal(&signal);
TEST(1 == signalcount_iqsignal(&signal));
for (int i = 0; i < 100000; ++i) {
sched_yield();
if (0 == cmpxchg_atomicsize(&signal.waitcount, 0, 0)) break;
}
TEST(0 == cmpxchg_atomicsize(&signal.waitcount, 0, 0));
for (int i = 0; i < 100; ++i) {
TEST(0 == pthread_join(thr[i], 0));
}
PASS();
// TEST free_iqsignal
TEST(0 == free_iqsignal(&signal));
PASS();
}
#define MAXRANGE 80000
#define MAXTHREAD 5
#define QUEUESIZE 4000
static uint32_t s_threadid;
static int s_threadtry;
static iqsignal_t s_threadsignal;
static uint8_t s_flag[MAXTHREAD][MAXRANGE];
struct range_t {
uint32_t tid;
uint32_t nr;
};
void* thread_sendrange(void* queue)
{
uint32_t myid = s_threadid;
struct range_t msg[2*QUEUESIZE];
for (;;) {
myid = s_threadid;
if (myid == cmpxchg_atomicu32(&s_threadid, myid, myid+1)) break;
}
for (uint32_t nr = 0; nr < 2*QUEUESIZE; ++nr) {
msg[nr].nr = MAXRANGE;
}
for (uint32_t nr = 0; nr < MAXRANGE; ++nr) {
uint32_t m = nr % (2*QUEUESIZE);
while (MAXRANGE != cmpxchg_atomicu32(&msg[m].nr, MAXRANGE, 0)) {
sched_yield(); // message in use
}
msg[m].tid = myid;
msg[m].nr = nr;
for (int i = 0; i < 200 && 0 != ((iqueue_t*)queue)->writer.waitcount; ++i) {
sched_yield();
}
for (int i = 0; ; ++i) {
int err = s_threadtry ? trysend_iqueue(queue, &msg[m]) : send_iqueue(queue, &msg[m]);
if (err == 0) break;
TEST(s_threadtry && err == EAGAIN);
sched_yield();
if (i == 1000000) {
printf("Sender starvation\n");
exit(1);
}
}
}
wait_iqsignal(&s_threadsignal);
return 0;
}
void* thread_recvrange(void* queue)
{
void* imsg;
for (;;) {
for (int i = 0; ; ++i) {
int err = s_threadtry ? tryrecv_iqueue(queue, &imsg) : recv_iqueue(queue, &imsg);
if (err == EPIPE) return 0;
if (err == 0) break;
TEST(err == EAGAIN);
sched_yield();
if (i == 1000000) {
printf("Receiver starvation\n");
exit(1);
}
}
struct range_t* rmsg = (struct range_t*) imsg;
TEST(rmsg->tid < MAXTHREAD);
TEST(rmsg->nr < MAXRANGE);
s_flag[rmsg->tid][rmsg->nr] = (uint8_t) (s_flag[rmsg->tid][rmsg->nr] + 1);
// message processed
cmpxchg_atomicu32(&rmsg->nr, rmsg->nr, MAXRANGE);
}
return 0;
}
void test_multi_sendrecv(void)
{
iqueue_t* queue = 0;
pthread_t rthr[MAXTHREAD/2];
pthread_t sthr[MAXTHREAD];
for (int usetry = 0; usetry <= 1; ++usetry) {
memset(s_flag, 0, sizeof(s_flag));
// start threads
s_threadid = 0;
s_threadtry = usetry;
TEST(0 == init_iqsignal(&s_threadsignal));
TEST(0 == new_iqueue(&queue, QUEUESIZE));
for (int i = 0; i < MAXTHREAD; ++i) {
TEST(0 == pthread_create(&sthr[i], 0, &thread_sendrange, queue));
if (i < MAXTHREAD/2) {
TEST(0 == pthread_create(&rthr[i], 0, &thread_recvrange, queue));
}
}
for (int i = 0; i < MAXTHREAD; ++i) {
for (int r = 0; r < MAXRANGE; ++r) {
int x = 0;
while (__sync_fetch_and_add(&s_flag[i][r], 0) == 0) {
sched_yield();
++x;
if (x == 1000000) {
// DEBUG:
printf("usetry:%d rwait:%d wwait:%d wready:%d\n", usetry, queue->reader.waitcount, queue->writer.waitcount, s_threadsignal.waitcount);
x = 0;
}
}
// == DEBUG: PRINT PROGRESS (change 0 into 1) ==
if (0 && 0 == r % 1000) {
printf("%d: %d\n", i, r);
}
}
}
close_iqueue(queue);
// stop threads
for (int i = 0; i < MAXTHREAD/2; ++i) {
TEST(0 == pthread_join(rthr[i], 0));
}
signal_iqsignal(&s_threadsignal);
for (int i = 0; i < MAXTHREAD; ++i) {
TEST(0 == pthread_join(sthr[i], 0));
}
TEST(0 == delete_iqueue(&queue));
TEST(0 == free_iqsignal(&s_threadsignal));
for (int r = 0; r < MAXRANGE; ++r) {
for (int i = 0; i < MAXTHREAD; ++i) {
TEST(s_flag[i][r] == 1);
}
}
PASS();
}
}
static void* thr_lock1(void* param)
{
iqueue1_t* queue = param;
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
cmpxchg_atomicu32(&queue->closed, 0, 1);
TEST(0 == pthread_cond_wait(&queue->writer.cond, &queue->writer.lock));
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
cmpxchg_atomicu32(&queue->closed, 1, 2);
TEST(0 == pthread_cond_wait(&queue->reader.cond, &queue->reader.lock));
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
cmpxchg_atomicu32(&queue->closed, 2, 3);
return 0;
}
static void test_initfree1(void)
{
pthread_t thr;
iqueue1_t* queue = 0;
// TEST new_iqueue
TEST(0 == new_iqueue1(&queue, 12345));
TEST(0 != queue);
TEST(12345 == queue->capacity);
TEST(0 == queue->readpos);
TEST(0 == queue->writepos);
TEST(0 == queue->closed);
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (size_t i = 0; i < queue->capacity; ++i) {
TEST(0 == queue->msg[i]);
}
// test writelock + writecond
TEST(0 == pthread_create(&thr, 0, &thr_lock1, queue));
for (int i = 0; i < 100000; ++i) {
if (0 != cmpxchg_atomicu32(&queue->closed, 0, 0)) break;
sched_yield();
}
// thr_lock1 is waiting on writecond
TEST(1 == cmpxchg_atomicu32(&queue->closed, 0, 0));
TEST(0 == pthread_mutex_lock(&queue->writer.lock));
TEST(0 == pthread_cond_signal(&queue->writer.cond));
for (int i = 0; i < 10; ++i) {
sched_yield();
TEST(1 == cmpxchg_atomicu32(&queue->closed, 0, 0));
}
TEST(0 == pthread_mutex_unlock(&queue->writer.lock));
for (int i = 0; i < 100000; ++i) {
if (1 != cmpxchg_atomicu32(&queue->closed, 0, 0)) break;
sched_yield();
}
// thr_lock is waiting on readcond
TEST(2 == cmpxchg_atomicu32(&queue->closed, 0, 0));
TEST(0 == pthread_mutex_lock(&queue->reader.lock));
TEST(0 == pthread_cond_signal(&queue->reader.cond));
for (int i = 0; i < 10; ++i) {
sched_yield();
TEST(2 == cmpxchg_atomicu32(&queue->closed, 0, 0));
}
TEST(0 == pthread_mutex_unlock(&queue->reader.lock));
TEST(0 == pthread_join(thr, 0));
TEST(3 == cmpxchg_atomicu32(&queue->closed, 0, 0));
PASS();
// TEST delete_iqueue
TEST(0 == delete_iqueue1(&queue));
TEST(0 == queue);
PASS();
// TEST new_iqueue: different size parameter
for (size_t s = 1; s < 65536; s = (s << 1) + 33) {
TEST(0 == new_iqueue1(&queue, (uint16_t) s));
TEST(0 != queue);
TEST(s == queue->capacity);
TEST(0 == queue->readpos);
TEST(0 == queue->writepos);
TEST(0 == queue->closed);
TEST(0 == queue->reader.waitcount);
TEST(0 == queue->writer.waitcount);
for (size_t i = 0; i < queue->capacity; ++i) {
TEST(0 == queue->msg[i]);
}
TEST(0 == delete_iqueue1(&queue));
TEST(0 == queue);
}
PASS();
// TEST new_iqueue: EINVAL
TEST(EINVAL == new_iqueue1(&queue, 0));
PASS();
}
static void test_query1(void)
{
iqueue1_t* queue = 0;
// prepare
TEST(0 == new_iqueue1(&queue, 128));
// TEST capacity_iqueue
TEST(128 == capacity_iqueue1(queue));
PASS();
// TEST size_iqueue
TEST(0 == size_iqueue1(queue));
PASS();
// TEST capacity_iqueue1: returns value from capacity
queue->capacity = 0;
TEST(0 == capacity_iqueue1(queue));
for (uint32_t i = 1; i; i = (uint16_t)(i << 1)) {
queue->capacity = i;
TEST(i == capacity_iqueue1(queue));
}
queue->capacity = 128;
PASS();
// TEST size_iqueue: readpos < writepos
for (uint32_t i = 1; i; i = (i << 1)) {
queue->readpos = 0;
queue->writepos = i;
TEST(i == size_iqueue1(queue));
}
for (uint32_t i = 1; i; i = (i << 1)) {
for (uint32_t s = 10; s; --s) {
queue->readpos = i;
queue->writepos = (i+s);
TEST(s == size_iqueue1(queue));
}
}
PASS();
// TEST size_iqueue: writepos < readpos
for (uint32_t i = 1; i; i = (i << 1)) {
for (uint32_t c = 65535; c >= 32768; c = (uint16_t)(c - (~c + 1))) {
queue->capacity = c;
queue->readpos = i;
queue->writepos = 0;
TEST((c - i) == size_iqueue1(queue));
}
}
for (uint32_t i = 1; i; i = (i << 1)) {
for (uint32_t s = 10; s; --s) {
for (uint32_t c = 65535; c >= 32768; c = (uint16_t)(c - (~c + 1))) {
queue->capacity = c;
queue->readpos = (i+s);
queue->writepos = i;
TEST((c-s) == size_iqueue1(queue));
}
}
}
queue->capacity = 128;
PASS();
// TEST size_iqueue: writepos == readpos
for (uint32_t c = 1; c <= 128; ++c) {
// writepos == 0
queue->capacity = c;
queue->readpos = 0;
queue->writepos = 0;
TEST(0 == size_iqueue1(queue));
queue->msg[c-1] = (void*) 1;
TEST(c == size_iqueue1(queue));
queue->msg[c-1] = (void*) 0;
}
for (uint32_t i = 1; i < 128; ++i) {
for (uint32_t c = 1; c <= 128; ++c) {
// writepos > 0
queue->capacity = c;
queue->readpos = i;
queue->writepos = i;
TEST(0 == size_iqueue1(queue));
queue->msg[i-1] = (void*) 1;
TEST(c == size_iqueue1(queue));
queue->msg[i-1] = (void*) 0;
}
}
PASS();
// unprepare
TEST(0 == delete_iqueue1(&queue));
}
void* thread_sendrange1(void* queue)
{
uint32_t myid = 0;
struct range_t msg[2*QUEUESIZE];
for (uint32_t nr = 0; nr < 2*QUEUESIZE; ++nr) {
msg[nr].nr = MAXRANGE;
}
for (uint32_t nr = 0; nr < MAXRANGE; ++nr) {
uint32_t m = nr % (2*QUEUESIZE);
while (MAXRANGE != cmpxchg_atomicu32(&msg[m].nr, MAXRANGE, 0)) {
sched_yield(); // message in use
}
msg[m].tid = myid;
msg[m].nr = nr;
for (int i = 0; ; ++i) {
int err = s_threadtry ? trysend_iqueue1(queue, &msg[m]) : send_iqueue1(queue, &msg[m]);
if (err == 0) break;
TEST(s_threadtry && err == EAGAIN);
sched_yield();
if (i == 1000000) {
printf("Sender starvation\n");
exit(1);
}
}
}
wait_iqsignal(&s_threadsignal);
return 0;
}
void* thread_recvrange1(void* queue)
{
void* imsg;
for (;;) {
for (int i = 0; ; ++i) {
int err = s_threadtry ? tryrecv_iqueue1(queue, &imsg) : recv_iqueue1(queue, &imsg);
if (err == EPIPE) return 0;
if (err == 0) break;
TEST(err == EAGAIN);
sched_yield();
if (i == 1000000) {
printf("Receiver starvation\n");
exit(1);
}
}
struct range_t* rmsg = (struct range_t*) imsg;
TEST(rmsg->tid < MAXTHREAD);
TEST(rmsg->nr < MAXRANGE);
s_flag[rmsg->tid][rmsg->nr] = (uint8_t) (s_flag[rmsg->tid][rmsg->nr] + 1);
// message processed
cmpxchg_atomicu32(&rmsg->nr, rmsg->nr, MAXRANGE);
}
return 0;
}
void test_single_sendrecv1(void)
{
iqueue1_t* queue = 0;
pthread_t rthr;
pthread_t sthr;
for (int usetry = 0; usetry <= 1; ++usetry) {
memset(s_flag, 0, sizeof(s_flag));
// start threads
s_threadid = 0;
s_threadtry = usetry;
TEST(0 == init_iqsignal(&s_threadsignal));
TEST(0 == new_iqueue1(&queue, QUEUESIZE));
TEST(0 == pthread_create(&sthr, 0, &thread_sendrange1, queue));
TEST(0 == pthread_create(&rthr, 0, &thread_recvrange1, queue));
for (int r = 0; r < MAXRANGE; ++r) {
int x = 0;
while (__sync_fetch_and_add(&s_flag[0][r], 0) == 0) {
sched_yield();
++x;
if (x == 1000000) {
// DEBUG:
printf("usetry:%d rwait:%d wwait:%d wready:%d rpos:%d wpos:%d\n", usetry, queue->reader.waitcount, queue->writer.waitcount, s_threadsignal.waitcount, queue->readpos, queue->writepos);
x = 0;
}
}
// == DEBUG: PRINT PROGRESS (change 0 into 1) ==
if (0 && 0 == r % 1000) {
printf("%d: %d\n", 0, r);
}
}
close_iqueue1(queue);
// stop threads
TEST(0 == pthread_join(rthr, 0));
signal_iqsignal(&s_threadsignal);
TEST(0 == pthread_join(sthr, 0));
TEST(0 == delete_iqueue1(&queue));
TEST(0 == free_iqsignal(&s_threadsignal));
for (int r = 0; r < MAXRANGE; ++r) {
TEST(s_flag[0][r] == 1);
}
PASS();
}
}
int main(void)
{
size_t nrofbytes;
size_t nrofbytes2;
printf("Running iqueue test: ");
fflush(stdout);
// if first call to pthread API allocates memory - repeat the tests
for (int i = 0; i < 2; ++i) {
TEST(0 == allocated_bytes(&nrofbytes));
// iqueue_t
test_initfree();
test_query();
test_trysend_single();
test_send_single();
test_tryrecv_single();
test_recv_single();
test_close();
test_iqsignal();
test_multi_sendrecv();
// iqueue1_t
test_initfree1();
test_query1();
test_single_sendrecv1();
TEST(0 == allocated_bytes(&nrofbytes2));
if (nrofbytes == nrofbytes2) break;
}
printf("\n");
if (nrofbytes != nrofbytes2) {
printf("Memory leak of '%ld' bytes!\n", (long) (nrofbytes2 - nrofbytes));
return 1;
}
return 0;
}
|
je-so/iqueue
|
src/test.c
|
C
|
gpl-2.0
| 42,544
|
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
/* Default styles */
.mod_eprivacy {
margin: 0;
padding: 1em 5em 1em 2em;
position: fixed;
bottom: 0;
left: 0;
right: 0;
background-color: #f8ee7b;
z-index: 10000;
width: 100%;
color: #333;
}
.mod_eprivacy-close {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
background-color: #e4d53f;
text-align: left;
padding: 0.5em;
font-size: 2em;
border: none !important;
}
.mod_eprivacy-close:hover {
border: none !important;
}
.mod_eprivacy-close span {
display: block;
width: 1em;
height: 1em;
overflow: hidden;
white-space: nowrap;
}
.mod_eprivacy-close span:before {
font-family: 'Fontcons';
content: "\2716";
padding: 0.2em;
}
|
hubzero/hubzero-cms
|
core/modules/mod_eprivacy/assets/css/mod_eprivacy.css
|
CSS
|
gpl-2.0
| 883
|
# nbmdt
network boot, monitor, and diagnostic tool (NBMDT).
This tool will do fault isolation and diagnostics on a linux network. It runs in several different but similar modes:
* boot. In this mode, NBMDT reads its nominal network configuration file and nominal values of the IP protocol stack, from bottom to top, with a Pass/Fail indication.
+ Verify hardware: cable is connected
+ Verify that all of the network interface cards have proper IPv4 and IPv6 addresses either from DHCP, DHCP6, automatic configuration (IPv6 only), or static configuration.
+ ping the nearby routers and gateway nodes. The routers come from the normal system routing tables.
+ Verify ARP table (IPv4) or neighbor table (IPv6).
+ Verify that DNS is working by querying all of the nameservers listed in /etc/resolv.conf
+ Verify that the remote machines specified by the sysadmin in the persistent configuration file and the nominal configuration file are reachable using the protocol/port specified.
+ Verify that local services are listening on their given ports, as given by the sysadmin in the persistent configuration file and the nominal configuration file
* monitor. In this mode, NBMDT monitors the network using its predefined configuration and the configuration it has auto-discovered. Each of the tests in boot mode are run, but in no particular sequence, and with frequecy specified by the system administrator in the persistent configuration file
* monitor. In this mode, NBMDT watches over the network periodically, and alerts on any important change.
* discovery. In this mode, NBMDT assumes that the network is correct and goes through the auto discovery process. It makes a new nominal configuration file. This file can be compared with an earlier nominal configuration file to see what changed.
The roadmap for MBMDT is:
1 Use a bash script to implement the NBMDT. Output is to a flat ASCII file, and changes are detected using the diff command
2 Use a python program that invokes other programs to examine the state of the network. Output is to a JSON file, and changes are detected using [JSON tools](https://bitbucket.org/vadim_semenov/json_tools/src/75cc15381188c760badbd5b66aef9941a42c93fa?at=default)
3 Use a python program that reads files in the /proc and /system pseudo file systems to examine the state of the network.
4 Use nagios plugins to do the same things if unavailable by other means.
See also [How to test and repair local area networks using linux tools] by Jeff Silverman
+ Version 1.0: Uses subprocesses and scrapes the outputs to gather information about the networks. Has the persistent
file, the logging at boot, the diagnostic ability, but not the monitoring or logging
+ Version 2.0: Queries the operating system for more information, monitoring, and logging.
+ Version 3.0: Supports nagios plugins, and dependencies.
|
jeffsilverm/nbmdt
|
README.md
|
Markdown
|
gpl-2.0
| 2,913
|
package net.sf.memoranda.util;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
/**
* A FileSystemView class that limits the file selections to a single root.
* <p>
* When used with the JFileChooser component the user will only be able to
* traverse the directories contained within the specified root fill.
* <p>
* The "Look In" combo box will only display the specified root.
* <p>
* The "Up One Level" button will be disable when at the root.
* <p>
* Obtained from https://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/
*/
public class SingleRootFileSystemView extends FileSystemView {
private final File root;
private final File[] roots = new File[1];
public SingleRootFileSystemView(File root) {
super();
this.root = root;
roots[0] = root;
}
@Override
public File createNewFolder(File containingDir) throws IOException {
File folder = new File(containingDir, "New Folder");
if (!folder.mkdir()) throw new IOException("Unable to create new folder");
return folder;
}
@Override
public File getDefaultDirectory() {
return root;
}
@Override
public File getHomeDirectory() {
return root;
}
@Override
public File[] getRoots() {
return roots.clone();
}
}
|
cst316/spring16project-Team-Laredo
|
src/net/sf/memoranda/util/SingleRootFileSystemView.java
|
Java
|
gpl-2.0
| 1,367
|
/**
* ownCloud Android client application
*
* Copyright (C) 2016 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.activity;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.owncloud.android.R;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.ui.dialog.LoadingDialog;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.FileStorageUtils;
public class LogHistoryActivity extends ToolbarActivity {
private static final String MAIL_ATTACHMENT_TYPE = "text/plain";
private static final String KEY_LOG_TEXT = "LOG_TEXT";
private static final String TAG = LogHistoryActivity.class.getSimpleName();
private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
private String mLogPath = FileStorageUtils.getLogPath();
private File logDIR = null;
private String mLogText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_send_file);
setupToolbar();
setTitle(getText(R.string.actionbar_logger));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button deleteHistoryButton = (Button) findViewById(R.id.deleteLogHistoryButton);
Button sendHistoryButton = (Button) findViewById(R.id.sendLogHistoryButton);
TextView logTV = (TextView) findViewById(R.id.logTV);
deleteHistoryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log_OC.deleteHistoryLogging();
finish();
}
});
sendHistoryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendMail();
}
});
if (savedInstanceState == null) {
if (mLogPath != null) {
logDIR = new File(mLogPath);
}
if (logDIR != null && logDIR.isDirectory()) {
// Show a dialog while log data is being loaded
showLoadingDialog();
// Start a new thread that will load all the log data
LoadingLogTask task = new LoadingLogTask(logTV);
task.execute();
}
} else {
mLogText = savedInstanceState.getString(KEY_LOG_TEXT);
logTV.setText(mLogText);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean retval = true;
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
retval = super.onOptionsItemSelected(item);
}
return retval;
}
/**
* Start activity for sending email with logs attached
*/
private void sendMail() {
// For the moment we need to consider the possibility that setup.xml
// does not include the "mail_logger" entry. This block prevents that
// compilation fails in this case.
String emailAddress;
try {
Class<?> stringClass = R.string.class;
Field mailLoggerField = stringClass.getField("mail_logger");
int emailAddressId = (Integer) mailLoggerField.get(null);
emailAddress = getString(emailAddressId);
} catch (Exception e) {
emailAddress = "";
}
ArrayList<Uri> uris = new ArrayList<Uri>();
// Convert from paths to Android friendly Parcelable Uri's
for (String file : Log_OC.getLogFileNames())
{
File logFile = new File(mLogPath, file);
if (logFile.exists()) {
uris.add(Uri.fromFile(logFile));
}
}
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_EMAIL, emailAddress);
String subject = String.format(getString(R.string.log_send_mail_subject), getString(R.string.app_name));
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MAIL_ATTACHMENT_TYPE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, getString(R.string.log_send_no_mail_app), Toast.LENGTH_LONG).show();
Log_OC.i(TAG, "Could not find app for sending log history.");
}
}
/**
*
* Class for loading the log data async
*
*/
private class LoadingLogTask extends AsyncTask<String, Void, String> {
private final WeakReference<TextView> textViewReference;
public LoadingLogTask(TextView logTV){
// Use of a WeakReference to ensure the TextView can be garbage collected
textViewReference = new WeakReference<TextView>(logTV);
}
protected String doInBackground(String... args) {
return readLogFile();
}
protected void onPostExecute(String result) {
if (textViewReference != null && result != null) {
final TextView logTV = textViewReference.get();
if (logTV != null) {
mLogText = result;
logTV.setText(mLogText);
dismissLoadingDialog();
}
}
}
/**
* Read and show log file info
*/
private String readLogFile() {
String[] logFileName = Log_OC.getLogFileNames();
//Read text from files
StringBuilder text = new StringBuilder();
BufferedReader br = null;
try {
String line;
for (int i = logFileName.length-1; i >= 0; i--) {
File file = new File(mLogPath,logFileName[i]);
if (file.exists()) {
// Check if FileReader is ready
if (new FileReader(file).ready()) {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// Append the log info
text.append(line);
text.append('\n');
}
}
}
}
}
catch (IOException e) {
Log_OC.d(TAG, e.getMessage().toString());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// ignore
}
}
}
return text.toString();
}
}
/**
* Show loading dialog
*/
public void showLoadingDialog() {
// Construct dialog
LoadingDialog loading = LoadingDialog.newInstance(R.string.log_progress_dialog_text, false);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
loading.show(ft, DIALOG_WAIT_TAG);
}
/**
* Dismiss loading dialog
*/
public void dismissLoadingDialog(){
Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
if (frag != null) {
LoadingDialog loading = (LoadingDialog) frag;
loading.dismiss();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/// global state
outState.putString(KEY_LOG_TEXT, mLogText);
}
}
|
PauloSantos13/android
|
src/com/owncloud/android/ui/activity/LogHistoryActivity.java
|
Java
|
gpl-2.0
| 9,170
|
<?php
class UT2_theme_ms_tilecolor_Tweak {
function settings() {
return UT2_Helper::field( 'theme_ms_tilecolor', 'color', array(
'title' => __( 'Background color for a live tile', UT2_SLUG ),
'transparent' => false
) );
}
function tweak() {
add_action( 'wp_head', array( $this, '_do' ) );
}
function _do() {
?>
<meta name="msapplication-TileColor" content="<?php echo $this->value; ?>" /><?php
}
}
|
cchuang6/wp_adora
|
wp-content/plugins/ultimate-tweaker/sections/theme_favicon_logos/theme_ms_tilecolor/tweak.php
|
PHP
|
gpl-2.0
| 446
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ImgurDotNetSDK
{
public class ImgurReplyComment
{
/// <summary>
/// Gets or sets the actual comment.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Gets or sets the ID of the image that the comment is for.
/// </summary>
public string ImageId { get; set; }
}
}
|
thegreatco/ImgurDotNetSDK
|
src/ImgurDotNetSDK45/Model/ImgurReplyComment.cs
|
C#
|
gpl-2.0
| 460
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2005, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.iaxproxy.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*
* Object Model for Asterisk
*/
#ifndef _ASTERISK_ASTOBJ_H
#define _ASTERISK_ASTOBJ_H
#include "iaxproxy/lock.h"
/*! \file
* \brief A set of macros implementing objects and containers.
* Macros are used for maximum performance, to support multiple inheritance,
* and to be easily integrated into existing structures without additional
* malloc calls, etc.
*
* These macros expect to operate on two different object types, ASTOBJs and
* ASTOBJ_CONTAINERs. These are not actual types, as any struct can be
* converted into an ASTOBJ compatible object or container using the supplied
* macros.
*
* <b>Sample Usage:</b>
* \code
* struct sample_object {
* ASTOBJ_COMPONENTS(struct sample_object);
* };
*
* struct sample_container {
* ASTOBJ_CONTAINER_COMPONENTS(struct sample_object);
* } super_container;
*
* void sample_object_destroy(struct sample_object *obj)
* {
* free(obj);
* }
*
* int init_stuff()
* {
* struct sample_object *obj1;
* struct sample_object *found_obj;
*
* obj1 = malloc(sizeof(struct sample_object));
*
* ASTOBJ_CONTAINER_INIT(&super_container);
*
* ASTOBJ_INIT(obj1);
* ASTOBJ_WRLOCK(obj1);
* ast_copy_string(obj1->name, "obj1", sizeof(obj1->name));
* ASTOBJ_UNLOCK(obj1);
*
* ASTOBJ_CONTAINER_LINK(&super_container, obj1);
*
* found_obj = ASTOBJ_CONTAINER_FIND(&super_container, "obj1");
*
* if(found_obj) {
* printf("Found object: %s", found_obj->name);
* ASTOBJ_UNREF(found_obj,sample_object_destroy);
* }
*
* ASTOBJ_CONTAINER_DESTROYALL(&super_container,sample_object_destroy);
* ASTOBJ_CONTAINER_DESTROY(&super_container);
*
* return 0;
* }
* \endcode
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#define ASTOBJ_DEFAULT_NAMELEN 80
#define ASTOBJ_DEFAULT_BUCKETS 256
#define ASTOBJ_DEFAULT_HASH ast_strhash
#define ASTOBJ_FLAG_MARKED (1 << 0) /* Object has been marked for future operation */
/* C++ is simply a syntactic crutch for those who cannot think for themselves
in an object oriented way. */
/*! \brief Lock an ASTOBJ for reading.
*/
#define ASTOBJ_RDLOCK(object) ast_mutex_lock(&(object)->_lock)
/*! \brief Lock an ASTOBJ for writing.
*/
#define ASTOBJ_WRLOCK(object) ast_mutex_lock(&(object)->_lock)
#define ASTOBJ_TRYWRLOCK(object) ast_mutex_trylock(&(object)->_lock)
/*! \brief Unlock a locked object. */
#define ASTOBJ_UNLOCK(object) ast_mutex_unlock(&(object)->_lock)
#ifdef ASTOBJ_CONTAINER_HASHMODEL
#define __ASTOBJ_HASH(type,hashes) \
type *next[hashes]
#else
#define __ASTOBJ_HASH(type,hashes) \
type *next[1]
#endif
/*! \brief Add ASTOBJ components to a struct (without locking support).
*
* \param type The datatype of the object.
* \param namelen The length to make the name char array.
* \param hashes The number of containers the object can be present in.
*
* This macro adds components to a struct to make it an ASTOBJ. This macro
* differs from ASTOBJ_COMPONENTS_FULL in that it does not create a mutex for
* locking.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct {
* ASTOBJ_COMPONENTS_NOLOCK_FULL(struct sample_struct,1,1);
* };
* \endcode
*/
#define ASTOBJ_COMPONENTS_NOLOCK_FULL(type,namelen,hashes) \
char name[namelen]; \
unsigned int refcount; \
unsigned int objflags; \
__ASTOBJ_HASH(type,hashes)
/*! \brief Add ASTOBJ components to a struct (without locking support).
*
* \param type The datatype of the object.
*
* This macro works like #ASTOBJ_COMPONENTS_NOLOCK_FULL() except it only accepts a
* type and uses default values for namelen and hashes.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_componets {
* ASTOBJ_COMPONENTS_NOLOCK(struct sample_struct);
* };
* \endcode
*/
#define ASTOBJ_COMPONENTS_NOLOCK(type) \
ASTOBJ_COMPONENTS_NOLOCK_FULL(type,ASTOBJ_DEFAULT_NAMELEN,1)
/*! \brief Add ASTOBJ components to a struct (with locking support).
*
* \param type The datatype of the object.
*
* This macro works like #ASTOBJ_COMPONENTS_NOLOCK() except it includes locking
* support.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct {
* ASTOBJ_COMPONENTS(struct sample_struct);
* };
* \endcode
*/
#define ASTOBJ_COMPONENTS(type) \
ASTOBJ_COMPONENTS_NOLOCK(type); \
ast_mutex_t _lock;
/*! \brief Add ASTOBJ components to a struct (with locking support).
*
* \param type The datatype of the object.
* \param namelen The length to make the name char array.
* \param hashes The number of containers the object can be present in.
*
* This macro adds components to a struct to make it an ASTOBJ and includes
* support for locking.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct {
* ASTOBJ_COMPONENTS_FULL(struct sample_struct,1,1);
* };
* \endcode
*/
#define ASTOBJ_COMPONENTS_FULL(type,namelen,hashes) \
ASTOBJ_COMPONENTS_NOLOCK_FULL(type,namelen,hashes); \
ast_mutex_t _lock;
/*! \brief Increment an object reference count.
* \param object A pointer to the object to operate on.
* \return The object.
*/
#define ASTOBJ_REF(object) \
({ \
ASTOBJ_WRLOCK(object); \
(object)->refcount++; \
ASTOBJ_UNLOCK(object); \
(object); \
})
/*! \brief Decrement the reference count on an object.
*
* \param object A pointer the object to operate on.
* \param destructor The destructor to call if the object is no longer referenced. It will be passed the pointer as an argument.
*
* This macro unreferences an object and calls the specfied destructor if the
* object is no longer referenced. The destructor should free the object if it
* was dynamically allocated.
*/
#define ASTOBJ_UNREF(object,destructor) \
do { \
int newcount = 0; \
ASTOBJ_WRLOCK(object); \
if (__builtin_expect((object)->refcount > 0, 1)) \
newcount = --((object)->refcount); \
else \
ast_log(AST_LOG_WARNING, "Unreferencing unreferenced (object)!\n"); \
ASTOBJ_UNLOCK(object); \
if (newcount == 0) { \
ast_mutex_destroy(&(object)->_lock); \
destructor((object)); \
} \
(object) = NULL; \
} while(0)
/*! \brief Mark an ASTOBJ by adding the #ASTOBJ_FLAG_MARKED flag to its objflags mask.
* \param object A pointer to the object to operate on.
*
* This macro "marks" an object. Marked objects can later be unlinked from a container using
* #ASTOBJ_CONTAINER_PRUNE_MARKED().
*
*/
#define ASTOBJ_MARK(object) \
do { \
ASTOBJ_WRLOCK(object); \
(object)->objflags |= ASTOBJ_FLAG_MARKED; \
ASTOBJ_UNLOCK(object); \
} while(0)
/*! \brief Unmark an ASTOBJ by subtracting the #ASTOBJ_FLAG_MARKED flag from its objflags mask.
* \param object A pointer to the object to operate on.
*/
#define ASTOBJ_UNMARK(object) \
do { \
ASTOBJ_WRLOCK(object); \
(object)->objflags &= ~ASTOBJ_FLAG_MARKED; \
ASTOBJ_UNLOCK(object); \
} while(0)
/*! \brief Initialize an object.
* \param object A pointer to the object to operate on.
*
* \note This should only be used on objects that support locking (objects
* created with #ASTOBJ_COMPONENTS() or #ASTOBJ_COMPONENTS_FULL())
*/
#define ASTOBJ_INIT(object) \
do { \
ast_mutex_init(&(object)->_lock); \
object->name[0] = '\0'; \
object->refcount = 1; \
} while(0)
/* Containers for objects -- current implementation is linked lists, but
should be able to be converted to hashes relatively easily */
/*! \brief Lock an ASTOBJ_CONTAINER for reading.
*/
#define ASTOBJ_CONTAINER_RDLOCK(container) ast_mutex_lock(&(container)->_lock)
/*! \brief Lock an ASTOBJ_CONTAINER for writing.
*/
#define ASTOBJ_CONTAINER_WRLOCK(container) ast_mutex_lock(&(container)->_lock)
/*! \brief Unlock an ASTOBJ_CONTAINER. */
#define ASTOBJ_CONTAINER_UNLOCK(container) ast_mutex_unlock(&(container)->_lock)
#ifdef ASTOBJ_CONTAINER_HASHMODEL
#error "Hash model for object containers not yet implemented!"
#else
/* Linked lists */
/*! \brief Create a container for ASTOBJs (without locking support).
*
* \param type The type of objects the container will hold.
* \param hashes Currently unused.
* \param buckets Currently unused.
*
* This macro is used to create a container for ASTOBJs without locking
* support.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_nolock_container {
* ASTOBJ_CONTAINER_COMPONENTS_NOLOCK_FULL(struct sample_struct,1,1);
* };
* \endcode
*/
#define ASTOBJ_CONTAINER_COMPONENTS_NOLOCK_FULL(type,hashes,buckets) \
type *head
/*! \brief Initialize a container.
*
* \param container A pointer to the container to initialize.
* \param hashes Currently unused.
* \param buckets Currently unused.
*
* This macro initializes a container. It should only be used on containers
* that support locking.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_container {
* ASTOBJ_CONTAINER_COMPONENTS_FULL(struct sample_struct,1,1);
* } container;
*
* int func()
* {
* ASTOBJ_CONTAINER_INIT_FULL(&container,1,1);
* }
* \endcode
*/
#define ASTOBJ_CONTAINER_INIT_FULL(container,hashes,buckets) \
do { \
ast_mutex_init(&(container)->_lock); \
} while(0)
/*! \brief Destroy a container.
*
* \param container A pointer to the container to destroy.
* \param hashes Currently unused.
* \param buckets Currently unused.
*
* This macro frees up resources used by a container. It does not operate on
* the objects in the container. To unlink the objects from the container use
* #ASTOBJ_CONTAINER_DESTROYALL().
*
* \note This macro should only be used on containers with locking support.
*/
#define ASTOBJ_CONTAINER_DESTROY_FULL(container,hashes,buckets) \
do { \
ast_mutex_destroy(&(container)->_lock); \
} while(0)
/*! \brief Iterate through the objects in a container.
*
* \param container A pointer to the container to traverse.
* \param continue A condition to allow the traversal to continue.
* \param eval A statement to evaluate in the iteration loop.
*
* This is macro is a little complicated, but it may help to think of it as a
* loop. Basically it iterates through the specfied containter as long as the
* condition is met. Two variables, iterator and next, are provided for use in
* your \p eval statement. See the sample code for an example.
*
* <b>Sample Usage:</b>
* \code
* ASTOBJ_CONTAINER_TRAVERSE(&sample_container,1, {
* ASTOBJ_RDLOCK(iterator);
* printf("Currently iterating over '%s'\n", iterator->name);
* ASTOBJ_UNLOCK(iterator);
* } );
* \endcode
*
* \code
* ASTOBJ_CONTAINER_TRAVERSE(&sample_container,1, sample_func(iterator));
* \endcode
*/
#define ASTOBJ_CONTAINER_TRAVERSE(container,continue,eval) \
do { \
typeof((container)->head) iterator; \
typeof((container)->head) next; \
ASTOBJ_CONTAINER_RDLOCK(container); \
next = (container)->head; \
while((continue) && (iterator = next)) { \
next = iterator->next[0]; \
eval; \
} \
ASTOBJ_CONTAINER_UNLOCK(container); \
} while(0)
/*! \brief Find an object in a container.
*
* \param container A pointer to the container to search.
* \param namestr The name to search for.
*
* Use this function to find an object with the specfied name in a container.
*
* \note When the returned object is no longer in use, #ASTOBJ_UNREF() should
* be used to free the additional reference created by this macro.
*
* \return A new reference to the object located or NULL if nothing is found.
*/
#define ASTOBJ_CONTAINER_FIND(container,namestr) \
({ \
typeof((container)->head) found = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, !found, do { \
if (!(strcasecmp(iterator->name, (namestr)))) \
found = ASTOBJ_REF(iterator); \
} while (0)); \
found; \
})
/*! \brief Find an object in a container.
*
* \param container A pointer to the container to search.
* \param data The data to search for.
* \param field The field/member of the container's objects to search.
* \param hashfunc The hash function to use, currently not implemented.
* \param hashoffset The hash offset to use, currently not implemented.
* \param comparefunc The function used to compare the field and data values.
*
* This macro iterates through a container passing the specified field and data
* elements to the specified comparefunc. The function should return 0 when a match is found.
*
* \note When the returned object is no longer in use, #ASTOBJ_UNREF() should
* be used to free the additional reference created by this macro.
*
* \return A pointer to the object located or NULL if nothing is found.
*/
#define ASTOBJ_CONTAINER_FIND_FULL(container,data,field,hashfunc,hashoffset,comparefunc) \
({ \
typeof((container)->head) found = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, !found, do { \
ASTOBJ_RDLOCK(iterator); \
if (!(comparefunc(iterator->field, (data)))) { \
found = ASTOBJ_REF(iterator); \
} \
ASTOBJ_UNLOCK(iterator); \
} while (0)); \
found; \
})
/*! \brief Empty a container.
*
* \param container A pointer to the container to operate on.
* \param destructor A destructor function to call on each object.
*
* This macro loops through a container removing all the items from it using
* #ASTOBJ_UNREF(). This does not destroy the container itself, use
* #ASTOBJ_CONTAINER_DESTROY() for that.
*
* \note If any object in the container is only referenced by the container,
* the destructor will be called for that object once it has been removed.
*/
#define ASTOBJ_CONTAINER_DESTROYALL(container,destructor) \
do { \
typeof((container)->head) iterator; \
ASTOBJ_CONTAINER_WRLOCK(container); \
while((iterator = (container)->head)) { \
(container)->head = (iterator)->next[0]; \
ASTOBJ_UNREF(iterator,destructor); \
} \
ASTOBJ_CONTAINER_UNLOCK(container); \
} while(0)
/*! \brief Remove an object from a container.
*
* \param container A pointer to the container to operate on.
* \param obj A pointer to the object to remove.
*
* This macro iterates through a container and removes the specfied object if
* it exists in the container.
*
* \note This macro does not destroy any objects, it simply unlinks
* them from the list. No destructors are called.
*
* \return The container's reference to the removed object or NULL if no
* matching object was found.
*/
#define ASTOBJ_CONTAINER_UNLINK(container,obj) \
({ \
typeof((container)->head) found = NULL; \
typeof((container)->head) prev = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, !found, do { \
if (iterator == obj) { \
found = iterator; \
found->next[0] = NULL; \
ASTOBJ_CONTAINER_WRLOCK(container); \
if (prev) \
prev->next[0] = next; \
else \
(container)->head = next; \
ASTOBJ_CONTAINER_UNLOCK(container); \
} \
prev = iterator; \
} while (0)); \
found; \
})
/*! \brief Find and remove an object from a container.
*
* \param container A pointer to the container to operate on.
* \param namestr The name of the object to remove.
*
* This macro iterates through a container and removes the first object with
* the specfied name from the container.
*
* \note This macro does not destroy any objects, it simply unlinks
* them. No destructors are called.
*
* \return The container's reference to the removed object or NULL if no
* matching object was found.
*/
#define ASTOBJ_CONTAINER_FIND_UNLINK(container,namestr) \
({ \
typeof((container)->head) found = NULL; \
typeof((container)->head) prev = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, !found, do { \
if (!(strcasecmp(iterator->name, (namestr)))) { \
found = iterator; \
found->next[0] = NULL; \
ASTOBJ_CONTAINER_WRLOCK(container); \
if (prev) \
prev->next[0] = next; \
else \
(container)->head = next; \
ASTOBJ_CONTAINER_UNLOCK(container); \
} \
prev = iterator; \
} while (0)); \
found; \
})
/*! \brief Find and remove an object in a container.
*
* \param container A pointer to the container to search.
* \param data The data to search for.
* \param field The field/member of the container's objects to search.
* \param hashfunc The hash function to use, currently not implemented.
* \param hashoffset The hash offset to use, currently not implemented.
* \param comparefunc The function used to compare the field and data values.
*
* This macro iterates through a container passing the specified field and data
* elements to the specified comparefunc. The function should return 0 when a match is found.
* If a match is found it is removed from the list.
*
* \note This macro does not destroy any objects, it simply unlinks
* them. No destructors are called.
*
* \return The container's reference to the removed object or NULL if no match
* was found.
*/
#define ASTOBJ_CONTAINER_FIND_UNLINK_FULL(container,data,field,hashfunc,hashoffset,comparefunc) \
({ \
typeof((container)->head) found = NULL; \
typeof((container)->head) prev = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, !found, do { \
ASTOBJ_RDLOCK(iterator); \
if (!(comparefunc(iterator->field, (data)))) { \
found = iterator; \
found->next[0] = NULL; \
ASTOBJ_CONTAINER_WRLOCK(container); \
if (prev) \
prev->next[0] = next; \
else \
(container)->head = next; \
ASTOBJ_CONTAINER_UNLOCK(container); \
} \
ASTOBJ_UNLOCK(iterator); \
prev = iterator; \
} while (0)); \
found; \
})
/*! \brief Add an object to the end of a container.
*
* \param container A pointer to the container to operate on.
* \param newobj A pointer to the object to be added.
*
* This macro adds an object to the end of a container.
*/
#define ASTOBJ_CONTAINER_LINK_END(container,newobj) \
do { \
typeof((container)->head) iterator; \
typeof((container)->head) next; \
typeof((container)->head) prev; \
ASTOBJ_CONTAINER_RDLOCK(container); \
prev = NULL; \
next = (container)->head; \
while((iterator = next)) { \
next = iterator->next[0]; \
prev = iterator; \
} \
if(prev) { \
ASTOBJ_CONTAINER_WRLOCK((container)); \
prev->next[0] = ASTOBJ_REF(newobj); \
(newobj)->next[0] = NULL; \
ASTOBJ_CONTAINER_UNLOCK((container)); \
} else { \
ASTOBJ_CONTAINER_LINK_START((container),(newobj)); \
} \
ASTOBJ_CONTAINER_UNLOCK((container)); \
} while(0)
/*! \brief Add an object to the front of a container.
*
* \param container A pointer to the container to operate on.
* \param newobj A pointer to the object to be added.
*
* This macro adds an object to the start of a container.
*/
#define ASTOBJ_CONTAINER_LINK_START(container,newobj) \
do { \
ASTOBJ_CONTAINER_WRLOCK(container); \
(newobj)->next[0] = (container)->head; \
(container)->head = ASTOBJ_REF(newobj); \
ASTOBJ_CONTAINER_UNLOCK(container); \
} while(0)
/*! \brief Remove an object from the front of a container.
*
* \param container A pointer to the container to operate on.
*
* This macro removes the first object in a container.
*
* \note This macro does not destroy any objects, it simply unlinks
* them from the list. No destructors are called.
*
* \return The container's reference to the removed object or NULL if no
* matching object was found.
*/
#define ASTOBJ_CONTAINER_UNLINK_START(container) \
({ \
typeof((container)->head) found = NULL; \
ASTOBJ_CONTAINER_WRLOCK(container); \
if((container)->head) { \
found = (container)->head; \
(container)->head = (container)->head->next[0]; \
found->next[0] = NULL; \
} \
ASTOBJ_CONTAINER_UNLOCK(container); \
found; \
})
/*! \brief Prune marked objects from a container.
*
* \param container A pointer to the container to prune.
* \param destructor A destructor function to call on each marked object.
*
* This macro iterates through the specfied container and prunes any marked
* objects executing the specfied destructor if necessary.
*/
#define ASTOBJ_CONTAINER_PRUNE_MARKED(container,destructor) \
do { \
typeof((container)->head) prev = NULL; \
ASTOBJ_CONTAINER_TRAVERSE(container, 1, do { \
ASTOBJ_RDLOCK(iterator); \
if (iterator->objflags & ASTOBJ_FLAG_MARKED) { \
ASTOBJ_CONTAINER_WRLOCK(container); \
if (prev) \
prev->next[0] = next; \
else \
(container)->head = next; \
ASTOBJ_CONTAINER_UNLOCK(container); \
ASTOBJ_UNLOCK(iterator); \
ASTOBJ_UNREF(iterator,destructor); \
continue; \
} \
ASTOBJ_UNLOCK(iterator); \
prev = iterator; \
} while (0)); \
} while(0)
/*! \brief Add an object to a container.
*
* \param container A pointer to the container to operate on.
* \param newobj A pointer to the object to be added.
* \param data Currently unused.
* \param field Currently unused.
* \param hashfunc Currently unused.
* \param hashoffset Currently unused.
* \param comparefunc Currently unused.
*
* Currently this function adds an object to the head of the list. One day it
* will support adding objects atthe position specified using the various
* options this macro offers.
*/
#define ASTOBJ_CONTAINER_LINK_FULL(container,newobj,data,field,hashfunc,hashoffset,comparefunc) \
do { \
ASTOBJ_CONTAINER_WRLOCK(container); \
(newobj)->next[0] = (container)->head; \
(container)->head = ASTOBJ_REF(newobj); \
ASTOBJ_CONTAINER_UNLOCK(container); \
} while(0)
#endif /* List model */
/* Common to hash and linked list models */
/*! \brief Create a container for ASTOBJs (without locking support).
*
* \param type The type of objects the container will hold.
*
* This macro is used to create a container for ASTOBJs without locking
* support.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_nolock_container {
* ASTOBJ_CONTAINER_COMPONENTS_NOLOCK(struct sample_struct);
* };
* \endcode
*/
#define ASTOBJ_CONTAINER_COMPONENTS_NOLOCK(type) \
ASTOBJ_CONTAINER_COMPONENTS_NOLOCK_FULL(type,1,ASTOBJ_DEFAULT_BUCKETS)
/*! \brief Create a container for ASTOBJs (with locking support).
*
* \param type The type of objects the container will hold.
*
* This macro is used to create a container for ASTOBJs with locking support.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_container {
* ASTOBJ_CONTAINER_COMPONENTS(struct sample_struct);
* };
* \endcode
*/
#define ASTOBJ_CONTAINER_COMPONENTS(type) \
ast_mutex_t _lock; \
ASTOBJ_CONTAINER_COMPONENTS_NOLOCK(type)
/*! \brief Initialize a container.
*
* \param container A pointer to the container to initialize.
*
* This macro initializes a container. It should only be used on containers
* that support locking.
*
* <b>Sample Usage:</b>
* \code
* struct sample_struct_container {
* ASTOBJ_CONTAINER_COMPONENTS(struct sample_struct);
* } container;
*
* int func()
* {
* ASTOBJ_CONTAINER_INIT(&container);
* }
* \endcode
*/
#define ASTOBJ_CONTAINER_INIT(container) \
ASTOBJ_CONTAINER_INIT_FULL(container,1,ASTOBJ_DEFAULT_BUCKETS)
/*! \brief Destroy a container.
*
* \param container A pointer to the container to destory.
*
* This macro frees up resources used by a container. It does not operate on
* the objects in the container. To unlink the objects from the container use
* #ASTOBJ_CONTAINER_DESTROYALL().
*
* \note This macro should only be used on containers with locking support.
*/
#define ASTOBJ_CONTAINER_DESTROY(container) \
ASTOBJ_CONTAINER_DESTROY_FULL(container,1,ASTOBJ_DEFAULT_BUCKETS)
/*! \brief Add an object to a container.
*
* \param container A pointer to the container to operate on.
* \param newobj A pointer to the object to be added.
*
* Currently this macro adds an object to the head of a container. One day it
* should add an object in alphabetical order.
*/
#define ASTOBJ_CONTAINER_LINK(container,newobj) \
ASTOBJ_CONTAINER_LINK_FULL(container,newobj,(newobj)->name,name,ASTOBJ_DEFAULT_HASH,0,strcasecmp)
/*! \brief Mark all the objects in a container.
* \param container A pointer to the container to operate on.
*/
#define ASTOBJ_CONTAINER_MARKALL(container) \
ASTOBJ_CONTAINER_TRAVERSE(container, 1, ASTOBJ_MARK(iterator))
/*! \brief Unmark all the objects in a container.
* \param container A pointer to the container to operate on.
*/
#define ASTOBJ_CONTAINER_UNMARKALL(container) \
ASTOBJ_CONTAINER_TRAVERSE(container, 1, ASTOBJ_UNMARK(iterator))
/*! \brief Dump information about an object into a string.
*
* \param s A pointer to the string buffer to use.
* \param slen The length of s.
* \param obj A pointer to the object to dump.
*
* This macro dumps a text representation of the name, objectflags, and
* refcount fields of an object to the specfied string buffer.
*/
#define ASTOBJ_DUMP(s,slen,obj) \
snprintf((s),(slen),"name: %s\nobjflags: %d\nrefcount: %d\n\n", (obj)->name, (obj)->objflags, (obj)->refcount);
/*! \brief Dump information about all the objects in a container to a file descriptor.
*
* \param fd The file descriptor to write to.
* \param s A string buffer, same as #ASTOBJ_DUMP().
* \param slen The length of s, same as #ASTOBJ_DUMP().
* \param container A pointer to the container to dump.
*
* This macro dumps a text representation of the name, objectflags, and
* refcount fields of all the objects in a container to the specified file
* descriptor.
*/
#define ASTOBJ_CONTAINER_DUMP(fd,s,slen,container) \
ASTOBJ_CONTAINER_TRAVERSE(container, 1, do { ASTOBJ_DUMP(s,slen,iterator); ast_cli(fd, "%s", s); } while(0))
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif /* _ASTERISK_ASTOBJ_H */
|
primuslabs/iaxproxy
|
include/iaxproxy/astobj.h
|
C
|
gpl-2.0
| 25,923
|
package game;
import java.util.Scanner;
import deck.Card;
import deck.Deck;
import player.Hand;
/**
* Game represents a full game of blackjack, with 1 dealer and 1 player, playing
* in consecutive turns until the player calls to stop.
*
* Regular blackjack rules apply;
*
* @author Odin
*
*/
public class Game {
private Deck deck;
private Hand player;
private Hand dealer;
private int playerWins;
private int playerLoses;
private boolean stop;
private Scanner scanner;
public Game(Deck deck, Hand player, Hand dealer) {
this.deck = deck;
this.player = player;
this.dealer = dealer;
this.playerWins = 0;
this.playerLoses = 0;
this.stop = false;
this.scanner = new Scanner(System.in);
}
public void start() {
System.out.println("BLACKJACK");
while (!stop) {
System.out.println("Dealing the first two cards:");
Card first = dealer.getCard();
Card second = dealer.getCard();
System.out.println("Dealer's first card is: " + first.toString());
first = player.getCard();
second = player.getCard();
System.out.println("Your first two cards are: " + first.toString() + " and " + second.toString() + ".");
System.out.println("Your current hand value is: " + player.getHandValue());
int playerValue = playerTurn();
int dealerValue = dealerTurn();
System.out.println("=================");
if (dealerValue > 21 || ((dealerValue < playerValue) && dealerValue < 21)) {
System.out.println("Player wins!");
playerWins++;
} else if (playerValue > 21 || ((playerValue < dealerValue) && playerValue < 21)) {
System.out.println("Dealer wins!");
playerLoses++;
} else if (playerValue == dealerValue) {
System.out.println("Push!");
}
System.out.println("Player wins:" + playerWins);
System.out.println("Player loses:" + playerLoses);
System.out.println("Want to play again? (Y/N)");
if (scanner.next().equals("N")) {
stop = true;
scanner.close();
}
prepareForNextTurn();
}
}
private int playerTurn() {
boolean end = false;
System.out.println("Player's turn");
while (!end) {
System.out.println("What do you want to do now?");
System.out.println("1-Hit");
System.out.println("2-Stand");
int operation = scanner.nextInt();
switch (operation) {
case 1:
Card card = player.getCard();
System.out.println("You pull a:" + card.toString());
System.out.println("Your current hand value is: " + player.getHandValue());
if (player.getHandValue() > 21) {
System.out.println("You are bust!");
end = true;
}
break;
case 2:
end = true;
}
}
return player.getHandValue();
}
/**
* Play a turn of the dealer, that must keep drawing cards until the value
* of his hand is 17 or above
*
* @return
*/
private int dealerTurn() {
System.out.println("Dealer's turn");
while (dealer.getHandValue() < 17) {
Card card = dealer.getCard();
System.out.println("Dealer draws a: " + card.toString());
System.out.println("Dealer's hand value is: " + dealer.getHandValue());
}
return dealer.getHandValue();
}
/**
* Clears all the hands and shuffles the deck for the next turnF
*/
private void prepareForNextTurn() {
player.clear();
dealer.clear();
deck.shuffleDeck();
}
}
|
ManuelPalomo/Blackjack
|
src/game/Game.java
|
Java
|
gpl-2.0
| 3,291
|
//
// jawt_md.h
//
// Copyright (c) 2002-2008 Apple Inc. All rights reserved.
//
#ifndef _JAVASOFT_JAWT_MD_H_
#define _JAVASOFT_JAWT_MD_H_
#include <jawt.h>
#include <AppKit/NSView.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct JAWT_MacOSXDrawingSurfaceInfo
{
NSView *cocoaViewRef; // the view is guaranteed to be valid only for the duration of Component.paint method
}
JAWT_MacOSXDrawingSurfaceInfo;
#ifdef __cplusplus
}
#endif
#endif /* !_JAVASOFT_JAWT_MD_H_ */
|
sschiesser/ASK_server
|
MacOSX10.6/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Headers/jawt_md.h
|
C
|
gpl-2.0
| 486
|
#ifndef FILTERCONTROLLER_H
#define FILTERCONTROLLER_H
#include <QObject>
#include <QRunnable>
#include <QMutex>
#include <QWaitCondition>
#include "../Operacao/filter.h"
#include "../../ImagemController/imagem.h"
#include <opencv2/core/core.hpp>
#include <opencv/cv.h>
#include <opencv2/gpu/gpumat.hpp>
using namespace cv;
class FilterController : public QObject,public QRunnable
{
Q_OBJECT
public:
explicit FilterController(QObject *parent = 0);
~FilterController();
void addProcessa(Imagem frame);
void stopThread();
void run();
signals:
void onTerminouSalEPimenta(Imagem frame);
public slots:
private:
QList<Imagem> listaProcessa;
Filter *filter;
QWaitCondition sincronizedThread;
bool finishedThread;
void processImage();
void executeFilter();
};
#endif // FILTERCONTROLLER_H
|
lillo42/Intel
|
AeroPlano/AeroPlano/TrataImage/Controller/filtercontroller.h
|
C
|
gpl-2.0
| 842
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 IT-SUDPARIS
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Providence SALUMU M. <Providence.Salumu_Munga@it-sudparis.eu>
*/
#include "mih-information-service-query-type-list.h"
namespace ns3 {
namespace mih {
InformationServiceQueryTypeList::InformationServiceQueryTypeList (uint64_t queryTypes) :
m_bitmap (queryTypes)
{}
InformationServiceQueryTypeList::InformationServiceQueryTypeList (InformationServiceQueryTypeList const &o) :
m_bitmap (o.m_bitmap)
{}
TLV_TYPE_HELPER_IMPLEM (InformationServiceQueryTypeList, TLV_MIIS_QUERY_TYPE_LIST)
InformationServiceQueryTypeList::~InformationServiceQueryTypeList (void)
{}
uint64_t
InformationServiceQueryTypeList::GetInformationServiceQueryTypes (void)
{
return m_bitmap;
}
void
InformationServiceQueryTypeList::SetInformationServiceQueryTypes (uint64_t queryTypes)
{
m_bitmap = queryTypes;
}
uint32_t
InformationServiceQueryTypeList::GetTlvSerializedSize (void) const
{
return TlvMih::GetSerializedSizeU64 ();
}
void
InformationServiceQueryTypeList::Print (std::ostream &os) const
{
os <<
"MIIS queries = 0x" << std::hex << (uint64_t)m_bitmap
<< std::endl
;
}
void
InformationServiceQueryTypeList::TlvSerialize (Buffer &buffer) const
{
TlvMih::SerializeU64 (buffer, m_bitmap, TLV_MIIS_QUERY_TYPE_LIST);
}
uint32_t
InformationServiceQueryTypeList::TlvDeserialize (Buffer &buffer)
{
return TlvMih::DeserializeU64 (buffer, m_bitmap, TLV_MIIS_QUERY_TYPE_LIST);
}
} // namespace mih
} // namespace ns3
|
srene/ns-3-mptcp
|
src/mih/model/mih-information-service-query-type-list.cc
|
C++
|
gpl-2.0
| 2,386
|
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace WiktionaryNET
{
/// <summary>
/// Holds the header for the section containg the word definition for a particular language.
/// A single word can be understood both as a verb AND a noun, for example.
/// The ==Verb== header will contain the word definition on wiktionary, for example.
/// </summary>
public static class WordDefinitionHeader
{
// Avoid reloading the same file again and again.
static Dictionary<string, IEnumerable<string>> list = new Dictionary<string,IEnumerable<string>>();
/// <summary>
/// Returns the headers for sections (in wiktionary)
/// containing the word definition for the selected language.
/// </summary>
/// <param name="language">"en" for English or "de" for German, for example</param>
/// <returns></returns>
public static IEnumerable<string> Get(string language)
{
// Language already present.
if (list.ContainsKey(language))
return list[language];
// Don't know what headers to search for
if (!File.Exists(DefinitionsPath(language)))
return new List<string>();
// Search in files.
var definitionParts = File.ReadAllLines(DefinitionsPath(language)).ToList();
list.Add(language, definitionParts);
return definitionParts;
}
/// <summary>
/// Get the file path holding the word definition headers for a specific language
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
static string DefinitionsPath(string language)
{
#if DEBUG
Console.WriteLine("Debug Version");
return "../../../WiktionaryNET/word_definition_headers/" + language + ".txt";
#else
// Return the path to NuGet installed packages.
var packageName = typeof(WordDefinitionHeader).Assembly.GetName().Name.ToString();
var packageLocation = Directory.GetDirectories("../../../packages/", packageName + "*")[0];
return packageLocation + "/content/word_definition_headers/" + language + ".txt";
#endif
}
}
}
|
mihaiolteanu/WiktionaryNET
|
WiktionaryNET/WordDefinitionHeader.cs
|
C#
|
gpl-2.0
| 2,315
|
cmd_drivers/hid/hid.o := /space/android/system/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi-ld -EL -r -o drivers/hid/hid.o drivers/hid/hid-debug.o drivers/hid/hid-core.o drivers/hid/hid-input.o
|
asopov/linux-tpt-2.6.39
|
drivers/hid/.hid.o.cmd
|
Batchfile
|
gpl-2.0
| 210
|
/*
* linux/include/linux/nfsd/xdr3.h
*
* XDR types for NFSv3 in nfsd.
*
* Copyright (C) 1996-1998, Olaf Kirch <okir@monad.swb.de>
*/
#ifndef _LINUX_NFSD_XDR3_H
#define _LINUX_NFSD_XDR3_H
#include <linux/nfsd/xdr.h>
#include <linux/posix_acl.h>
struct nfsd3_sattrargs {
struct svc_fh fh;
struct iattr attrs;
int check_guard;
time_t guardtime;
};
struct nfsd3_diropargs {
struct svc_fh fh;
char * name;
int len;
};
struct nfsd3_accessargs {
struct svc_fh fh;
unsigned int access;
};
struct nfsd3_readargs {
struct svc_fh fh;
__u64 offset;
__u32 count;
};
struct nfsd3_writeargs {
svc_fh fh;
__u64 offset;
__u32 count;
int stable;
__u8 * data;
__u32 len;
};
struct nfsd3_createargs {
struct svc_fh fh;
char * name;
int len;
int createmode;
struct iattr attrs;
__u32 * verf;
};
struct nfsd3_mknodargs {
struct svc_fh fh;
char * name;
int len;
__u32 ftype;
__u32 major, minor;
struct iattr attrs;
};
struct nfsd3_renameargs {
struct svc_fh ffh;
char * fname;
int flen;
struct svc_fh tfh;
char * tname;
int tlen;
};
struct nfsd3_linkargs {
struct svc_fh ffh;
struct svc_fh tfh;
char * tname;
int tlen;
};
struct nfsd3_symlinkargs {
struct svc_fh ffh;
char * fname;
int flen;
char * tname;
int tlen;
struct iattr attrs;
};
struct nfsd3_readdirargs {
struct svc_fh fh;
__u64 cookie;
__u32 dircount;
__u32 count;
__u32 * verf;
};
struct nfsd3_commitargs {
struct svc_fh fh;
__u64 offset;
__u32 count;
};
struct nfsd3_getaclargs {
struct svc_fh fh;
int mask;
};
struct nfsd3_setaclargs {
struct svc_fh fh;
int mask;
struct posix_acl *acl_access;
struct posix_acl *acl_default;
};
struct nfsd3_attrstat {
__u32 status;
struct svc_fh fh;
};
/* LOOKUP, CREATE, MKDIR, SYMLINK, MKNOD */
struct nfsd3_diropres {
__u32 status;
struct svc_fh dirfh;
struct svc_fh fh;
};
struct nfsd3_accessres {
__u32 status;
struct svc_fh fh;
__u32 access;
};
struct nfsd3_readlinkres {
__u32 status;
struct svc_fh fh;
__u32 len;
};
struct nfsd3_readres {
__u32 status;
struct svc_fh fh;
unsigned long count;
int eof;
};
struct nfsd3_writeres {
__u32 status;
struct svc_fh fh;
unsigned long count;
int committed;
};
struct nfsd3_renameres {
__u32 status;
struct svc_fh ffh;
struct svc_fh tfh;
};
struct nfsd3_linkres {
__u32 status;
struct svc_fh tfh;
struct svc_fh fh;
};
struct nfsd3_readdirres {
__u32 status;
struct svc_fh fh;
int count;
__u32 verf[2];
};
struct nfsd3_fsstatres {
__u32 status;
struct statfs stats;
__u32 invarsec;
};
struct nfsd3_fsinfores {
__u32 status;
__u32 f_rtmax;
__u32 f_rtpref;
__u32 f_rtmult;
__u32 f_wtmax;
__u32 f_wtpref;
__u32 f_wtmult;
__u32 f_dtpref;
__u64 f_maxfilesize;
__u32 f_properties;
};
struct nfsd3_pathconfres {
__u32 status;
__u32 p_link_max;
__u32 p_name_max;
__u32 p_no_trunc;
__u32 p_chown_restricted;
__u32 p_case_insensitive;
__u32 p_case_preserving;
};
struct nfsd3_commitres {
__u32 status;
struct svc_fh fh;
};
struct nfsd3_getaclres {
__u32 status;
struct svc_fh fh;
int mask;
struct posix_acl *acl_access;
struct posix_acl *acl_default;
};
/* dummy type for release */
struct nfsd3_fhandle_pair {
__u32 dummy;
struct svc_fh fh1;
struct svc_fh fh2;
};
/*
* Storage requirements for XDR arguments and results.
*/
union nfsd3_xdrstore {
struct nfsd3_sattrargs sattrargs;
struct nfsd3_diropargs diropargs;
struct nfsd3_readargs readargs;
struct nfsd3_writeargs writeargs;
struct nfsd3_createargs createargs;
struct nfsd3_renameargs renameargs;
struct nfsd3_linkargs linkargs;
struct nfsd3_symlinkargs symlinkargs;
struct nfsd3_readdirargs readdirargs;
struct nfsd3_diropres diropres;
struct nfsd3_accessres accessres;
struct nfsd3_readlinkres readlinkres;
struct nfsd3_readres readres;
struct nfsd3_writeres writeres;
struct nfsd3_renameres renameres;
struct nfsd3_linkres linkres;
struct nfsd3_readdirres readdirres;
struct nfsd3_fsstatres fsstatres;
struct nfsd3_fsinfores fsinfores;
struct nfsd3_pathconfres pathconfres;
struct nfsd3_commitres commitres;
struct nfsd3_getaclres getaclres;
};
#define NFS3_SVC_XDRSIZE sizeof(union nfsd3_xdrstore)
int nfs3svc_decode_fhandle(struct svc_rqst *, u32 *, struct svc_fh *);
int nfs3svc_decode_sattrargs(struct svc_rqst *, u32 *,
struct nfsd3_sattrargs *);
int nfs3svc_decode_diropargs(struct svc_rqst *, u32 *,
struct nfsd3_diropargs *);
int nfs3svc_decode_accessargs(struct svc_rqst *, u32 *,
struct nfsd3_accessargs *);
int nfs3svc_decode_readargs(struct svc_rqst *, u32 *,
struct nfsd3_readargs *);
int nfs3svc_decode_writeargs(struct svc_rqst *, u32 *,
struct nfsd3_writeargs *);
int nfs3svc_decode_createargs(struct svc_rqst *, u32 *,
struct nfsd3_createargs *);
int nfs3svc_decode_mkdirargs(struct svc_rqst *, u32 *,
struct nfsd3_createargs *);
int nfs3svc_decode_mknodargs(struct svc_rqst *, u32 *,
struct nfsd3_mknodargs *);
int nfs3svc_decode_renameargs(struct svc_rqst *, u32 *,
struct nfsd3_renameargs *);
int nfs3svc_decode_linkargs(struct svc_rqst *, u32 *,
struct nfsd3_linkargs *);
int nfs3svc_decode_symlinkargs(struct svc_rqst *, u32 *,
struct nfsd3_symlinkargs *);
int nfs3svc_decode_readdirargs(struct svc_rqst *, u32 *,
struct nfsd3_readdirargs *);
int nfs3svc_decode_readdirplusargs(struct svc_rqst *, u32 *,
struct nfsd3_readdirargs *);
int nfs3svc_decode_commitargs(struct svc_rqst *, u32 *,
struct nfsd3_commitargs *);
int nfs3svc_decode_getaclargs(struct svc_rqst *, u32 *,
struct nfsd3_getaclargs *);
int nfs3svc_decode_setaclargs(struct svc_rqst *, u32 *,
struct nfsd3_setaclargs *);
int nfs3svc_encode_voidres(struct svc_rqst *, u32 *, void *);
int nfs3svc_encode_attrstat(struct svc_rqst *, u32 *,
struct nfsd3_attrstat *);
int nfs3svc_encode_wccstat(struct svc_rqst *, u32 *,
struct nfsd3_attrstat *);
int nfs3svc_encode_diropres(struct svc_rqst *, u32 *,
struct nfsd3_diropres *);
int nfs3svc_encode_accessres(struct svc_rqst *, u32 *,
struct nfsd3_accessres *);
int nfs3svc_encode_readlinkres(struct svc_rqst *, u32 *,
struct nfsd3_readlinkres *);
int nfs3svc_encode_readres(struct svc_rqst *, u32 *, struct nfsd3_readres *);
int nfs3svc_encode_writeres(struct svc_rqst *, u32 *, struct nfsd3_writeres *);
int nfs3svc_encode_createres(struct svc_rqst *, u32 *,
struct nfsd3_diropres *);
int nfs3svc_encode_renameres(struct svc_rqst *, u32 *,
struct nfsd3_renameres *);
int nfs3svc_encode_linkres(struct svc_rqst *, u32 *,
struct nfsd3_linkres *);
int nfs3svc_encode_readdirres(struct svc_rqst *, u32 *,
struct nfsd3_readdirres *);
int nfs3svc_encode_fsstatres(struct svc_rqst *, u32 *,
struct nfsd3_fsstatres *);
int nfs3svc_encode_fsinfores(struct svc_rqst *, u32 *,
struct nfsd3_fsinfores *);
int nfs3svc_encode_pathconfres(struct svc_rqst *, u32 *,
struct nfsd3_pathconfres *);
int nfs3svc_encode_commitres(struct svc_rqst *, u32 *,
struct nfsd3_commitres *);
int nfs3svc_encode_getaclres(struct svc_rqst *, u32 *,
struct nfsd3_getaclres *);
int nfs3svc_encode_setaclres(struct svc_rqst *, u32 *,
struct nfsd3_attrstat *);
int nfs3svc_release_fhandle(struct svc_rqst *, u32 *,
struct nfsd3_attrstat *);
int nfs3svc_release_fhandle2(struct svc_rqst *, u32 *,
struct nfsd3_fhandle_pair *);
int nfs3svc_release_getacl(struct svc_rqst *rqstp, u32 *p,
struct nfsd3_getaclres *resp);
int nfs3svc_encode_entry(struct readdir_cd *, const char *name,
int namlen, loff_t offset, ino_t ino,
unsigned int);
int nfs3svc_encode_entry_plus(struct readdir_cd *, const char *name,
int namlen, loff_t offset, ino_t ino,
unsigned int);
#endif /* _LINUX_NFSD_XDR3_H */
|
dduval/kernel-rhel3
|
include/linux/nfsd/xdr3.h
|
C
|
gpl-2.0
| 7,903
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrueChessGame.GameEngine
{
/*
Review VV:
для читабельності такі записи краще робити у багато рядків
*/
public enum DefaultPieces : sbyte
{
BlackKing = -6,
BlackQueen = -5,
BlackRook = -4,
BlackBishop = -3,
BlackkNight = -2,
BlackPawn = -1,
Empty = 0,
WhitePawn = 1,
WhitekNight = 2,
WhiteBishop = 3,
WhiteRook = 4,
WhiteQueen = 5,
WhiteKing = 6
};
/*
Review VV:
1) не зрозуміле призначення цього класу
на мою думку, його функції повинні бути нестатичними функціями сутності "Game"
2) всі функції класів-фігур повинні бути нестатичними
*/
public class Piece
{
public static ChessBoard PerformMove(ChessBoard board, Square oldposition, Square newposition)
{
sbyte piecetype = board[oldposition.file, oldposition.rank];
/*
Review VV:
для чого необхідно робити копію ігрового поля?
*/
ChessBoard tempboard = board.ShallowCopy();
tempboard[oldposition.file, oldposition.rank] = 0;
tempboard[newposition.file, newposition.rank] = piecetype;
// tempboard.DebugConsoleSimpleDraw(); Console.WriteLine();
return tempboard;
}
// Code Review: Назваргументів методу повинні починатися з малої літери.
public static List<ChessBoard> AddNewPosition(List<ChessBoard> ResultedPositionsList, ChessBoard position, bool IsWhite)
{
if (IsWhite && WhiteKing.IsSafe(position))
{
ResultedPositionsList.Add(position);
}
else if (!IsWhite && BlackKing.IsSafe(position))
{
ResultedPositionsList.Add(position);
}
return ResultedPositionsList;
}
public static Square[] GetSimplekNightMoveDestinations(Square current)
{
Square[] moves = new Square[8];
moves[0] = new Square((char)(current.file + 1), current.rank + 2);
moves[1] = new Square((char)(current.file + 2), current.rank + 1);
moves[2] = new Square((char)(current.file + 2), current.rank - 1);
moves[3] = new Square((char)(current.file + 1), current.rank - 2);
moves[4] = new Square((char)(current.file - 1), current.rank + 2);
moves[5] = new Square((char)(current.file - 2), current.rank + 1);
moves[6] = new Square((char)(current.file - 2), current.rank - 1);
moves[7] = new Square((char)(current.file - 1), current.rank - 2);
return moves;
}
public static Square[] GetSimpleKingMoveDestinations(Square current)
{
char file = current.file; int rank = current.rank;
Square[] moves = new Square[8];
moves[0] = new Square(file, rank + 1);
moves[1] = new Square(file, rank - 1);
moves[2] = new Square((char)(file + 1), rank + 1);
moves[3] = new Square((char)(file + 1), rank);
moves[4] = new Square((char)(file + 1), rank - 1);
moves[5] = new Square((char)(file - 1), rank + 1);
moves[6] = new Square((char)(file - 1), rank);
moves[7] = new Square((char)(file - 1), rank - 1);
return moves;
}
public static Square GetPosition(ChessBoard board, sbyte piece)
{
Square result = new Square();
for (char tfile = 'a'; tfile <= 'h'; tfile++)
{
for (int trank = 1; trank <= 8; trank++)
{
if (board[tfile, trank] == piece)
{
result.file = tfile;
result.rank = (sbyte)trank;
break;
}
}
}
return result;
}
}
#region White Pieces
/*
Review VV:
не бачу сенсу в такому наслідуванні, оскільки всі функції класу Piece статичні
*/
public class WhitePiece : Piece
{
public static void GetDiagonalDestinations(ChessBoard board, ref List<Square> moves, Square current, int multfile, int multrank)
{
char file = current.file;
int rank = current.rank;
for (int i = 1; i < 8; i++)
{
Square tempsquare=new Square((char)(file+multfile*i), rank+multrank*i);
if (!tempsquare.IsOK())
{
break;
}
else if (board[tempsquare] > 0)
{
break;
}
else if (board[tempsquare] < 0)
{
moves.Add(tempsquare);
break;
}
else
{
moves.Add(tempsquare);
}
}
}
public static void GetVerticalUpDestinations(ChessBoard board, List<Square> moves, Square current)
{
for (int i = current.rank + 1; i <= 8; i++)
{
if (board[current.file, i] > 0)
{
break;
}
else
{
if (board[current.file, i] < 0)
{
moves.Add(new Square(current.file, i));
break;
}
else
{
moves.Add(new Square(current.file, i));
}
}
}
}
public static void GetVerticalDownDestinations(ChessBoard board, List<Square> moves, Square current)
{
for (int i = current.rank - 1; i >= 1; i--)
{
if (board[current.file, i] > 0)
{
break;
}
else
{
if (board[current.file, i] < 0)
{
moves.Add(new Square(current.file, i));
break;
}
else
{
moves.Add(new Square(current.file, i));
}
}
}
}
public static void GetHorizontalLeftDestinations(ChessBoard board, List<Square> moves, Square current)
{
for (char tchar = (char)(current.file - 1); tchar >= 'a'; tchar--)
{
if (board[tchar, current.rank] > 0)
{
break;
}
else
{
if (board[tchar, current.rank] < 0)
{
moves.Add(new Square(tchar, current.rank));
break;
}
else
{
moves.Add(new Square(tchar, current.rank));
}
}
}
}
public static void GetHorizontalRightDestinations(ChessBoard board, List<Square> moves, Square current)
{
for (char tchar = (char)(current.file + 1); tchar <= 'h'; tchar++)
{
if (board[tchar, current.rank] > 0)
{
break;
}
else
{
if (board[tchar, current.rank] < 0)
{
moves.Add(new Square(tchar, current.rank));
break;
}
else
{
moves.Add(new Square(tchar, current.rank));
}
}
}
}
public static List<Square> GetPossibleBlackAttackersToSquare(ChessBoard board, Square goalsquare)
{
List<Square> result = new List<Square>();
char file = goalsquare.file; int rank = goalsquare.rank;
//check for Pawn
if (file >= 'a' && file <= 'g' && rank<=7 && board[(char)(file + 1), rank + 1] == (sbyte)DefaultPieces.BlackPawn)
{
result.Add(new Square((char)(file + 1), rank + 1));
}
if (file >= 'b' && file <= 'h' && rank <=7 && board[(char)(file - 1), rank + 1] == (sbyte)DefaultPieces.BlackPawn)
{
result.Add(new Square((char)(file - 1), rank + 1));
}
Square[] moves_array = Piece.GetSimplekNightMoveDestinations(goalsquare);
foreach (Square move in moves_array)
{
if (move.IsOK() && board[move] == (sbyte)DefaultPieces.BlackkNight)
{
result.Add(move);
}
}
GetVerticalUpBlackAttackers(board, result, file, rank);
GetVerticalDownBlackAttackers(board, result, file, rank);
GetHorizontalRightBlackAttacker(board, result, file, rank);
GetHorizontalLeftBlackAttackers(board, result, file, rank);
GetDiagonalBlackAttackers(board, result, goalsquare, 1, 1);
GetDiagonalBlackAttackers(board, result, goalsquare, 1, -1);
GetDiagonalBlackAttackers(board, result, goalsquare, -1, 1);
GetDiagonalBlackAttackers(board, result, goalsquare, -1, -1);
Square[] moves = Piece.GetSimpleKingMoveDestinations(goalsquare);
foreach (Square move in moves)
{
if (move.IsOK() && board[move] == (sbyte)DefaultPieces.BlackKing)
{
result.Add(move); break;
}
}
return result;
}
private static bool CheckSquareForBlackRookOrQueen(ChessBoard board, Square CheckedSquare, List<Square> result)
{
// Code Review: Назва локальної змінної повинна починатися з малої літери.
bool ToBreakNow = false;
if (board[CheckedSquare]>0)
{
ToBreakNow = true;
}
else if (board[CheckedSquare]<0 && board[CheckedSquare]!=(sbyte)DefaultPieces.BlackRook && board[CheckedSquare]!=(sbyte)DefaultPieces.BlackQueen)
{
ToBreakNow = true;
}
else if (board[CheckedSquare]==(sbyte)DefaultPieces.BlackRook || board[CheckedSquare]==(sbyte)DefaultPieces.BlackQueen)
{
result.Add(CheckedSquare);
ToBreakNow=true;
}
return ToBreakNow;
}
private static void GetHorizontalLeftBlackAttackers(ChessBoard board, List<Square> result, char file, int rank)
{
for (char tchar = (char)(file - 1); tchar >= 'a'; tchar--)
{
// Code Review: Назва локальної змінної повинна починатися з малої літери.
bool EndOfCycle = CheckSquareForBlackRookOrQueen(board, new Square(tchar, rank), result);
if (EndOfCycle)
{
break;
}
}
}
private static void GetHorizontalRightBlackAttacker(ChessBoard board, List<Square> result, char file, int rank)
{
for (char tchar = (char)(file + 1); tchar <= 'h'; tchar++)
{
// Code Review: Назва локальної змінної повинна починатися з малої літери.
bool EndOfCycle = CheckSquareForBlackRookOrQueen(board, new Square(tchar, rank), result);
if (EndOfCycle)
{
break;
}
}
}
private static void GetVerticalDownBlackAttackers(ChessBoard board, List<Square> result, char file, int rank)
{
for (int i = rank - 1; i >= 1; i--)
{
// Code Review: Назва локальної змінної повинна починатися з малої літери.
bool EndOfCycle = CheckSquareForBlackRookOrQueen(board, new Square(file, i), result);
if (EndOfCycle)
{
break;
}
}
}
private static void GetVerticalUpBlackAttackers(ChessBoard board, List<Square> result, char file, int rank)
{
for (int i = rank + 1; i <= 8; i++)
{
// Code Review: Назва локальної змінної повинна починатися з малої літери.
bool EndOfCycle = CheckSquareForBlackRookOrQueen(board, new Square(file, i), result);
if (EndOfCycle)
{
break;
}
}
}
private static void GetDiagonalBlackAttackers(ChessBoard board, List<Square> result, Square current, int multfile, int multrank)
{
char file = current.file;
int rank = current.rank;
for (int i = 1; i < 8; i++)
{
Square tempsquare = new Square((char)(file + multfile * i), rank + multrank * i);
if (!tempsquare.IsOK())
{
break;
}
else if (board[tempsquare] > 0)
{
break;
}
else if (board[tempsquare] < 0 && board[tempsquare]!=(sbyte)DefaultPieces.BlackBishop && board[tempsquare] != (sbyte)DefaultPieces.BlackQueen)
{
break;
}
else if (board[tempsquare]== (sbyte)DefaultPieces.BlackBishop || board[tempsquare] == (sbyte)DefaultPieces.BlackQueen)
{
result.Add(new Square((char)(file + multfile * i), rank + multrank * i));
break;
}
}
}
}
public class WhitePawn
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard = board.ShallowCopy();
Square currentposition=new Square(file, rank);
if (DefaultInfo.BlackEnPassantEndangered)
{
GetEnPassantPositions(ref result, board, currentposition);
}
if (rank == 2 && board[file, rank + 1] == 0 && board[file, rank + 2] == 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square(file, rank + 2));
result = Piece.AddNewPosition(result, tempboard, true);
}
if (board[file, rank + 1] == 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square(file, rank + 1));
result = Piece.AddNewPosition(result, tempboard, true);
}
if (file >= 'a' && file <= 'g' && board[(char)(file + 1), rank + 1] < 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square((char)(file + 1), rank + 1));
result = Piece.AddNewPosition(result, tempboard, true);
}
if (file >= 'b' && file <= 'h' && board[(char)(file - 1), rank + 1] < 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square((char)(file - 1), rank + 1));
result = Piece.AddNewPosition(result, tempboard, true);
}
if (rank <= 6 || result.Count == 0)
{
return result;
}
else
{
return GetPawnPromotionPositions(file, result, tempboard);
}
}
private static void GetEnPassantPositions(ref List<ChessBoard> result, ChessBoard board, Square currentposition)
{
ChessBoard tempboard = board.ShallowCopy();
bool CheckEnPassant = DefaultInfo.EnPassantPossibleCapture.rank == currentposition.rank + 1 && (DefaultInfo.EnPassantPossibleCapture.file == (char)(currentposition.file + 1) || DefaultInfo.EnPassantPossibleCapture.file == (char)(currentposition.file - 1));
if (CheckEnPassant)
{
tempboard = Piece.PerformMove(board, currentposition, DefaultInfo.EnPassantPossibleCapture);
tempboard[DefaultInfo.EnPassantPossibleCapture.file, DefaultInfo.EnPassantPossibleCapture.rank - 1] = 0;
result = Piece.AddNewPosition(result, tempboard, true);
}
}
private static List<ChessBoard> GetPawnPromotionPositions(char file, List<ChessBoard> result, ChessBoard tempboard)
{
List<ChessBoard> resultpromotion = new List<ChessBoard>();
foreach (ChessBoard promotiontempboard in result)
{
tempboard = promotiontempboard.ShallowCopy();
char promotionfile = file;
for (char tempfile = 'a'; tempfile <= 'h'; tempfile++)
{
if (tempboard[tempfile, 8] == (sbyte)DefaultPieces.WhitePawn)
{
promotionfile = tempfile;
break;
}
}
//now Promotions!
tempboard[promotionfile, 8] = (sbyte)DefaultPieces.WhitekNight;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 8] = (sbyte)DefaultPieces.WhiteBishop;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 8] = (sbyte)DefaultPieces.WhiteRook;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 8] = (sbyte)DefaultPieces.WhiteQueen;
resultpromotion.Add(tempboard.ShallowCopy());
}
return resultpromotion;
}
}
public class WhitekNight
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
Square current = new Square(file, rank);
Square[] moves = Piece.GetSimplekNightMoveDestinations(current);
ChessBoard tempboard;
foreach (Square move in moves)
{
if (move.IsOK())
{
if (board[move] <= 0)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, true);
}
}
}
return result;
}
}
public class WhiteBishop
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard;
List<Square> moves = new List<Square>();
Square current = new Square(file, rank);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, 1, 1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, 1, -1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, -1, 1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, -1, -1);
foreach (Square move in moves)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, true);
}
return result;
}
}
public class WhiteRook
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard;
List<Square> moves = new List<Square>();
Square current=new Square(file, rank);
WhitePiece.GetVerticalUpDestinations(board, moves, current);
WhitePiece.GetVerticalDownDestinations(board, moves, current);
WhitePiece.GetHorizontalLeftDestinations(board, moves, current);
WhitePiece.GetHorizontalRightDestinations(board, moves, current);
Console.WriteLine(moves.Count);
foreach (Square move in moves)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, true);
}
Console.WriteLine(result.Count);
return result;
}
}
public class WhiteQueen
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard;
List<Square> moves = new List<Square>();
Square current = new Square(file, rank);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, 1, 1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, 1, -1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, -1, 1);
WhitePiece.GetDiagonalDestinations(board, ref moves, current, -1, -1);
WhitePiece.GetVerticalUpDestinations(board, moves, current);
WhitePiece.GetVerticalDownDestinations(board, moves, current);
WhitePiece.GetHorizontalLeftDestinations(board, moves, current);
WhitePiece.GetHorizontalRightDestinations(board, moves, current);
foreach (Square move in moves)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, true);
}
return result;
}
}
public class WhiteKing
{
public static bool IsSafe(ChessBoard board)
{
Square current = Piece.GetPosition(board, (sbyte)DefaultPieces.WhiteKing);
char file = current.file; int rank = current.rank;
List<Square> result = WhitePiece.GetPossibleBlackAttackersToSquare(board, current);
return (result.Count == 0);
}
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard;
Square current=new Square(file, rank);
Square[] moves = Piece.GetSimpleKingMoveDestinations(current);
foreach (Square move in moves)
{
if (move.IsOK() && board[move]<=0)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, true);
}
}
GetQueenCastlingPosition(board, file, rank, result, current);
GetKingCastlingPosition(board, file, rank, result, current);
return result;
}
private static void GetKingCastlingPosition(ChessBoard board, char file, sbyte rank, List<ChessBoard> result, Square current)
{
ChessBoard tempboard;
if (WhiteKing.IsSafe(board) && DefaultInfo.WhiteKingIsUnMoved && DefaultInfo.WhiteHsideRookIsUnMoved)
{
char rookfile = 'h';
for (char tfile = file; tfile < 'h'; tfile++)
{
if (board[tfile, rank] == (sbyte)DefaultPieces.WhiteRook)
{
rookfile = tfile;
}
}
tempboard = board.ShallowCopy();
bool CastlingAvailable = true;
for (char tfile = file; tfile <= 'g'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = rookfile; tfile >= 'f'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = rookfile; tfile <= 'f'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = file; tfile <= 'g'; tfile++)
{
ChessBoard temp2board = board.ShallowCopy();
temp2board[file, rank] = 0;
temp2board[tfile, rank] = (sbyte)DefaultPieces.WhiteKing;
if (!WhiteKing.IsSafe(temp2board))
{
CastlingAvailable = false;
break;
}
}
if (CastlingAvailable)
{
tempboard = Piece.PerformMove(board, current, new Square('g', rank));
tempboard = Piece.PerformMove(tempboard, new Square(rookfile, rank), new Square('f', rank));
result.Add(tempboard);
}
}
}
private static void GetQueenCastlingPosition(ChessBoard board, char file, sbyte rank, List<ChessBoard> result, Square current)
{
ChessBoard tempboard;
if (WhiteKing.IsSafe(board) && DefaultInfo.WhiteKingIsUnMoved && DefaultInfo.WhiteAsideRookIsUnMoved)
{
char rookfile = 'a';
for (char tfile = file; tfile > 'a'; tfile--)
{
if (board[tfile, rank] == (sbyte)DefaultPieces.WhiteRook)
{
rookfile = tfile;
}
}
tempboard = board.ShallowCopy();
bool CastlingAvailable = true;
for (char tfile = file; tfile >= 'c'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = rookfile; tfile <= 'd'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = rookfile; tfile >= 'd'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.WhiteKing && board[tfile, rank] != (sbyte)DefaultPieces.WhiteRook)
{
CastlingAvailable = false;
break;
}
}
for (char tfile = file; tfile >= 'c'; tfile--)
{
ChessBoard temp2board = Piece.PerformMove(board, current, new Square(tfile, rank));
if (!WhiteKing.IsSafe(temp2board))
{
CastlingAvailable = false;
break;
}
}
if (file == 'b')
{
ChessBoard temp2board = Piece.PerformMove(board, current, new Square('c', rank));
if (!WhiteKing.IsSafe(temp2board))
{
CastlingAvailable = false;
}
}
if (CastlingAvailable)
{
tempboard = Piece.PerformMove(board, current, new Square('c', rank));
tempboard = Piece.PerformMove(tempboard, new Square(rookfile, rank), new Square('d', rank));
result.Add(tempboard);
}
}
}
}
#endregion
#region Black Pieces
/*
Review VV:
не бачу сенсу в такому наслідуванні, оскільки всі функції класу Piece статичні
*/
public class BlackPiece:Piece
{
public static List<ChessBoard> GetReversedPossibleWhitePositions(ChessBoard board, char file, sbyte rank, sbyte piece)
{
ChessBoard tempboard = board.ShallowCopy();
tempboard.ReverseSides();
Square tempsquare = new Square(file, rank);
tempsquare.Reverse();
char piecechar = FIDEnotation.GetLetter(piece);
FIDEnotation.GetPiecePositionsType function = FIDEnotation.GetWhitePiecePositionsType(piecechar);
List<ChessBoard> result = function(tempboard, tempsquare.file, tempsquare.rank);
foreach (ChessBoard temp in result)
{
temp.ReverseSides();
}
return result;
}
public static List<Square> GetPossibleWhiteAttackersToSquare(ChessBoard board, Square goalsquare)
{
ChessBoard tempboard = board.ShallowCopy();
tempboard.DebugConsoleSimpleDraw();
Console.WriteLine();
tempboard.ReverseSides();
//tempboard.DebugConsoleSimpleDraw();
Square tempsquare=new Square(goalsquare.file, goalsquare.rank);
tempsquare.Reverse();
var result = WhitePiece.GetPossibleBlackAttackersToSquare(tempboard, tempsquare);
for (int i = 0; i < result.Count; i++ )
{
Square temp = result[i];
temp.Reverse();
result[i] = temp;
}
return result;
}
}
public class BlackPawn
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard = board.ShallowCopy();
Square currentposition = new Square(file, rank);
if (DefaultInfo.WhiteEnPassantEndangered)
{
GetEnPassantPositions(ref result, board, currentposition);
}
if (rank == 7 && board[file, rank - 1] == 0 && board[file, rank - 2] == 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square(file, rank - 2));
result = Piece.AddNewPosition(result, tempboard, false);
}
if (board[file, rank - 1] == 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square(file, rank - 1));
result = Piece.AddNewPosition(result, tempboard, false);
}
if (file >= 'a' && file <= 'g' && board[(char)(file + 1), rank - 1] > 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square((char)(file + 1), rank - 1));
result = Piece.AddNewPosition(result, tempboard, false);
}
if (file >= 'b' && file <= 'h' && board[(char)(file - 1), rank - 1] > 0)
{
tempboard = Piece.PerformMove(board, currentposition, new Square((char)(file - 1), rank - 1));
result = Piece.AddNewPosition(result, tempboard, false);
}
if (rank > 2 || result.Count == 0)
{
return result;
}
else
{
return GetPawnPromotionPositions(file, result, tempboard);
}
}
private static void GetEnPassantPositions(ref List<ChessBoard> result, ChessBoard board, Square currentposition)
{
ChessBoard tempboard = board.ShallowCopy();
bool CheckEnPassant = DefaultInfo.EnPassantPossibleCapture.rank == currentposition.rank - 1 && (DefaultInfo.EnPassantPossibleCapture.file == (char)(currentposition.file + 1) || DefaultInfo.EnPassantPossibleCapture.file == (char)(currentposition.file - 1));
if (CheckEnPassant)
{
tempboard = Piece.PerformMove(board, currentposition, DefaultInfo.EnPassantPossibleCapture);
tempboard[DefaultInfo.EnPassantPossibleCapture.file, DefaultInfo.EnPassantPossibleCapture.rank + 1] = 0;
result = Piece.AddNewPosition(result, tempboard, false);
}
}
private static List<ChessBoard> GetPawnPromotionPositions(char file, List<ChessBoard> result, ChessBoard tempboard)
{
List<ChessBoard> resultpromotion = new List<ChessBoard>();
foreach (ChessBoard promotiontempboard in result)
{
tempboard = promotiontempboard.ShallowCopy();
char promotionfile = file;
for (char tempfile = 'a'; tempfile <= 'h'; tempfile++)
{
if (tempboard[tempfile, 1] == (sbyte)DefaultPieces.BlackPawn)
{
promotionfile = tempfile;
break;
}
}
//now Promotions!
tempboard[promotionfile, 1] = (sbyte)DefaultPieces.BlackkNight;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 1] = (sbyte)DefaultPieces.BlackBishop;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 1] = (sbyte)DefaultPieces.BlackRook;
resultpromotion.Add(tempboard.ShallowCopy());
tempboard[promotionfile, 1] = (sbyte)DefaultPieces.BlackQueen;
resultpromotion.Add(tempboard.ShallowCopy());
}
return resultpromotion;
}
}
public class BlackkNight
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
sbyte piece =(sbyte) DefaultPieces.WhitekNight;
return BlackPiece.GetReversedPossibleWhitePositions(board, file, rank, piece);
}
}
public class BlackBishop
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
sbyte piece = (sbyte)DefaultPieces.WhiteBishop;
return BlackPiece.GetReversedPossibleWhitePositions(board, file, rank, piece);
}
}
public class BlackRook
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
sbyte piece = (sbyte)DefaultPieces.WhiteRook;
return BlackPiece.GetReversedPossibleWhitePositions(board, file, rank, piece);
}
}
public class BlackQueen
{
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
sbyte piece = (sbyte)DefaultPieces.WhiteQueen;
return BlackPiece.GetReversedPossibleWhitePositions(board, file, rank, piece);
}
}
public class BlackKing
{
public static bool IsSafe(ChessBoard board)
{
ChessBoard tempboard = board.ShallowCopy();
tempboard.ReverseSides();
return WhiteKing.IsSafe(tempboard);
}
public static List<ChessBoard> GetPossiblePositions(ChessBoard board, char file, sbyte rank)
{
List<ChessBoard> result = new List<ChessBoard>();
ChessBoard tempboard;
Square current = new Square(file, rank);
Square[] moves = Piece.GetSimpleKingMoveDestinations(current);
foreach (Square move in moves)
{
if (move.IsOK() && board[move] >= 0)
{
tempboard = Piece.PerformMove(board, current, move);
result = Piece.AddNewPosition(result, tempboard, false);
}
}
GetQueenCastlingPosition(board, file, rank, result, current);
GetKingCastlingPosition(board, file, rank, result, current);
return result;
}
private static void GetKingCastlingPosition(ChessBoard board, char file, sbyte rank, List<ChessBoard> result, Square current)
{
ChessBoard tempboard;
if (BlackKing.IsSafe(board) && DefaultInfo.BlackKingIsUnMoved && DefaultInfo.BlackHsideRookIsUnMoved)
{
char rookfile = 'h';
for (char tfile = file; tfile < 'h'; tfile++)
{
if (board[tfile, rank] == (sbyte)DefaultPieces.BlackRook)
{
rookfile = tfile;
}
}
tempboard = board.ShallowCopy();
bool CastlingAvailable = true;
for (char tfile = file; tfile <= 'g'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = rookfile; tfile >= 'f'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = rookfile; tfile <= 'f'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = file; tfile <= 'g'; tfile++)
{
ChessBoard temp2board = board.ShallowCopy();
temp2board[file, rank] = 0;
temp2board[tfile, rank] = (sbyte)DefaultPieces.BlackKing;
if (!BlackKing.IsSafe(temp2board))
{
CastlingAvailable = false;
return;
}
}
if (CastlingAvailable)
{
tempboard = Piece.PerformMove(board, current, new Square('g', rank));
tempboard = Piece.PerformMove(tempboard, new Square(rookfile, rank), new Square('f', rank));
result.Add(tempboard);
}
}
}
private static void GetQueenCastlingPosition(ChessBoard board, char file, sbyte rank, List<ChessBoard> result, Square current)
{
ChessBoard tempboard;
if (BlackKing.IsSafe(board) && DefaultInfo.BlackKingIsUnMoved && DefaultInfo.BlackAsideRookIsUnMoved)
{
char rookfile = 'a';
for (char tfile = file; tfile > 'a'; tfile--)
{
if (board[tfile, rank] == (sbyte)DefaultPieces.BlackRook)
{
rookfile = tfile;
}
}
tempboard = board.ShallowCopy();
bool CastlingAvailable = true;
for (char tfile = file; tfile >= 'c'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = rookfile; tfile <= 'd'; tfile++)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = rookfile; tfile >= 'd'; tfile--)
{
if (board[tfile, rank] != 0 && board[tfile, rank] != (sbyte)DefaultPieces.BlackKing && board[tfile, rank] != (sbyte)DefaultPieces.BlackRook)
{
CastlingAvailable = false;
return;
}
}
for (char tfile = file; tfile >= 'c'; tfile--)
{
ChessBoard temp2board = Piece.PerformMove(board, current, new Square(tfile, rank));
if (!BlackKing.IsSafe(temp2board))
{
CastlingAvailable = false;
return;
}
}
if (file == 'b')
{
ChessBoard temp2board = Piece.PerformMove(board, current, new Square('c', rank));
if (!BlackKing.IsSafe(temp2board))
{
CastlingAvailable = false;
}
}
if (CastlingAvailable)
{
tempboard = Piece.PerformMove(board, current, new Square('c', rank));
tempboard = Piece.PerformMove(tempboard, new Square(rookfile, rank), new Square('d', rank));
result.Add(tempboard);
}
}
}
}
}
#endregion
|
DanielYurystovskyi/truechessgame
|
TrueChessGame.GameEngine/ChessPiece.cs
|
C#
|
gpl-2.0
| 44,470
|
// Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id$
//
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 2006-2012 by The Odamex Team.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// DESCRIPTION:
// Rendering of moving objects, sprites.
//
//-----------------------------------------------------------------------------
#ifndef __R_THINGS__
#define __R_THINGS__
// [RH] Particle details
struct particle_s {
fixed_t x,y,z;
fixed_t velx,vely,velz;
fixed_t accx,accy,accz;
byte ttl;
byte trans;
byte size;
byte fade;
int color;
WORD next;
WORD nextinsubsector;
};
typedef struct particle_s particle_t;
extern int NumParticles;
extern int ActiveParticles;
extern int InactiveParticles;
extern particle_t *Particles;
extern TArray<WORD> ParticlesInSubsec;
const WORD NO_PARTICLE = 0xffff;
#ifdef _MSC_VER
__inline particle_t *NewParticle (void)
{
particle_t *result = NULL;
if (InactiveParticles != NO_PARTICLE) {
result = Particles + InactiveParticles;
InactiveParticles = result->next;
result->next = ActiveParticles;
ActiveParticles = result - Particles;
}
return result;
}
#else
particle_t *NewParticle (void);
#endif
void R_InitParticles (void);
void R_ClearParticles (void);
void R_DrawParticleP (vissprite_t *, int, int);
void R_DrawParticleD (vissprite_t *, int, int);
void R_ProjectParticle (particle_t *, const sector_t* sector, int fakeside);
void R_FindParticleSubsectors();
extern int MaxVisSprites;
extern vissprite_t *vissprites;
extern vissprite_t* vissprite_p;
extern vissprite_t vsprsortedhead;
// Constant arrays used for psprite clipping
// and initializing clipping.
extern int *negonearray;
extern int *screenheightarray;
// vars for R_DrawMaskedColumn
extern int* mfloorclip;
extern int* mceilingclip;
extern fixed_t spryscale;
extern fixed_t sprtopscreen;
extern fixed_t pspritexscale;
extern fixed_t pspriteyscale;
extern fixed_t pspritexiscale;
void R_DrawMaskedColumn(tallpost_t* post);
void R_CacheSprite (spritedef_t *sprite);
void R_SortVisSprites (void);
void R_AddSprites (sector_t *sec, int lightlevel, int fakeside);
void R_AddPSprites (void);
void R_DrawSprites (void);
void R_InitSprites (const char** namelist);
void R_ClearSprites (void);
void R_DrawMasked (void);
#endif
|
JamesDunne/odamex
|
common/r_things.h
|
C
|
gpl-2.0
| 2,822
|
/*
This file is part of EqualizerAPO, a system-wide equalizer.
Copyright (C) 2015 Jonas Thedering
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.
*/
#pragma once
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <fftw3.h>
#include "DeviceAPOInfo.h"
class AnalysisThread : public QThread
{
Q_OBJECT
public:
AnalysisThread();
~AnalysisThread();
void setParameters(std::shared_ptr<AbstractAPOInfo> device, int channelMask, int channelIndex, QString configPath, int frameCount);
void beginGetResult();
void endGetResult();
fftwf_complex* getFreqData() const;
int getFreqDataLength() const;
int getFreqDataSampleRate() const;
double getPeakGain() const;
int getLatency() const;
double getInitializationTime() const;
double getProcessingTime() const;
unsigned getProcessedFrames() const;
signals:
void analysisFinished();
protected:
void run() override;
private:
QMutex mutex;
QWaitCondition condition;
bool quit = false;
// input
std::shared_ptr<AbstractAPOInfo> device;
int channelMask;
int channelIndex;
QString configPath;
int frameCount = 0;
// output
fftwf_complex* resultFreqData = NULL;
int freqDataLength = 0;
int freqDataSampleRate;
double peakGain;
int latency;
double initializationTime;
double processingTime;
int processedFrames;
// internal (not protected by mutex)
int lastFrameCount = -1;
int lastChannelCount = -1;
float* buf = NULL;
float* buf2 = NULL;
float* timeData = NULL;
fftwf_complex* freqData = NULL;
fftwf_plan planForward = NULL;
};
|
mirror/equalizerapo
|
Editor/AnalysisThread.h
|
C
|
gpl-2.0
| 2,303
|
/* Balcora is a gateway AE which reside at kernel level. Balcora intercepts
* every packets going through an determined network interface and redirect it
* on RNS network. It performs then the inverse operation with PDUs arriving
* from RNS to this AE instance.
*
* Actually Balcora operates on network layer of the ISO/OSI stack.
*
* This is the first application for Service Application Entities. This type of
* AE reside at kernel level, and you can resume their life with "you had one
* job!".
*
* Yes... the name of the project has been pick in honor of Homeworld 2.
*
* Copyright (c) 2016 Kewin Rausch <kewin.rausch@create-net.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.
*
* Contributors:
*
*/
#include <asm/uaccess.h>
#include <linux/byteorder/generic.h>
#include <linux/etherdevice.h>
#include <linux/fs.h>
#include <linux/if_arp.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <net/checksum.h>
#include <net/ip.h>
#include <rnsatom.h>
#include <rnslist.h>
#include <rnslock.h>
#include <debug.h>
#include <ae.h>
#include <core.h>
#include <ipcm.h>
#include <name.h>
#include <mem.h>
#include <sys.h>
/* Size of IP addresses taken into account. */
#define BAL_ETH_ADDR_SIZE 6
/* Size of IP addresses taken into account. */
#define BAL_IPADDR_SIZE 4
#include "balcom.h"
/* Rule to provide translation between ETH to RNS names. */
struct bal_eth_rule {
/* Member of a list. */
rnslist listh;
/* Destination ip address. */
char h_addr[BAL_ETH_ADDR_SIZE];
/* Name of the AE which manage such ip. */
struct name dest;
};
/* Rule to provide translation between IP to RNS names. */
struct bal_ip_rule {
/* Member of a list. */
rnslist listh;
/* Destination ip address. */
char ip_addr[BAL_IPADDR_SIZE];
/* Name of the AE which manage such ip. */
struct name dest;
};
/* This procedure contains all information of a single gate. */
struct bal_gate {
/* The module maintains a list of spawned gates. */
rnslist listh;
/* Id of the ipcm to use. */
ipcmid ipcm;
/* Id of the application entity. */
aeid ae;
/* Qos used by this AE. */
qosid qos;
/* Set of rule to apply to the passing PDUs. */
rnslist ip_rules;
/* Set of rule to apply to the passing PDUs. */
rnslist eth_rules;
/* Device requested name. Use to renew (eventually) the ndev pointer. */
char devname[IFNAMSIZ];
/* Network device we want to tunnel. */
struct net_device * ndev;
#ifdef RNS_SYSFS
/* Sysfs entry for this gate. */
struct kobject kobj;
#endif
/* Locking elements at gate granularity. */
rnspinlock lock;
};
/* Balcora network device. */
struct bal_netdev {
/* The actual network device. */
struct net_device * net;
/* Set on/off the possibility to capture the packet. */
int enabled;
};
/******************************************************************************
* Module global variables. *
******************************************************************************/
/* THE misc device of this module. */
static struct miscdevice bal_miscdev = {0};
/* Name of the misc device which will be found under /dev. */
static char * bal_dev_name = "balcora";
/* The list of gates actually active at kernel level. */
RNSLIST_DEFINE(bal_gates_list);
/* Lock to access balcora sensitive informations. */
RNSPIN_LOCK_DEFINE(bal_lock);
/******************************************************************************
* Prototypes area. *
******************************************************************************/
/* Send data. This action is done always on RNS network system. */
int bal_send_data(struct bal_gate * gate, struct sk_buff * skb);
/* Receive data from RNS network and move it into a device. */
int bal_recv_data(struct bal_gate * gate, struct pdu * pdu);
/* Releases a gate in it's correct way. */
int bal_release_gate(struct bal_gate * gate);
/******************************************************************************
* Balcora gates. *
******************************************************************************/
void bal_add_gate(struct bal_gate * gate) {
rnslist_add(&gate->listh, &bal_gates_list);
}
void bal_del_gate(struct bal_gate * gate) {
rnslist_del(&gate->listh);
}
void bal_lock_gates(void) {
rnspin_lock(&bal_lock);
}
void bal_lock_read_gates(void) {
rnsrcu_lock();
}
void bal_unlock_gates(void) {
rnspin_unlock(&bal_lock);
}
void bal_unlock_read_gates(void) {
rnsrcu_unlock();
}
/******************************************************************************
* Skb stuff routines. *
******************************************************************************/
/* Allocate one or more sk_buffs depending on the packet size. */
struct sk_buff * bal_alloc_skb_with_frags(
unsigned long header_len,
unsigned long data_len,
int max_page_order,
int *errcode,
gfp_t gfp_mask) {
/* This is a copy, adapted copy for older kernel versions. */
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 17, 0)
int npages = 0;
unsigned long chunk = 0;
struct sk_buff * skb = 0;
struct page * page = 0;
gfp_t gfp_head;
int i = 0;
int order = 0;
order = max_page_order;
npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
*errcode = -EMSGSIZE;
/* Note this test could be relaxed, if we succeed to allocate
* high order pages...
*/
if (npages > MAX_SKB_FRAGS) {
return NULL;
}
gfp_head = gfp_mask;
/* __GFP_DIRECT_RECLAIM cannot be resolved in these kernel versions.
if (gfp_head & __GFP_DIRECT_RECLAIM) {
gfp_head |= __GFP_REPEAT;
}
*/
*errcode = -ENOBUFS;
skb = alloc_skb(header_len, gfp_head);
if (!skb) {
return NULL;
}
skb->truesize += npages << PAGE_SHIFT;
for (i = 0; npages > 0; i++) {
while (order) {
if (npages >= 1 << order) {
page = alloc_pages(
gfp_mask |
__GFP_COMP |
__GFP_NOWARN |
__GFP_NORETRY,
order);
if (page) {
goto fill_page;
}
/* Do not retry other high order allocations */
order = 1;
max_page_order = 0;
}
order--;
}
page = alloc_page(gfp_mask);
if (!page) {
goto failure;
}
fill_page:
chunk = min_t(unsigned long, data_len, PAGE_SIZE << order);
skb_fill_page_desc(skb, i, page, 0, chunk);
data_len -= chunk;
npages -= 1 << order;
}
return skb;
failure:
kfree_skb(skb);
return NULL;
#else
/* Call the available procedure from the kernel API. */
return alloc_skb_with_frags(
header_len, data_len, max_page_order, errcode, gfp_mask);
#endif
}
/* Allocates a new skb taking in account both linear and possible paged data. */
struct sk_buff * bal_alloc_skb(int len) {
struct sk_buff * ret = 0;
int err = 0;
int size = len; /* Length of the first skb, at the head position. */
int paged = 0; /* Length of successive, paged, data...*/
int pages = 0; /* Number of pages needed. */
/* Adjust the data to be compatible with skb stuff. */
if(size > PAGE_SIZE) {
pages = min_t(int, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
paged = pages << PAGE_SHIFT;
size = paged + (len & ~PAGE_MASK);
}
/* Allocate the first skb and it's eventual fragment chain. */
ret = bal_alloc_skb_with_frags(
size - paged, paged, 0, &err, GFP_KERNEL);
if(!ret) {
LOG_ERR("Could not allocate a new skb, error=%d", err);
return 0;
}
/* Adjust the pointers. */
/* skb_reserve(ret, pre); */
skb_put(ret, size - paged);
/* Assign the right values. */
ret->len = size;
ret->data_len = paged;
return ret;
}
/******************************************************************************
* Balcora network device. *
* *
* This code is inspired by: *
* - linux/drivers/net/tun.c *
* - linux/drivers/net/loopback.c *
******************************************************************************/
#define BAL_MIN_MTU 68
#define BAL_MAX_MTU 65535
int bal_dev_change_mtu(struct net_device * dev, int new_mtu) {
if (new_mtu < BAL_MIN_MTU ||
new_mtu + dev->hard_header_len > BAL_MAX_MTU) {
return -EINVAL;
}
dev->mtu = new_mtu;
return 0;
}
int bal_dev_init(struct net_device * dev) {
return 0;
}
int bal_dev_open(struct net_device *dev) {
netif_tx_start_all_queues(dev);
return 0;
}
int bal_dev_stop(struct net_device *dev) {
netif_tx_stop_all_queues(dev);
return 0;
}
void bal_dev_uninit(struct net_device *dev) {
}
netdev_tx_t bal_dev_xmit(struct sk_buff * skb, struct net_device * dev) {
struct bal_netdev * bd = netdev_priv(dev);
struct bal_gate * g = 0;
/* Block the usage of this device. */
/* netif_stop_queue(dev); */
/* Detach the skb from the Linux network context.
* We are stealing it.
*/
skb_orphan(skb);
nf_reset(skb);
/* Do not use this device! */
if(!bd->enabled) {
goto skip;
}
#if 0
LOG_INFO("Stealing %d bytes", skb->len);
#endif
bal_lock_read_gates();
/* Do it for every gate which hooked to the network device! */
rnslist_for_each_entry(g, &bal_gates_list, listh) {
if(dev == g->ndev) {
bal_send_data(g, skb);
/* NO BREAK here! */
}
}
bal_unlock_read_gates();
skip:
kfree_skb(skb);
/* Use the device again. */
/* netif_start_queue(dev); */
return NETDEV_TX_OK;
}
/* Network device operation for all the balcora netdevs. */
struct net_device_ops bal_netdev_ops = {
.ndo_change_mtu = bal_dev_change_mtu,
.ndo_init = bal_dev_init,
.ndo_open = bal_dev_open,
.ndo_set_mac_address = eth_mac_addr,
.ndo_start_xmit = bal_dev_xmit,
.ndo_stop = bal_dev_stop,
.ndo_uninit = bal_dev_uninit,
.ndo_validate_addr = eth_validate_addr,
};
void bal_dev_destructor(struct net_device * dev) {
struct bal_netdev * bd = netdev_priv(dev);
LOG_DBG("Finally releasing the net device %s memory.",
dev->name);
bd->enabled = 0;
/* Drop one reference to this module... once everything is dropped, then
* the module can be correctly dropped.
*/
module_put(THIS_MODULE);
free_netdev(dev);
}
void bal_dev_setup(struct net_device * dev) {
dev->netdev_ops = &bal_netdev_ops;
dev->hw_features =
NETIF_F_SG |
NETIF_F_FRAGLIST |
NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX;
dev->features = dev->hw_features;
dev->vlan_features = dev->features &
~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX);
/* Follow classic ethernet setup. */
ether_setup(dev);
eth_hw_addr_random(dev);
dev->destructor = bal_dev_destructor;
}
int bal_dev_nl_validate(struct nlattr * tb[], struct nlattr * data[]) {
/* Avoid neltlink messing with us. */
return -EINVAL;
}
const struct rtnl_link_ops bal_dev_nl_ops __read_mostly = {
.kind = "balcora",
.priv_size = 0,
.setup = bal_dev_setup,
.validate = bal_dev_nl_validate,
};
/* Creates a new network device with the given name. */
struct bal_netdev * bal_create_netdev(char * name) {
int err = 0;
struct bal_netdev * dev = 0;
struct net_device * net = 0;
if(!name) {
LOG_ERR("Wrong name for the device!");
return 0;
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 17, 0)
net = alloc_netdev(
sizeof(struct bal_netdev), name, bal_dev_setup);
#else
net = alloc_netdev(
sizeof(struct bal_netdev),
name,
NET_NAME_UNKNOWN,
bal_dev_setup);
#endif
if(!net) {
LOG_ERR("Netdev allocation failed");
mem_free(dev);
return 0;
}
dev = netdev_priv(net);
/*
* Some additional initialization before registering it.
*/
dev->net = net;
dev->enabled = 1;
dev->net->rtnl_link_ops = &bal_dev_nl_ops;
err = register_netdev(dev->net);
if(err) {
LOG_ERR("Failed to register the network device, "
"name=%s, error=%d",
name,
err);
free_netdev(dev->net);
mem_free(dev);
return 0;
}
/* Get a reference to this module, which is dropped once the network
* device is destroyed.
*/
__module_get(THIS_MODULE);
netif_carrier_on(dev->net);
if (netif_running(dev->net)) {
netif_tx_wake_all_queues(dev->net);
}
LOG_DBG("Balcora created a new network device, name=%s", name);
return dev;
}
int bal_release_netdev(struct net_device * net) {
struct bal_gate * g = 0;
struct bal_gate * h = 0;
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
if(g->ndev == net) {
bal_release_gate(g);
break;
}
}
LOG_DBG("Unregistering a balcora network device, name=%s",
net->name);
netif_carrier_off(net);
unregister_netdev(net);
return 0;
}
/* Resolve the device in a quick-to-use key for evaluations. */
int bal_resolve_netdev(struct bal_gate * gate) {
struct net_device * net = 0;
if(!gate || !gate->devname) {
LOG_WARNING("Wrong args, gate=0x%pK, name=0x%pK",
gate,
gate ? gate->devname : 0);
return -1;
}
net = dev_get_by_name(&init_net, gate->devname);
if(!net) {
if(!bal_create_netdev(gate->devname)) {
return -1;
}
net = dev_get_by_name(&init_net, gate->devname);
gate->ndev = net;
} else {
gate->ndev = net;
}
if(!gate->ndev) {
LOG_WARNING("Device %s not found!", gate->devname);
return -1;
}
return 0;
}
/******************************************************************************
* Balcora operations. *
******************************************************************************/
/* Data for an AE is ready! */
int bal_data_ready(struct ae * ae);
int bal_add_eth_rule(struct bal_gate * gate, char * addr, char * name) {
struct bal_eth_rule * er = 0;
rnspin_lock(&gate->lock);
/*
* Update rule:
*/
rnslist_for_each_entry(er, &gate->eth_rules, listh) {
if(name_cmp_raw(&er->dest, name, PDU_NAME_LEN) == 0) {
memcpy(er->h_addr, addr, BAL_ETH_ADDR_SIZE);
LOG_DBG("Eth rule updated, "
"%d%d%d%d --> "
"%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char)name[0],
(unsigned char)name[1],
(unsigned char)name[2],
(unsigned char)name[3],
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3],
(unsigned char)addr[4],
(unsigned char)addr[5]);
rnspin_unlock(&gate->lock);
return 0;
}
}
/*
* New rule:
*/
er = mem_alloc(sizeof(struct bal_eth_rule), MEM_TYPE_ATOMIC);
if(!er) {
LOG_ERR("Not enough memory");
rnspin_unlock(&gate->lock);
return -1;
}
INIT_LIST_HEAD(&er->listh);
memcpy(er->h_addr, addr, BAL_ETH_ADDR_SIZE);
if(name_init(&er->dest, name, AE_MAX_NAME)) {
LOG_ERR("Not enough memory");
mem_free(er);
rnspin_unlock(&gate->lock);
return -1;
}
list_add_rcu(&er->listh, &gate->eth_rules);
rnspin_unlock(&gate->lock);
LOG_DBG("%d.%d Added new ETH rule, "
"%d%d%d%d ---> %02x:%02x:%02x:%02x:%02x:%02x",
gate->ipcm,
gate->ae,
(unsigned char)name[0],
(unsigned char)name[1],
(unsigned char)name[2],
(unsigned char)name[3],
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3],
(unsigned char)addr[4],
(unsigned char)addr[5]);
return 0;
}
int bal_add_ip_rule(struct bal_gate * gate, char * addr, char * name) {
struct bal_ip_rule * ipr = 0;
rnspin_lock(&gate->lock);
/*
* Update rule:
*/
rnslist_for_each_entry(ipr, &gate->ip_rules, listh) {
if(name_cmp_raw(&ipr->dest, name, PDU_NAME_LEN) == 0) {
memcpy(ipr->ip_addr, addr, BAL_IPADDR_SIZE);
LOG_DBG("IP rule updated, "
"%d%d%d%d --> %d.%d.%d.%d",
(unsigned char)name[0],
(unsigned char)name[1],
(unsigned char)name[2],
(unsigned char)name[3],
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3]);
rnspin_unlock(&gate->lock);
return 0;
}
}
/*
* New rule:
*/
ipr = mem_alloc(sizeof(struct bal_ip_rule), MEM_TYPE_KERNEL);
if(!ipr) {
LOG_ERR("Not enough memory");
return -1;
}
INIT_LIST_HEAD(&ipr->listh);
memcpy(ipr->ip_addr, addr, 4);
if(name_init(&ipr->dest, name, AE_MAX_NAME)) {
LOG_ERR("Not enough memory");
mem_free(ipr);
return -1;
}
list_add_rcu(&ipr->listh, &gate->ip_rules);
rnspin_unlock(&gate->lock);
LOG_DBG("%d.%d Added new IP rule, %d%d%d%d --> %02x%02x%02x%02x",
gate->ipcm,
gate->ae,
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3],
(unsigned char)name[0],
(unsigned char)name[1],
(unsigned char)name[2],
(unsigned char)name[3]);
return 0;
}
int bal_create_gate(
char * iface,
ipcmid ipcm,
ipcpid ipcp,
qosid qos,
char * src, unsigned int srclen) {
struct bal_gate * g = mem_zac(sizeof(struct bal_gate), MEM_TYPE_KERNEL);
struct name n = {0};
struct ae * ae = 0;
struct qos * q = 0;
struct ipcm * im = 0;
char source[AE_MAX_NAME] = {0};
if(!g) {
LOG_ERR("No more memory!");
return -1;
}
if(srclen > AE_MAX_NAME) {
LOG_ERR("Name too long!");
return -1;
}
memcpy(source, src, srclen);
/*
* Initialize the gate structure with the necessary data.
*/
strncpy(g->devname, iface, IFNAMSIZ);
g->qos = qos;
g->ipcm = ipcm;
RNSLIST_INIT_HEAD(&g->listh);
RNSLIST_INIT_HEAD(&g->eth_rules);
RNSLIST_INIT_HEAD(&g->ip_rules);
rnspin_lock_init(&g->lock);
/*
* Naming...
*/
if(name_init(&n, source, AE_MAX_NAME)) {
goto err;
}
/*
* Network device resolution.
*/
/* First check if is possible to do operation on that interface. */
if(bal_resolve_netdev(g)) {
goto err;
}
/*
* RNS network resolution.
*/
/* Find the IPCM context. */
im = core_find_ipcm(ipcm);
if(!im) {
goto err;
}
/* Create our service AE. */
ae = ipcm_create_ae(im, &n);
if(!ae) {
goto err;
}
/* This is important... save it to send/recv messages. */
g->ae = ae->id;
/* We decided to use that QoS, so create the AE level profile. */
q = ae_create_qos(ae, qos);
if(!q) {
goto err;
}
/* Try to register to the ipcp. */
if(ipcm_register_ae(im, g->ae, ipcp) < 0) {
goto err;
}
/*
* Prepare now for data arrival.
*/
/* Perform operations when the data arrives. */
ae->priv = g;
ae->data_ready = bal_data_ready;
/*
* To resume: we have our entry in RNS, ready to be used, and we
* resolved the network interface. Now it's time to enable the filter;
* this is done by adding the gate to the scanned list.
*/
/* This will make the gate to appear in the hook computation. */
bal_lock_gates();
bal_add_gate(g);
bal_unlock_gates();
LOG_DBG("New gate on %s successfuly created, ipcm=%d, ae=%d",
g->devname, g->ipcm, g->ae);
name_release(&n);
return 0;
/* Nicely formatted common error procedures. */
err:
if(g) {
if(g->ndev) {
/* One cannot simply free the memory;
* references must be dropped.
*/
dev_put(g->ndev);
}
if(g->ae) {
ipcm_release_ae(im, g->ae);
}
mem_free(g);
}
if(n.data) {
name_release(&n);
}
LOG_ERR("Balcora %s gate creation failed!", iface);
return -1;
}
/* When the AE has available data, then take this action. */
int bal_data_ready(struct ae * ae) {
/* Recover the precious informations. */
struct bal_gate * g = (struct bal_gate *)ae->priv;
struct pdu * p = 0;
do {
/* Reset the pdu and try again to read it. */
p = 0;
ae_read(ae, g->qos, &p);
if(p) {
bal_recv_data(g, p);
}
} while(p);
return 0;
}
int bal_del_eth_rule(struct bal_gate * gate, char * addr) {
struct bal_eth_rule * etr = 0;
struct bal_eth_rule * tmp = 0;
LOG_DBG("%d.%d Removing ETH rule for %x.%x.%x.%x.%x.%x",
gate->ipcm,
gate->ae,
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3],
(unsigned char)addr[4],
(unsigned char)addr[5]);
rnspin_lock(&gate->lock);
rnslist_for_each_entry_safe(etr, tmp, &gate->ip_rules, listh) {
if(memcmp(etr->h_addr, addr, BAL_ETH_ADDR_SIZE) == 0) {
rnslist_del(&etr->listh);
name_release(&etr->dest);
mem_free(etr);
break;
}
}
rnspin_unlock(&gate->lock);
return 0;
}
int bal_del_ip_rule(struct bal_gate * gate, char * addr) {
struct bal_ip_rule * ipr = 0;
struct bal_ip_rule * tmp = 0;
LOG_DBG("%d.%d Removing IP rule for %d.%d.%d.%d",
gate->ipcm,
gate->ae,
(unsigned char)addr[0],
(unsigned char)addr[1],
(unsigned char)addr[2],
(unsigned char)addr[3]);
rnspin_lock(&gate->lock);
rnslist_for_each_entry_safe(ipr, tmp, &gate->ip_rules, listh) {
if(memcmp(ipr->ip_addr, addr, 4) == 0) {
rnslist_del(&ipr->listh);
name_release(&ipr->dest);
mem_free(ipr);
break;
}
}
rnspin_unlock(&gate->lock);
return 0;
}
int bal_release_gate(struct bal_gate * gate) {
struct bal_ip_rule * a = 0;
struct bal_ip_rule * b = 0;
struct bal_eth_rule * c = 0;
struct bal_eth_rule * d = 0;
struct ipcm * im = 0;
/* No more traffic from the network devices. */
bal_lock_gates();
bal_del_gate(gate);
bal_unlock_gates();
im = core_find_ipcm(gate->ipcm);
if(im) {
/* Release the AE from the RNS network. */
ipcm_release_ae(im, gate->ae);
}
LOG_DBG("Gate closed, net device=%s, ae=%d", gate->devname, gate->ae);
/* Drop the reference count to the device. We got it when looking for
* the device using it's name.
*/
if(gate->ndev) {
dev_put(gate->ndev);
}
/*
* Release all the introduced rules.
*/
rnspin_lock(&gate->lock);
rnslist_for_each_entry_safe(a, b, &gate->ip_rules, listh) {
rnslist_del(&a->listh);
name_release(&a->dest);
mem_free(a);
}
rnslist_for_each_entry_safe(c, d, &gate->eth_rules, listh) {
rnslist_del(&c->listh);
name_release(&c->dest);
mem_free(c);
}
rnspin_unlock(&gate->lock);
mem_free(gate);
return 0;
}
/* This is a little more complicated, because we need to setup correctly the
* socket buffer.
*/
int bal_recv_data(struct bal_gate * gate, struct pdu * pdu) {
int len = 0;
struct pci pci = {0};
struct sk_buff * skb = 0;
struct ethhdr * eth = 0;
struct arphdr * arh = 0;
char * buf = mem_zac(pdu_data_length(pdu), MEM_TYPE_KERNEL);
if(!buf) {
LOG_ERR("Not nough memory!");
return -1;
}
/* Get info from RNS layers. */
pdu_pci_rebase(&pci, pdu);
/* Now that we have only data, use it! */
len = pdu_data_length(pdu);
skb = bal_alloc_skb(len);
if(!skb) {
gate->ndev->stats.rx_dropped++;
pdu_release(pdu);
mem_free(pdu);
mem_free(buf);
return -1;
}
/* We are moving from fragmented to linear to fragmented world.
*
* Can this be done better? Probably we can directly steal and format
* correctly the skb buf fragments.
*/
pdu_copy_data_to(pdu, buf, pdu_data_length(pdu), 0);
/* Copy the data into the sk_buff structure. */
skb_store_bits(skb, 0, buf, len);
/*
* Setup some important fields of the skb.
*/
skb->dev = gate->ndev;
skb->protocol = eth_type_trans(skb, gate->ndev);
eth = eth_hdr(skb);
/*
if (!skb_transport_header_was_set(skb)){
skb_reset_transport_header(skb);
}
*/
/* An ARP? */
if(ntohs(skb->protocol) == ETH_P_ARP) {
skb_reset_network_header(skb);
arh = arp_hdr(skb);
bal_add_eth_rule(gate, eth->h_source, pci.src);
}
/*
skb_probe_transport_header(skb, 0);
*/
#if 0
LOG_INFO("<-- Receiving %d bytes", skb->len);
#endif
/* Receiving packet from non-interrupt context (see ipcp models). */
//if(netif_rx_ni(skb)) {
if(netif_receive_skb(skb)) {
gate->ndev->stats.rx_dropped++;
LOG_ERR("Error while enqueuing the packet!");
}
gate->ndev->stats.rx_packets++;
gate->ndev->stats.rx_bytes += len;
/* Nicely release unused resources. */
pdu_release(pdu);
mem_free(pdu);
mem_free(buf);
return 0;
}
int bal_send_data(struct bal_gate * gate, struct sk_buff * skb) {
struct ae * ae= 0;
struct ipcm * ipcm = core_find_ipcm(gate->ipcm);
struct pdu * pdu = 0;
struct bal_eth_rule * rulh = 0;
struct bal_ip_rule * rule = 0;
struct arphdr * arh = 0;
struct ethhdr * eth = 0;
struct iphdr * iph = 0;
char * buf = 0;
int mc = 0; /* Multicast? */
if(!ipcm) {
LOG_ERR("IPCM %d no longer exists!", gate->ipcm);
goto free_drop;
}
ae = ipcm_find_ae(ipcm, gate->ae);
if(!ae) {
LOG_ERR("AE %d no longer exists!", gate->ae);
goto free_drop;
}
/* This probably can be avoided because skb already have pages of
* memory.
*/
buf = mem_zac(skb->len, MEM_TYPE_KERNEL);
if(!buf) {
LOG_ERR("No more memory!");
return -1;
}
eth = eth_hdr(skb);
skb_copy_bits(skb, 0, buf, skb->len);
/* Broadcast the message to every known AE. */
if(eth->h_dest[0] == 0xff &&
eth->h_dest[1] == 0xff &&
eth->h_dest[2] == 0xff &&
eth->h_dest[3] == 0xff &&
eth->h_dest[4] == 0xff &&
eth->h_dest[5] == 0xff) {
mc = 1;
rnsrcu_lock();
rnslist_for_each_entry_rcu(rulh, &gate->eth_rules, listh) {
ae_write(ae, &rulh->dest, gate->qos, buf, skb->len);
}
rnsrcu_unlock();
rnsrcu_lock();
rnslist_for_each_entry_rcu(rule, &gate->ip_rules, listh) {
ae_write(ae, &rule->dest, gate->qos, buf, skb->len);
}
rnsrcu_unlock();
goto done;
}
/* In case of ARP? */
if(ntohs(eth->h_proto) == ETH_P_ARP) {
arh = arp_hdr(skb);
rnsrcu_lock();
rnslist_for_each_entry_rcu(rulh, &gate->eth_rules, listh) {
if(memcmp(
eth->h_dest,
rulh->h_addr,
BAL_ETH_ADDR_SIZE) == 0) {
ae_write(
ae,
&rulh->dest,
gate->qos,
buf,
skb->len);
break;
}
}
rnsrcu_unlock();
goto done;
}
/* In case of IP? */
if(ntohs(eth->h_proto) == ETH_P_IP) {
iph = ip_hdr(skb);
rnsrcu_lock();
rnslist_for_each_entry_rcu(rule, &gate->ip_rules, listh) {
if(memcmp(
rule->ip_addr,
&iph->daddr,
BAL_IPADDR_SIZE) == 0) {
if(ae_write(
ae,
&rule->dest,
gate->qos,
buf,
skb->len) < 0) {
rnsrcu_unlock();
goto dropit;
}
break;
}
}
rnsrcu_unlock();
goto done;
}
done:
gate->ndev->stats.tx_packets++;
gate->ndev->stats.tx_bytes += skb->len;
mem_free(buf);
return 0;
free_drop:
pdu_release(pdu);
mem_free(pdu);
dropit:
LOG_DBG("Dropping a PDU, 0x%pK", pdu);
mem_free(buf);
gate->ndev->stats.tx_dropped++;
return -1;
}
/******************************************************************************
* Miscdevice operations. *
******************************************************************************/
static long bal_unlocked_ioctl(
struct file *file, unsigned int cmd, unsigned long arg) {
long op = 0;
struct bal_cr cr;
struct bal_rel rel = {0};
struct bal_reld reld;
struct bal_ipr ipr = {0};
struct bal_gate * g = 0;
struct bal_gate * h = 0;
struct net_device * net = 0;
switch(cmd) {
case BAL_CTRL_CREATE_GATE:
op = copy_from_user(
&cr, (void *) arg, sizeof(struct bal_cr));
if(op) {
LOG_ERR("I/O error, error=%ld", op);
break;
}
/* Create the necessary stuff to handle the gate. */
if(bal_create_gate(
cr.devname,
cr.ipcm,
cr.ipcp,
cr.qos,
cr.src, cr.src_len)) {
return -1;
}
break;
case BAL_CTRL_RELEASE_GATE:
op = copy_from_user(
&rel, (void *) arg, sizeof(struct bal_rel));
if(op) {
LOG_ERR("I/O error, error=%ld", op);
break;
}
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
if(g->ae == rel.ae) {
bal_release_gate(g);
break;
}
}
break;
case BAL_CTRL_RELEASE_DEV:
op = copy_from_user(
&reld, (void *) arg, sizeof(struct bal_reld));
if(op) {
LOG_ERR("I/O error, error=%ld", op);
break;
}
synchronize_net();
net = dev_get_by_name(&init_net, reld.devname);
if(!net) {
LOG_WARNING("Desired network device does not exists, "
"name=%s",
reld.devname);
break;
}
/* Remove all those AE which are attached to such device. */
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
if(g->ndev == net) {
bal_release_gate(g);
}
}
/* Since we got a reference before, drop it now. */
dev_put(net);
bal_release_netdev(net);
break;
case BAL_CTRL_ADD_IP_RULE:
op = copy_from_user(
&ipr, (void *) arg, sizeof(struct bal_ip_rule));
if(op) {
LOG_ERR("I/O error, error=%ld", op);
break;
}
op = 0;
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
if(g->ae == ipr.ae) {
bal_add_ip_rule(g, ipr.addr, ipr.name);
op = 1;
break;
}
}
if(!op) {
return -1;
}
break;
case BAL_CTRL_DEL_IP_RULE:
op = copy_from_user(
&ipr, (void *) arg, sizeof(struct bal_ip_rule));
if(op) {
LOG_ERR("I/O error, error=%ld", op);
break;
}
op = 0;
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
if(g->ae == ipr.ae) {
bal_del_ip_rule(g, ipr.addr);
op = 1;
break;
}
}
if(!op) {
return -1;
}
break;
default:
LOG_ERR("Unknown I/O control to Balcora, command=%d", cmd);
break;
}
return 0;
}
/* File operations of rns gate. */
static const struct file_operations bal_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = bal_unlocked_ioctl,
};
/******************************************************************************
* Entry/exit points. *
******************************************************************************/
/* Module entry point. */
static void __exit bal_exit(void) {
struct bal_gate * g = 0;
struct bal_gate * h = 0;
/* Rollback misc registration. */
misc_deregister(&bal_miscdev);
rnslist_for_each_entry_safe(g, h, &bal_gates_list, listh) {
bal_release_gate(g);
}
LOG_INFO("Path to Sajuuk is now closed.");
}
/* Module exit point. */
static int __init bal_init(void) {
int status = 0;
/* Setup the misc device. */
bal_miscdev.minor= MISC_DYNAMIC_MINOR;
bal_miscdev.name = bal_dev_name;
bal_miscdev.fops = &bal_fops;
/* Register the misc device. */
status = misc_register(&bal_miscdev);
if(status < 0) {
LOG_ERR("Failed to load the device %s, error=%d",
bal_dev_name, status);
return -1;
}
LOG_DBG("Balcora device got minor %d", bal_miscdev.minor);
LOG_INFO("Path to Sajuuk successfully established.");
return 0;
}
module_init(bal_init);
module_exit(bal_exit);
MODULE_AUTHOR("Kewin Rausch <kewin.rausch@create-net.org>");
MODULE_DESCRIPTION("This is the Gate of Balcora, path to Sajuuk.");
MODULE_LICENSE("GPL");
|
kewinrausch/RNS
|
tools/balcora/balcora.c
|
C
|
gpl-2.0
| 30,667
|
<?php TheOne\Inc\Functions\paging_nav(); ?>
|
thefrosty/The-One-Theme
|
misc/loop-nav.php
|
PHP
|
gpl-2.0
| 43
|
<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
include_once('Smarty.class.php');
$main_smarty = new Smarty;
include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'link.php');
include(mnminclude.'smartyvariables.php');
require_once(realpath(dirname(__FILE__)) . "/vendor/autoload.php");
Logger::configure(realpath(dirname(__FILE__)) . '/conf/log4php.xml');
$logger = Logger::getLogger("generalLog");
// breadcrumbs and page title
$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Login');
$navwhere['link1'] = getmyurl('loginNoVar', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Login'));
// sidebar
$main_smarty = do_sidebar($main_smarty);
// initialize error message variable
$errorMsg="";
// if user requests to logout
if($my_pligg_base){
if (strpos($_GET['return'],$my_pligg_base)!==0) $_GET['return']=$my_pligg_base . '/';
if (strpos($_POST['return'],$my_pligg_base)!==0) $_POST['return']=$my_pligg_base . '/';
}
if(isset($_GET["op"])){
if(sanitize($_GET["op"], 3) == 'logout') {
$current_user->Logout(sanitize($_GET['return'], 3));
}
}
// if user tries to log in
if( (isset($_POST["processlogin"]) && is_numeric($_POST["processlogin"])) || (isset($_GET["processlogin"]) && is_numeric($_GET["processlogin"])) ){
$logger->info("at user tries to log in ");
if($_POST["processlogin"] == 1) { // users logs in with username and password
$username = sanitize(trim($_POST['username']), 3);
$password = sanitize(trim($_POST['password']), 3);
if(isset($_POST['persistent'])){$persistent = sanitize($_POST['persistent'], 3);}else{$persistent = '';}
$dbusername = sanitize($db->escape($username),4);
require_once(mnminclude.'check_behind_proxy.php');
$lastip = check_ip_behind_proxy();
$logger->info("Last ip: $lastip");
$login = $db->get_row("SELECT *, UNIX_TIMESTAMP()-UNIX_TIMESTAMP(login_time) AS time FROM " . table_login_attempts . " WHERE login_ip='$lastip'");
$logger->info($login);
if ($login->login_id) {
$login_id = $login->login_id;
$logger->info("login_id = $login_id");
if ($login->time < 3) {
$errorMsg=sprintf($main_smarty->get_config_vars('PLIGG_Visual_Login_Error'),3);
}
elseif ($login->login_count>=3) {
if ($login->time < min(60*pow(2,$login->login_count-3),3600)) {
$errorMsg=sprintf($main_smarty->get_config_vars('PLIGG_Login_Incorrect_Attempts'),$login->login_count,min(60*pow(2,$login->login_count-3),3600)-$login->time);
}
}
}
elseif (!is_ip_approved($lastip)) {
$logger->info("last ip $lastip is not approved");
$logger->info("INSERT INTO ".table_login_attempts." SET login_username = '$dbusername', login_time=NOW(), login_ip='$lastip'");
$db->query("INSERT INTO ".table_login_attempts." SET login_username = '$dbusername', login_time=NOW(), login_ip='$lastip', login_count=0");
$login_id = $db->insert_id;
if (!$login_id) {
$errorMsg=sprintf($main_smarty->get_config_vars('PLIGG_Visual_Login_Error'),3);
}
}
$logger->error("error message: $errorMsg");
if (!$errorMsg)
{
$logger->info("before auth");
if($current_user->Authenticate($username, $password, $persistent) == false) {
{
$db->query("UPDATE ".table_login_attempts." SET login_username='$dbusername', login_count=login_count+1, login_time=NOW() WHERE login_id=".$login_id);
$errorMsg=$main_smarty->get_config_vars('PLIGG_Visual_Login_Error');
$logger->info("auth == false. Error message $errorMsg");
}
} else {
$logger->info("auth == true");
$sql = "DELETE FROM " . table_login_attempts . " WHERE login_ip='$lastip' ";
$db->query($sql);
if(strlen(sanitize($_POST['return'], 3)) > 1) {
$return = sanitize($_POST['return'], 3);
} else {
$return = my_pligg_base.'/';
}
$logger->info("return");
$logger->info($return);
define('logindetails', $username . ";" . $password . ";" . $return);
$vars = '';
check_actions('login_success_pre_redirect', $vars);
$logger->info("vars");
$logger->info($vars);
if(strpos($_SERVER['SERVER_SOFTWARE'], "IIS") && strpos(php_sapi_name(), "cgi") >= 0){
echo '<SCRIPT LANGUAGE="JavaScript">window.location="' . $return . '";</script>';
echo $main_smarty->get_config_vars('PLIGG_Visual_IIS_Logged_In') . '<a href = "'.$return.'">' . $main_smarty->get_config_vars('PLIGG_Visual_IIS_Continue') . '</a>';
} else {
$logger->info("setting header to $return");
header('Location: '.$return);
}
$logger->info("before die");
die;
}
}
}
if($_POST["processlogin"] == 3) { // if user requests forgotten password
$email = sanitize($db->escape(trim($_POST['email'])),4);
if (check_email($email)){
$user = $db->get_row("SELECT * FROM `" . table_users . "` where `user_email` = '".$email."' AND user_level!='Spammer'");
if($user){
$username = $user->user_login;
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
$saltedlogin = generateHash($user->user_login);
$to = $user->user_email;
$subject = $main_smarty->get_config_vars("PLIGG_PassEmail_Subject");
$password = substr(md5(uniqid(rand(), true)),0,8);
$saltedPass = generateHash($password);
$db->query('UPDATE `' . table_users . "` SET `user_pass` = '$saltedPass' WHERE `user_login` = '$username'");
$body = sprintf($main_smarty->get_config_vars("PLIGG_PassEmail_PassBody"),
$main_smarty->get_config_vars("PLIGG_Visual_Name"),
$my_base_url . $my_pligg_base . '/login.php',
$username,
$password);
//$body = $main_smarty->get_config_vars("PLIGG_PassEmail_Body") . $my_base_url . $my_pligg_base . '/login.php?processlogin=4&username=' . $username . '&confirmationcode=' . $saltedlogin;
$headers = 'From: ' . $main_smarty->get_config_vars("PLIGG_PassEmail_From") . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
if(time() - strtotime($user->last_reset_request) > $main_smarty->get_config_vars("PLIGG_PassEmail_LimitPerSecond")){
if (mail($to, $subject, $body, $headers))
{
$main_smarty->assign('user_login', $user->user_login);
$main_smarty->assign('profile_url', getmyurl('profile'));
$main_smarty->assign('login_url', getmyurl('loginNoVar'));
$errorMsg = $main_smarty->get_config_vars("PLIGG_PassEmail_SendSuccess");
$db->query('UPDATE `' . table_users . '` SET `last_reset_code` = "'. $saltedlogin . '" WHERE `user_login` = "'.$username.'"');
$db->query('UPDATE `' . table_users . '` SET `last_reset_request` = FROM_UNIXTIME('.time().') WHERE `user_login` = "'.$username.'"');
define('pagename', 'login');
$main_smarty->assign('pagename', pagename);
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Password_Sent');
}else{
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Delivery_Failed');
}
}else{
$errorMsg = $main_smarty->get_config_vars("PLIGG_PassEmail_LimitPerSecond_Message");
}
}else{
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Password_Sent');
}
}else{
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Register_Error_BadEmail');
}
}
if($_GET["processlogin"] == 4) { // if user clicks on the forgotten password confirmation code
$username = $db->escape(sanitize(sanitize(trim($_GET['username']), 3), 4));
if(strlen($username) == 0){
$errorMsg = $main_smarty->get_config_vars("PLIGG_Visual_Login_Forgot_Error");
}
else {
$confirmationcode = sanitize($_GET["confirmationcode"], 3);
$DBconf = $db->get_var("SELECT `last_reset_code` FROM `" . table_users . "` where `user_login` = '".$username."'");
if($DBconf){
if($DBconf == $confirmationcode && !empty($confirmationcode)){
$db->query('UPDATE `' . table_users . '` SET `last_reset_code` = "" WHERE `user_login` = "'.$username.'"');
$db->query('UPDATE `' . table_users . '` SET `user_pass` = "033700e5a7759d0663e33b18d6ca0dc2b572c20031b575750" WHERE `user_login` = "'.$username.'"');
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Forgot_PassReset');
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Forgot_ErrorBadCode');
}
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Forgot_ErrorBadCode');
}
}
}
}
// pagename
define('pagename', 'login');
$main_smarty->assign('pagename', pagename);
// misc smarty
$main_smarty->assign('errorMsg',$errorMsg);
$main_smarty->assign('register_url', getmyurl('register'));
// show the template
$main_smarty->assign('tpl_center', $the_template . '/login_center');
$main_smarty->display($the_template . '/pligg.tpl');
?>
|
ColFusion/ColfusionWeb
|
login.php
|
PHP
|
gpl-2.0
| 9,358
|
/*
Copyright © 2017 Wan Wai Ho <me@nestal.net>
This file is subject to the terms and conditions of the GNU General Public
License. See the file COPYING in the main directory of the spaghetti
distribution for more details.
*/
//
// Created by nestal on 2/12/17.
//
#include "ClassModel.hh"
#include "ClassItem.hh"
#include "Edge.hh"
#include "gui/common/MimeType.hh"
#include "codebase/DataType.hh"
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QGraphicsScene>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QMimeData>
#include <QtGui/QPainter>
#include <QtCore/QBuffer>
#include <QtSvg/QSvgGenerator>
#include <QDebug>
#include <cassert>
#include <iostream>
#include "gui/common/CommonIO.hh"
namespace gui {
namespace classgf {
template <typename ItemType, typename Container, typename Func>
auto ForEachItem(Container&& cont, Func func)
{
for (auto&& i : cont)
{
if (auto item = dynamic_cast<ItemType*>(i))
func(item);
}
return func;
}
ClassModel::ClassModel(const codebase::EntityMap *codebase, const QString& name, QObject *parent) :
QObject{parent},
m_name{name},
m_scene{std::make_unique<QGraphicsScene>(this)},
m_codebase{codebase}
{
assert(m_codebase);
}
ClassModel::~ClassModel() = default;
void ClassModel::SetRect(const QRectF& )
{
}
void ClassModel::Clear()
{
// delete all items
for (auto&& item : m_scene->items())
{
m_scene->removeItem(item);
delete item;
}
}
void ClassModel::AddEntity(const std::string& id, const QPointF& pos)
{
AddItem(id, m_codebase, pos);
}
template <typename... Args>
void ClassModel::AddItem(Args&&... args)
{
try
{
auto item = std::make_unique<ClassItem>(std::forward<Args>(args)...);
connect(item.get(), &ClassItem::OnJustChanged, this, &ClassModel::OnChildChanged);
// draw arrows
DetectEdges(item.get());
m_scene->addItem(item.release());
// the model is changed because it has one more entity
SetChanged(true);
}
catch (std::exception& e)
{
// TODO: print log
QMessageBox::warning(nullptr, "Exception when adding item", e.what());
}
}
QGraphicsScene *ClassModel::Scene()
{
return m_scene.get();
}
std::string ClassModel::Name() const
{
return m_name.toStdString();
}
void ClassModel::SetName(const QString& name)
{
m_name = name;
}
bool ClassModel::CanRename() const
{
return true;
}
/**
* \brief Detects the relationship between a newly added item and the rest
* \param item the newly added item
*
* This function will add the edges between the new \a item and other
* related ones.
*/
void ClassModel::DetectEdges(ClassItem *item)
{
ForEachItem<ClassItem>(m_scene->items(), [this, item](auto citem)
{
if (item->RelationOf(citem) != ItemRelation::no_relation && !item->HasEdgeWith(citem))
this->AddLine(citem, item);
});
}
void ClassModel::AddLine(ClassItem *from, ClassItem *to)
{
auto edge = std::make_shared<Edge>(from, to);
from->AddEdge(edge);
to->AddEdge(edge);
m_scene->addItem(edge.get());
}
void ClassModel::Load(const QJsonObject& obj)
{
// prevent AddEntity() to emit OnChange()
m_changed = true;
for (auto&& item : obj["classes"].toArray())
AddItem(item.toObject(), m_codebase);
m_changed = false;
}
QJsonObject ClassModel::Save() const
{
QJsonArray items;
ForEachItem<ClassItem>(m_scene->items(), [this, &items](auto citem)
{
items.append(citem->Save());
citem->MarkUnchanged();
});
SetChanged(false);
return QJsonObject{{"classes", items}};
}
void ClassModel::DeleteSelectedItem()
{
ForEachItem<ClassItem>(m_scene->selectedItems(), [this](auto dead_item)
{
this->DeleteItem(dead_item);
});
}
void ClassModel::DeleteItem(ClassItem *dead_item)
{
this->SetChanged(true);
m_scene->removeItem(dead_item->GraphicsItem());
delete dead_item;
}
bool ClassModel::IsChanged() const
{
return m_changed;
}
void ClassModel::OnChildChanged(BaseItem *)
{
SetChanged(true);
}
void ClassModel::SetChanged(bool changed) const
{
if (m_changed != changed)
{
emit OnChanged(changed);
m_changed = changed;
}
}
void ClassModel::UpdateCodeBase(const codebase::EntityMap *codebase)
{
ForEachItem<BaseItem>(m_scene->items(), [codebase](auto item)
{
item->Update(codebase);
});
// ClassItem::Update() will remove edges, need to add them back
ForEachItem<ClassItem>(m_scene->items(), [this](auto item)
{
this->DetectEdges(item);
});
}
QImage ClassModel::RenderImage(const QRectF& rect) const
{
// Create the image with the exact size of the shrunk scene
auto size = rect.isNull() ? m_scene->itemsBoundingRect().size().toSize() : rect.size().toSize();
QImage image{size, QImage::Format_ARGB32};
image.fill(Qt::transparent);
QPainter painter(&image);
m_scene->render(&painter, {}, rect);
return image;
}
std::unique_ptr<QMimeData> ClassModel::CopySelection() const
{
QRectF selected;
for (auto&& item : m_scene->selectedItems())
selected = selected.united(item->sceneBoundingRect());
auto mime = std::make_unique<QMimeData>();
mime->setImageData(RenderImage(selected));
mime->setData(mime::svg, RenderSVG(selected));
QJsonArray jarr;
ForEachItem<ClassItem>(m_scene->items(), [this, &jarr](auto citem)
{
jarr.append(citem->Save());
});
mime->setData(mime::json, QJsonDocument{jarr}.toJson());
return mime;
}
void ClassModel::Paste(const QMimeData* data)
{
assert(data);
if (data->hasFormat(mime::json))
{
auto json = QJsonDocument::fromJson(data->data(mime::json));
for (auto&& item : json.array())
{
AddItem(item.toObject(), m_codebase);
m_changed = true;
}
}
}
QByteArray ClassModel::RenderSVG(const QRectF& rect) const
{
auto size = rect.isNull() ? m_scene->itemsBoundingRect().size().toSize() : rect.size().toSize();
QBuffer b;
QSvgGenerator p;
p.setOutputDevice(&b);
p.setSize(size);
p.setViewBox(QRect{0, 0, size.width(), size.height()});
{
QPainter painter(&p);
m_scene->render(&painter, {}, rect);
}
return b.buffer();
}
void ClassModel::AddParentClass(ClassItem *item, const QPointF& pos)
{
if (!item && !m_scene->selectedItems().isEmpty())
item = dynamic_cast<ClassItem*>(m_scene->selectedItems().front());
if (item)
{
for (auto&& bases : item->DataType().BaseClasses())
AddEntity(bases.ID(), pos);
}
}
}} // end of namespace
|
nestal/spaghetti
|
gui/classgf/ClassModel.cc
|
C++
|
gpl-2.0
| 6,306
|
<?php
/**
* This file is part of the upgrade process.
*
* @package SendStudio
*/
/**
* Do a sanity check to make sure the upgrade api has been included.
*/
if (!class_exists('Upgrade_API', false)) {
exit();
}
/**
* This class runs one change for the upgrade process.
* The Upgrade_API looks for a RunUpgrade method to call.
* That should return false for failure
* It should return true for success or if the change has already been made.
*
* @package SendStudio
*/
class newsletters_set_format_html extends Upgrade_API
{
/**
* RunUpgrade
* Runs the query for the upgrade process
* and returns the result from the query.
* The calling function looks for a true or false result
*
* @return Mixed Returns true if the condition is already met (eg the column already exists).
* Returns false if the database query can't be run.
* Returns the resource from the query (which is then checked to be true).
*/
function RunUpgrade()
{
$query = 'update ' . SENDSTUDIO_TABLEPREFIX . 'newsletters set format=\'h\' where format=\'2\'';
$result = $this->Db->Query($query);
return $result;
}
}
|
cuong09m/krwe
|
emailmarketer/admin/com/upgrades/nx/newsletters_set_format_html.php
|
PHP
|
gpl-2.0
| 1,102
|
/*
* linux/include/asm-c6x/page_offset.h
*
* Port on Texas Instruments TMS320C6x architecture
*
* Copyright (C) 2004, 2009, 2010 Texas Instruments Incorporated
* Author: Aurelien Jacquiot (aurelien.jacquiot@jaluna.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.
*
*/
#ifndef _ASM_C6X_PAGE_OFFSET_H
#define _ASM_C6X_PAGE_OFFSET_H
#include <mach/hardware.h>
/* This handles the memory map */
#ifdef CONFIG_PAGE_OFFSET
#define PAGE_OFFSET_RAW CONFIG_PAGE_OFFSET
#else
#define PAGE_OFFSET_RAW RAM_DDR2_CE0
#endif
/* Maximum size for the kernel code */
#define KERNEL_TEXT_LEN 0x07ffffff
#endif /* _ASM_C6X_PAGE_OFFSET_H */
|
insys-projects/linux-c6x
|
arch/c6x/include/asm/page_offset.h
|
C
|
gpl-2.0
| 794
|
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Vendula Poncova <vponcova@redhat.com>
#
import unittest
from blivet.devices import DiskDevice
from blivet.formats import get_format
from blivet.size import Size
from pyanaconda.modules.common.constants.objects import DISK_SELECTION
from pyanaconda.modules.common.errors.storage import UnavailableStorageError
from pyanaconda.modules.common.structures.validation import ValidationReport
from pyanaconda.modules.storage.disk_selection import DiskSelectionModule
from pyanaconda.modules.storage.disk_selection.selection_interface import DiskSelectionInterface
from pyanaconda.storage.initialization import create_storage
from tests.nosetests.pyanaconda_tests import check_dbus_property
class DiskSelectionInterfaceTestCase(unittest.TestCase):
"""Test DBus interface of the disk selection module."""
def setUp(self):
"""Set up the module."""
self.disk_selection_module = DiskSelectionModule()
self.disk_selection_interface = DiskSelectionInterface(self.disk_selection_module)
def _test_dbus_property(self, *args, **kwargs):
check_dbus_property(
self,
DISK_SELECTION,
self.disk_selection_interface,
*args, **kwargs
)
def selected_disks_property_test(self):
"""Test the selected disks property."""
self._test_dbus_property(
"SelectedDisks",
["sda", "sdb"]
)
def validate_selected_disks_test(self):
"""Test ValidateSelectedDisks."""
storage = create_storage()
self.disk_selection_module.on_storage_changed(storage)
dev1 = DiskDevice(
"dev1",
exists=False,
size=Size("15 GiB"),
fmt=get_format("disklabel")
)
dev2 = DiskDevice(
"dev2",
exists=False,
parents=[dev1],
size=Size("6 GiB"),
fmt=get_format("disklabel")
)
dev3 = DiskDevice(
"dev3",
exists=False,
parents=[dev2],
size=Size("6 GiB"),
fmt=get_format("disklabel")
)
storage.devicetree._add_device(dev1)
storage.devicetree._add_device(dev2)
storage.devicetree._add_device(dev3)
report = ValidationReport.from_structure(
self.disk_selection_interface.ValidateSelectedDisks([])
)
self.assertEqual(report.is_valid(), True)
report = ValidationReport.from_structure(
self.disk_selection_interface.ValidateSelectedDisks(["dev1"])
)
self.assertEqual(report.is_valid(), False)
self.assertEqual(report.error_messages, [
"You selected disk dev1, which contains devices that also use "
"unselected disks dev2, dev3. You must select or de-select "
"these disks as a set."
])
self.assertEqual(report.warning_messages, [])
report = ValidationReport.from_structure(
self.disk_selection_interface.ValidateSelectedDisks(["dev1", "dev2"])
)
self.assertEqual(report.is_valid(), False)
self.assertEqual(report.error_messages, [
"You selected disk dev1, which contains devices that also "
"use unselected disk dev3. You must select or de-select "
"these disks as a set.",
"You selected disk dev2, which contains devices that also "
"use unselected disk dev3. You must select or de-select "
"these disks as a set."
])
self.assertEqual(report.warning_messages, [])
report = ValidationReport.from_structure(
self.disk_selection_interface.ValidateSelectedDisks(["dev1", "dev2", "dev3"])
)
self.assertEqual(report.is_valid(), True)
def exclusive_disks_property_test(self):
"""Test the exclusive disks property."""
self._test_dbus_property(
"ExclusiveDisks",
["sda", "sdb"]
)
def ignored_disks_property_test(self):
"""Test the ignored disks property."""
self._test_dbus_property(
"IgnoredDisks",
["sda", "sdb"]
)
def protected_disks_property_test(self):
"""Test the protected disks property."""
self._test_dbus_property(
"ProtectedDevices",
["sda", "sdb"]
)
def disk_images_property_test(self):
"""Test the protected disks property."""
self._test_dbus_property(
"DiskImages",
{
"image_1": "/path/1",
"image_2": "/path/2"
}
)
def get_usable_disks_test(self):
"""Test the GetUsableDisks method."""
with self.assertRaises(UnavailableStorageError):
self.disk_selection_interface.GetUsableDisks()
self.disk_selection_module.on_storage_changed(create_storage())
self.assertEqual(self.disk_selection_interface.GetUsableDisks(), [])
|
atodorov/anaconda
|
tests/nosetests/pyanaconda_tests/module_disk_select_test.py
|
Python
|
gpl-2.0
| 5,967
|
/***************************************************************************
* Copyright (C) 2009 by Tamino Dauth *
* tamino@cdauth.eu *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QtWidgets/QtWidgets>
#include "config.h"
#include "module.hpp"
#include "modulemenu.hpp"
#include "moduletoolbar.hpp"
#include "windowsmenu.hpp"
#include "mpqprioritylist.hpp"
#include "editor.hpp"
#include "settingsinterface.hpp"
#include "sourcesdialog.hpp"
#include "resourcesdialog.hpp"
namespace wc3lib
{
namespace editor
{
Module::Module(MpqPriorityList *source, const QString &organization, const QString &applicationName, QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f | Qt::Window)
, m_source(source)
, m_organization(organization)
, m_applicationName(applicationName)
, m_moduleMenu(0)
, m_menuBar(0)
, m_topLayout(new QVBoxLayout())
, m_centerLayout(new QGridLayout())
, m_sourcesDialog(0)
, m_resourcesDialog(0)
{
QVBoxLayout *layout = new QVBoxLayout(this);
setLayout(layout);
topLayout()->setAlignment(Qt::AlignTop);
layout->addLayout(topLayout());
layout->addLayout(centerLayout());
if (hasEditor())
{
connect(editor(), SIGNAL(switchedToMap(Map*)), this, SLOT(switchToMap(Map*)));
}
/*
* Make sure that qblp is loaded when the plugin is not installed.
*/
#ifdef DEBUG
QPluginLoader loader("../qblp/qblp.so");
if (loader.instance())
{
qDebug() << "Ok";
qDebug() << "Supported image formats:" << QImageReader::supportedImageFormats();
}
else
{
qDebug() << "fail" << loader.errorString();
}
#endif
}
Module::~Module()
{
}
bool Module::configure()
{
readSettings();
// Configure source if started as stand-alone module.
if (!hasEditor())
{
if (!source()->configure(this, m_organization, m_applicationName))
{
return false;
}
}
retranslateUi();
return true;
}
void Module::retranslateUi()
{
this->m_fileMenu->setTitle(this->source()->sharedData()->tr("WESTRING_MENU_FILE"));
if (!hasEditor())
{
m_closeAction->setText(source()->sharedData()->tr("WESTRING_MENU_CLOSEMODULE"));
}
this->m_sourcesAction->setText(tr("Sources"));
this->m_editMenu->setTitle(source()->sharedData()->tr("WESTRING_MENU_EDIT"));
this->m_windowsMenu->retranslateUi();
this->m_helpMenu->setTitle(tr("Help"));
}
bool Module::hasEditor() const
{
return dynamic_cast<Editor*>(source()) != 0;
}
Editor* Module::editor() const
{
return boost::polymorphic_cast<Editor*>(source());
}
QString Module::settingsGroup() const
{
if (this->hasEditor())
{
return "WorldEditor";
}
else
{
return this->objectName(); // TODO set app name
}
}
void Module::showSourcesDialog()
{
if (hasEditor())
{
editor()->showSourcesDialog();
}
else
{
if (m_sourcesDialog == 0)
{
m_sourcesDialog = new SourcesDialog(source(), m_organization, m_applicationName, this);
}
m_sourcesDialog->update();
m_sourcesDialog->show();
}
}
void Module::showResourcesDialog()
{
if (m_resourcesDialog == 0)
{
m_resourcesDialog = new ResourcesDialog(this);
}
m_resourcesDialog->setSources(source());
m_resourcesDialog->show();
}
void Module::aboutWc3lib()
{
QMessageBox::about(this, tr("About wc3lib"), tr("wc3lib has been created by Tamino Dauth"));
}
void Module::aboutQt()
{
QMessageBox::aboutQt(this);
}
void Module::setupUi()
{
this->m_menuBar = new QMenuBar(this);
topLayout()->addWidget(this->m_menuBar);
this->m_fileMenu = new QMenu(this);
this->menuBar()->addMenu(this->m_fileMenu);
connect(this->m_fileMenu, SIGNAL(triggered(QAction *)), this, SLOT(triggered(QAction*)));
// use actions from editor
if (hasEditor())
{
}
// create user-defined actions in file menu
this->createFileActions(this->m_fileMenu);
// use actions from editor
this->m_fileMenu->addSeparator();
if (hasEditor())
{
}
else
{
m_closeAction = new QAction(this);
}
this->m_fileMenu->addAction(m_closeAction);
this->m_sourcesAction = new QAction(this);
connect(this->m_sourcesAction, SIGNAL(triggered()), this, SLOT(showSourcesDialog()));
this->m_fileMenu->addAction(m_sourcesAction);
this->m_editMenu = new QMenu(this);
this->menuBar()->addMenu(this->m_editMenu);
// create user-defined actions in edit menu
this->createEditActions(this->m_editMenu);
// module menu
if (hasEditor())
{
this->m_moduleMenu = new ModuleMenu(this);
this->menuBar()->addMenu(this->m_moduleMenu);
}
// create user-defined menus
this->createMenus(this->menuBar());
this->m_windowsMenu = new WindowsMenu(this);
this->menuBar()->addMenu(windowsMenu());
// create user-defined actions in windows menu
this->createWindowsActions(windowsMenu());
this->m_helpMenu = new QMenu(this);
this->menuBar()->addMenu(this->m_helpMenu);
this->m_resourcesAction = new QAction(tr("Resources"), this);
connect(this->m_resourcesAction, SIGNAL(triggered()), this, SLOT(showResourcesDialog()));
this->m_helpMenu->addAction(this->m_resourcesAction);
this->m_aboutWc3libAction = new QAction(tr("About wc3lib"), this);
connect(this->m_aboutWc3libAction, SIGNAL(triggered()), this, SLOT(aboutWc3lib()));
this->m_helpMenu->addAction(this->m_aboutWc3libAction);
this->m_aboutQtAction = new QAction(tr("About Qt"), this);
connect(this->m_aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()));
this->m_helpMenu->addAction(this->m_aboutQtAction);
// tool bar
this->m_toolBar = new ModuleToolBar(this);
this->topLayout()->addWidget(m_toolBar);
// user defined tool buttons
this->createToolButtons(toolBar());
}
void Module::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::ActivationChange && hasEditor())
{
const_cast<const Editor*>(editor())->modulesActions()[this]->setChecked(this->isActiveWindow());
}
else if (event->type() == QEvent::LanguageChange)
{
this->retranslateUi();
}
}
void Module::readSettings()
{
if (!this->hasEditor())
{
QSettings settings(organization(), applicationName());
this->source()->readSettings(settings, settingsGroup());
}
}
void Module::writeSettings()
{
if (!this->hasEditor())
{
QSettings settings(organization(), applicationName());
this->source()->writeSettings(settings, settingsGroup());
}
}
void Module::onEditorActionTrigger()
{
this->show();
this->activateWindow();
this->raise();
}
void Module::triggered(QAction *action)
{
if (this->isActiveWindow() && action == m_closeAction)
{
this->close();
}
}
void Module::switchToMap(Map *map)
{
onSwitchToMap(map);
}
#include "moc_module.cpp"
}
}
|
tdauth/wc3lib
|
src/editor/module.cpp
|
C++
|
gpl-2.0
| 7,755
|
/* $Id: content.css,v 1.12.2.3 2008/08/22 22:10:57 yched Exp $ */
/* Node display */
.field .field-label,
.field .field-label-inline,
.field .field-label-inline-first {
font-weight:bold;
}
.field .field-label-inline,
.field .field-label-inline-first {
display:inline;
}
.field .field-label-inline {
visibility:hidden;
}
/* Node form display */
.node-form .content-multiple-table td.content-multiple-drag {
width:30px;
padding-right:0;
}
.node-form .content-multiple-table td.content-multiple-drag a.tabledrag-handle{
padding-right:.5em;
}
.node-form .content-add-more .form-submit{
margin:0;
}
.node-form .number {
display:inline;
width:auto;
}
.node-form .text {
width:auto;
}
/* CSS overrides for Views-based autocomplete results.
- #autocomplete uses "white-space:pre", which is no good with
Views' template-based rendering
- Field titles are rendered with <label> in default templates,
but we don't want the 'form' styling it gets under .form-item
*/
.form-item #autocomplete .reference-autocomplete {
white-space:normal;
}
.form-item #autocomplete .reference-autocomplete label {
display:inline;
font-weight:normal;
}
/* 'Manage fields' overview */
table.content-field-overview, table.content-field-overview fieldset table {
width:100%;
}
table.content-field-overview td {
width:14%;
}
.content-field-overview-empty {
text-align:center;
}
|
pirog/mdo
|
sites/all/modules/cck/theme/content.css
|
CSS
|
gpl-2.0
| 1,461
|
## This file is part of Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
This is the Create_Modify_Interface function (along with its helpers).
It is used by WebSubmit for the "Modify Bibliographic Information" action.
"""
__revision__ = "$Id$"
import os
import re
import time
import pprint
from invenio.dbquery import run_sql
from invenio.websubmit_config import InvenioWebSubmitFunctionError
from invenio.websubmit_functions.Retrieve_Data import Get_Field
from invenio.errorlib import register_exception
def Create_Modify_Interface_getfieldval_fromfile(cur_dir, fld=""):
"""Read a field's value from its corresponding text file in 'cur_dir' (if it exists) into memory.
Delete the text file after having read-in its value.
This function is called on the reload of the modify-record page. This way, the field in question
can be populated with the value last entered by the user (before reload), instead of always being
populated with the value still found in the DB.
"""
fld_val = ""
if len(fld) > 0 and os.access("%s/%s" % (cur_dir, fld), os.R_OK|os.W_OK):
fp = open( "%s/%s" % (cur_dir, fld), "r" )
fld_val = fp.read()
fp.close()
try:
os.unlink("%s/%s"%(cur_dir, fld))
except OSError:
# Cannot unlink file - ignore, let WebSubmit main handle this
pass
fld_val = fld_val.strip()
return fld_val
def Create_Modify_Interface_getfieldval_fromDBrec(fieldcode, recid):
"""Read a field's value from the record stored in the DB.
This function is called when the Create_Modify_Interface function is called for the first time
when modifying a given record, and field values must be retrieved from the database.
"""
fld_val = ""
if fieldcode != "":
for next_field_code in [x.strip() for x in fieldcode.split(",")]:
fld_val += "%s\n" % Get_Field(next_field_code, recid)
fld_val = fld_val.rstrip('\n')
return fld_val
def Create_Modify_Interface_transform_date(fld_val):
"""Accept a field's value as a string. If the value is a date in one of the following formats:
DD Mon YYYY (e.g. 23 Apr 2005)
YYYY-MM-DD (e.g. 2005-04-23)
...transform this date value into "DD/MM/YYYY" (e.g. 23/04/2005).
"""
if re.search("^[0-9]{2} [a-z]{3} [0-9]{4}$", fld_val, re.IGNORECASE) is not None:
try:
fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%d %b %Y"))
except (ValueError, TypeError):
# bad date format:
pass
elif re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2}$", fld_val, re.IGNORECASE) is not None:
try:
fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%Y-%m-%d"))
except (ValueError,TypeError):
# bad date format:
pass
return fld_val
def Create_Modify_Interface(parameters, curdir, form, user_info=None):
"""
Create an interface for the modification of a document, based on
the fields that the user has chosen to modify. This avoids having
to redefine a submission page for the modifications, but rely on
the elements already defined for the initial submission i.e. SBI
action (The only page that needs to be built for the modification
is the page letting the user specify a document to modify).
This function should be added at step 1 of your modification
workflow, after the functions that retrieves report number and
record id (Get_Report_Number, Get_Recid). Functions at step 2 are
the one executed upon successful submission of the form.
Create_Modify_Interface expects the following parameters:
* "fieldnameMBI" - the name of a text file in the submission
working directory that contains a list of the names of the
WebSubmit fields to include in the Modification interface.
These field names are separated by"\n" or "+".
Given the list of WebSubmit fields to be included in the
modification interface, the values for each field are retrieved
for the given record (by way of each WebSubmit field being
configured with a MARC Code in the WebSubmit database). An HTML
FORM is then created. This form allows a user to modify certain
field values for a record.
The file referenced by 'fieldnameMBI' is usually generated from a
multiple select form field): users can then select one or several
fields to modify
Note that the function will display WebSubmit Response elements,
but will not be able to set an initial value: this must be done by
the Response element iteself.
Additionally the function creates an internal field named
'Create_Modify_Interface_DONE' on the interface, that can be
retrieved in curdir after the form has been submitted.
This flag is an indicator for the function that displayed values
should not be retrieved from the database, but from the submitted
values (in case the page is reloaded). You can also rely on this
value when building your WebSubmit Response element in order to
retrieve value either from the record, or from the submission
directory.
"""
global sysno,rn
t = ""
# variables declaration
fieldname = parameters['fieldnameMBI']
# Path of file containing fields to modify
the_globals = {
'doctype' : doctype,
'action' : action,
'act' : action, ## for backward compatibility
'step' : step,
'access' : access,
'ln' : ln,
'curdir' : curdir,
'uid' : user_info['uid'],
'uid_email' : user_info['email'],
'rn' : rn,
'last_step' : last_step,
'action_score' : action_score,
'__websubmit_in_jail__' : True,
'form': form,
'sysno': sysno,
'user_info' : user_info,
'__builtins__' : globals()['__builtins__'],
'Request_Print': Request_Print
}
if os.path.exists("%s/%s" % (curdir, fieldname)):
fp = open( "%s/%s" % (curdir, fieldname), "r" )
fieldstext = fp.read()
fp.close()
fieldstext = re.sub("\+","\n", fieldstext)
fields = fieldstext.split("\n")
else:
res = run_sql("SELECT fidesc FROM sbmFIELDDESC WHERE name=%s", (fieldname,))
if len(res) == 1:
fields = res[0][0].replace(" ", "")
fields = re.findall("<optionvalue=.*>", fields)
regexp = re.compile("""<optionvalue=(?P<quote>['|"]?)(?P<value>.*?)(?P=quote)""")
fields = [regexp.search(x) for x in fields]
fields = [x.group("value") for x in fields if x is not None]
fields = [x for x in fields if x not in ("Select", "select")]
else:
raise InvenioWebSubmitFunctionError("cannot find fields to modify")
#output some text
t = t+"<CENTER bgcolor=\"white\">The document <B>%s</B> has been found in the database.</CENTER><br />Please modify the following fields:<br />Then press the 'END' button at the bottom of the page<br />\n" % rn
for field in fields:
subfield = ""
value = ""
marccode = ""
text = ""
# retrieve and display the modification text
t = t + "<FONT color=\"darkblue\">\n"
res = run_sql("SELECT modifytext FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res)>0:
t = t + "<small>%s</small> </FONT>\n" % res[0][0]
# retrieve the marc code associated with the field
res = run_sql("SELECT marccode FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res) > 0:
marccode = res[0][0]
# then retrieve the previous value of the field
if os.path.exists("%s/%s" % (curdir, "Create_Modify_Interface_DONE")):
# Page has been reloaded - get field value from text file on server, not from DB record
value = Create_Modify_Interface_getfieldval_fromfile(curdir, field)
else:
# First call to page - get field value from DB record
value = Create_Modify_Interface_getfieldval_fromDBrec(marccode, sysno)
# If field is a date value, transform date into format DD/MM/YYYY:
value = Create_Modify_Interface_transform_date(value)
res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res) > 0:
element_type = res[0][3]
numcols = res[0][6]
numrows = res[0][5]
size = res[0][4]
maxlength = res[0][7]
val = res[0][8]
fidesc = res[0][9]
if element_type == "T":
text = "<TEXTAREA name=\"%s\" rows=%s cols=%s wrap>%s</TEXTAREA>" % (field, numrows, numcols, value)
elif element_type == "F":
text = "<INPUT TYPE=\"file\" name=\"%s\" size=%s maxlength=\"%s\">" % (field, size, maxlength)
elif element_type == "I":
value = re.sub("[\n\r\t]+", "", value)
text = "<INPUT name=\"%s\" size=%s value=\"%s\"> " % (field, size, val)
text = text + "<SCRIPT>document.forms[0].%s.value=\"%s\";</SCRIPT>" % (field, value)
elif element_type == "H":
text = "<INPUT type=\"hidden\" name=\"%s\" value=\"%s\">" % (field, val)
text = text + "<SCRIPT>document.forms[0].%s.value=\"%s\";</SCRIPT>" % (field, value)
elif element_type == "S":
values = re.split("[\n\r]+", value)
text = fidesc
if re.search("%s\[\]" % field, fidesc):
multipletext = "[]"
else:
multipletext = ""
if len(values) > 0 and not(len(values) == 1 and values[0] == ""):
text += "<SCRIPT>\n"
text += "var i = 0;\n"
text += "el = document.forms[0].elements['%s%s'];\n" % (field, multipletext)
text += "max = el.length;\n"
for val in values:
text += "var found = 0;\n"
text += "var i=0;\n"
text += "while (i != max) {\n"
text += " if (el.options[i].value == \"%s\" || el.options[i].text == \"%s\") {\n" % (val, val)
text += " el.options[i].selected = true;\n"
text += " found = 1;\n"
text += " }\n"
text += " i=i+1;\n"
text += "}\n"
#text += "if (found == 0) {\n"
#text += " el[el.length] = new Option(\"%s\", \"%s\", 1,1);\n"
#text += "}\n"
text += "</SCRIPT>\n"
elif element_type == "D":
text = fidesc
elif element_type == "R":
try:
co = compile(fidesc.replace("\r\n", "\n"), "<string>", "exec")
## Note this exec is safe WRT global variable because the
## Create_Modify_Interface has already been parsed by
## execfile within a protected environment.
the_globals['text'] = ''
exec co in the_globals
text = the_globals['text']
except:
msg = "Error in evaluating response element %s with globals %s" % (pprint.pformat(field), pprint.pformat(globals()))
register_exception(req=None, alert_admin=True, prefix=msg)
raise InvenioWebSubmitFunctionError(msg)
else:
text = "%s: unknown field type" % field
t = t + "<small>%s</small>" % text
# output our flag field
t += '<input type="hidden" name="Create_Modify_Interface_DONE" value="DONE\n" />'
# output some more text
t = t + "<br /><br /><CENTER><small><INPUT type=\"button\" width=400 height=50 name=\"End\" value=\"END\" onClick=\"document.forms[0].step.value = 2;user_must_confirm_before_leaving_page = false;document.forms[0].submit();\"></small></CENTER></H4>"
return t
|
pombredanne/invenio
|
modules/websubmit/lib/functions/Create_Modify_Interface.py
|
Python
|
gpl-2.0
| 12,904
|
#ifdef O3_WITH_GLUE
#pragma warning( disable : 4100)
#pragma warning( disable : 4189)
namespace o3 {
Trait* cJs1::select()
{
return clsTraits();
}
Trait* cJs1::clsTraits()
{
static Trait TRAITS[] = {
{ 0, Trait::TYPE_BEGIN, "cJs1", 0, 0, 0, cScr::clsTraits() },
{ 0, Trait::TYPE_FUN, "cJs1", "include", clsInvoke, 0, 0 },
{ 1, Trait::TYPE_FUN, "cJs1", "eval", clsInvoke, 1, 0 },
{ 0, Trait::TYPE_END, "cJs1", 0, 0, 0, 0 },
};
return TRAITS;
}
Trait* cJs1::extTraits()
{
static Trait TRAITS[] = {
{ 0, Trait::TYPE_BEGIN, "cJs1", 0, 0, 0, 0 },
{ 0, Trait::TYPE_GET, "cO3", "js", extInvoke, 0, 0 },
{ 0, Trait::TYPE_END, "cJs1", 0, 0, 0, 0 },
};
return TRAITS;
}
siEx cJs1::clsInvoke(iScr* pthis, iCtx* ctx, int index, int argc,
const Var* argv, Var* rval)
{
siEx ex;
cJs1* pthis1 = (cJs1*) pthis;
switch(index) {
case 0:
if (argc != 1)
return o3_new(cEx)("Invalid argument count. ( include )");
*rval = pthis1->include(argv[0].toStr(),&ex);
break;
case 1:
if (argc != 1)
return o3_new(cEx)("Invalid argument count. ( eval )");
*rval = pthis1->eval(argv[0].toStr(),&ex);
break;
}
return ex;
}
siEx cJs1::extInvoke(iScr* pthis, iCtx* ctx, int index, int argc,
const Var* argv, Var* rval)
{
siEx ex;
cJs1* pthis1 = (cJs1*) pthis;
switch(index) {
case 0:
if (argc != 0)
return o3_new(cEx)("Invalid argument count. ( js )");
*rval = pthis1->js(ctx);
break;
}
return ex;
}
}
#endif
#pragma warning(default : 4100)
#pragma warning(default : 4189)
|
krizsa/node-o3
|
include/js/o3_scr_cJs1_win32.h
|
C
|
gpl-2.0
| 2,349
|
/* $Id: error_gui.cpp 25982 2013-11-13 21:35:44Z rubidium $ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file error_gui.cpp GUI related to errors. */
#include "stdafx.h"
#include "landscape.h"
#include "newgrf_text.h"
#include "error.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "string_func.h"
#include "company_base.h"
#include "company_manager_face.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "window_func.h"
#include "console_func.h"
#include "window_gui.h"
#include "widgets/error_widget.h"
#include "table/strings.h"
#include <list>
static const NWidgetPart _nested_errmsg_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_RED),
NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_RED),
NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetPadding(0, 2, 0, 2), SetMinimalSize(236, 32),
EndContainer(),
};
static WindowDesc _errmsg_desc(
WDP_MANUAL, "error", 0, 0,
WC_ERRMSG, WC_NONE,
0,
_nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
);
static const NWidgetPart _nested_errmsg_face_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_RED),
NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_RED),
NWidget(NWID_HORIZONTAL), SetPIP(2, 1, 2),
NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_FACE), SetMinimalSize(92, 119), SetFill(0, 1), SetPadding(2, 0, 1, 0),
NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetFill(0, 1), SetMinimalSize(238, 123),
EndContainer(),
EndContainer(),
};
static WindowDesc _errmsg_face_desc(
WDP_MANUAL, "error_face", 0, 0,
WC_ERRMSG, WC_NONE,
0,
_nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
);
/**
* Copy the given data into our instance.
* @param data The data to copy.
*/
ErrorMessageData::ErrorMessageData(const ErrorMessageData &data)
{
*this = data;
for (size_t i = 0; i < lengthof(this->strings); i++) {
if (this->strings[i] != NULL) {
this->strings[i] = strdup(this->strings[i]);
this->decode_params[i] = (size_t)this->strings[i];
}
}
}
/** Free all the strings. */
ErrorMessageData::~ErrorMessageData()
{
for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
}
/**
* Display an error message in a window.
* @param summary_msg General error message showed in first line. Must be valid.
* @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
* @param duration The amount of time to show this error message.
* @param x World X position (TileVirtX) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
* @param y World Y position (TileVirtY) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
* @param textref_stack_size Number of uint32 values to put on the #TextRefStack for the error message; 0 if the #TextRefStack shall not be used.
* @param textref_stack Values to put on the #TextRefStack.
*/
ErrorMessageData::ErrorMessageData(StringID summary_msg, StringID detailed_msg, uint duration, int x, int y, uint textref_stack_size, const uint32 *textref_stack) :
duration(duration),
textref_stack_size(textref_stack_size),
summary_msg(summary_msg),
detailed_msg(detailed_msg),
face(INVALID_COMPANY)
{
this->position.x = x;
this->position.y = y;
memset(this->decode_params, 0, sizeof(this->decode_params));
memset(this->strings, 0, sizeof(this->strings));
if (textref_stack_size > 0) MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
assert(summary_msg != INVALID_STRING_ID);
}
/**
* Copy error parameters from current DParams.
*/
void ErrorMessageData::CopyOutDParams()
{
/* Reset parameters */
for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
memset(this->decode_params, 0, sizeof(this->decode_params));
memset(this->strings, 0, sizeof(this->strings));
/* Get parameters using type information */
if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_size, this->textref_stack);
CopyOutDParam(this->decode_params, this->strings, this->detailed_msg == INVALID_STRING_ID ? this->summary_msg : this->detailed_msg, lengthof(this->decode_params));
if (this->textref_stack_size > 0) StopTextRefStackUsage();
if (this->detailed_msg == STR_ERROR_OWNED_BY) {
CompanyID company = (CompanyID)GetDParamX(this->decode_params, 2);
if (company < MAX_COMPANIES) face = company;
}
}
/**
* Set a error string parameter.
* @param n Parameter index
* @param v Parameter value
*/
void ErrorMessageData::SetDParam(uint n, uint64 v)
{
this->decode_params[n] = v;
}
/**
* Set a rawstring parameter.
* @param n Parameter index
* @param str Raw string
*/
void ErrorMessageData::SetDParamStr(uint n, const char *str)
{
free(this->strings[n]);
this->strings[n] = strdup(str);
}
/** Define a queue with errors. */
typedef std::list<ErrorMessageData> ErrorList;
/** The actual queue with errors. */
ErrorList _error_list;
/** Whether the window system is initialized or not. */
bool _window_system_initialized = false;
/** Window class for displaying an error message window. */
struct ErrmsgWindow : public Window, ErrorMessageData {
private:
uint height_summary; ///< Height of the #summary_msg string in pixels in the #WID_EM_MESSAGE widget.
uint height_detailed; ///< Height of the #detailed_msg string in pixels in the #WID_EM_MESSAGE widget.
public:
ErrmsgWindow(const ErrorMessageData &data) : Window(data.HasFace() ? &_errmsg_face_desc : &_errmsg_desc), ErrorMessageData(data)
{
this->InitNested();
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
{
if (widget != WID_EM_MESSAGE) return;
CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_size, this->textref_stack);
int text_width = max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
this->height_summary = GetStringHeight(this->summary_msg, text_width);
this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
if (this->textref_stack_size > 0) StopTextRefStackUsage();
uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
size->height = max(size->height, panel_height);
}
virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
{
/* Position (0, 0) given, center the window. */
if (this->position.x == 0 && this->position.y == 0) {
Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
return pt;
}
/* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
* Add a fixed distance 20 to make it less cluttered.
*/
int scr_top = GetMainViewTop() + 20;
int scr_bot = GetMainViewBottom() - 20;
Point pt = RemapCoords2(this->position.x, this->position.y);
const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
if (this->face == INVALID_COMPANY) {
/* move x pos to opposite corner */
pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - sm_width - 20 : 20; // Stay 20 pixels away from the edge of the screen.
/* move y pos to opposite corner */
pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
pt.y = (pt.y < (_screen.height >> 1)) ? scr_bot - sm_height : scr_top;
} else {
pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (sm_width / 2), 0, _screen.width - sm_width);
pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (sm_height / 2), scr_top, scr_bot - sm_height);
}
return pt;
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
{
/* If company gets shut down, while displaying an error about it, remove the error message. */
if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) delete this;
}
virtual void SetStringParameters(int widget) const
{
if (widget == WID_EM_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
}
virtual void DrawWidget(const Rect &r, int widget) const
{
switch (widget) {
case WID_EM_FACE: {
const Company *c = Company::Get(this->face);
DrawCompanyManagerFace(c->face, c->colour, r.left, r.top);
break;
}
case WID_EM_MESSAGE:
CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_size, this->textref_stack);
if (this->detailed_msg == INVALID_STRING_ID) {
DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
this->summary_msg, TC_FROMSTRING, SA_CENTER);
} else {
int extra = (r.bottom - r.top + 1 - this->height_summary - this->height_detailed - WD_PAR_VSEP_WIDE) / 2;
/* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
int top = r.top + WD_FRAMERECT_TOP;
int bottom = top + this->height_summary + extra;
DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_WHITE, SA_CENTER);
bottom = r.bottom - WD_FRAMERECT_BOTTOM;
top = bottom - this->height_detailed - extra;
DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_WHITE, SA_CENTER);
}
if (this->textref_stack_size > 0) StopTextRefStackUsage();
break;
default:
break;
}
}
virtual void OnMouseLoop()
{
/* Disallow closing the window too easily, if timeout is disabled */
if (_right_button_down && this->duration != 0) delete this;
}
virtual void OnHundredthTick()
{
/* Timeout enabled? */
if (this->duration != 0) {
this->duration--;
if (this->duration == 0) delete this;
}
}
~ErrmsgWindow()
{
SetRedErrorSquare(INVALID_TILE);
if (_window_system_initialized) ShowFirstError();
}
virtual EventState OnKeyPress(WChar key, uint16 keycode)
{
if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
delete this;
return ES_HANDLED;
}
/**
* Check whether the currently shown error message was critical or not.
* @return True iff the message was critical.
*/
bool IsCritical()
{
return this->duration == 0;
}
};
/**
* Clear all errors from the queue.
*/
void ClearErrorMessages()
{
UnshowCriticalError();
_error_list.clear();
}
/** Show the first error of the queue. */
void ShowFirstError()
{
_window_system_initialized = true;
if (!_error_list.empty()) {
new ErrmsgWindow(_error_list.front());
_error_list.pop_front();
}
}
/**
* Unshow the critical error. This has to happen when a critical
* error is shown and we uninitialise the window system, i.e.
* remove all the windows.
*/
void UnshowCriticalError()
{
ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
if (_window_system_initialized && w != NULL) {
if (w->IsCritical()) _error_list.push_front(*w);
_window_system_initialized = false;
delete w;
}
}
/**
* Display an error message in a window.
* @param summary_msg General error message showed in first line. Must be valid.
* @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
* @param wl Message severity.
* @param x World X position (TileVirtX) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
* @param y World Y position (TileVirtY) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
* @param textref_stack_size Number of uint32 values to put on the #TextRefStack for the error message; 0 if the #TextRefStack shall not be used.
* @param textref_stack Values to put on the #TextRefStack.
*/
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x, int y, uint textref_stack_size, const uint32 *textref_stack)
{
assert(textref_stack_size == 0 || textref_stack != NULL);
if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
if (wl != WL_INFO) {
/* Print message to console */
char buf[DRAW_STRING_BUFFER];
if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_size, textref_stack);
char *b = GetString(buf, summary_msg, lastof(buf));
if (detailed_msg != INVALID_STRING_ID) {
b += seprintf(b, lastof(buf), " ");
GetString(b, detailed_msg, lastof(buf));
}
if (textref_stack_size > 0) StopTextRefStackUsage();
switch (wl) {
case WL_WARNING: IConsolePrint(CC_WARNING, buf); break;
default: IConsoleError(buf); break;
}
}
bool no_timeout = wl == WL_CRITICAL;
if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
ErrorMessageData data(summary_msg, detailed_msg, no_timeout ? 0 : _settings_client.gui.errmsg_duration, x, y, textref_stack_size, textref_stack);
data.CopyOutDParams();
ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
if (w != NULL && w->IsCritical()) {
/* A critical error is currently shown. */
if (wl == WL_CRITICAL) {
/* Push another critical error in the queue of errors,
* but do not put other errors in the queue. */
_error_list.push_back(data);
}
} else {
/* Nothing or a non-critical error was shown. */
delete w;
new ErrmsgWindow(data);
}
}
/**
* Schedule a list of errors.
* Note: This does not try to display the error now. This is useful if the window system is not yet running.
* @param data Error message datas; cleared afterwards
*/
void ScheduleErrorMessage(ErrorList &datas)
{
_error_list.splice(_error_list.end(), datas);
}
/**
* Schedule an error.
* Note: This does not try to display the error now. This is useful if the window system is not yet running.
* @param data Error message data; cleared afterwards
*/
void ScheduleErrorMessage(const ErrorMessageData &data)
{
_error_list.push_back(data);
}
|
Palo123/openttd_yacd_pp_dc
|
openttd/src/error_gui.cpp
|
C++
|
gpl-2.0
| 15,317
|
#include <QtCore/QCoreApplication>
#include "armatool.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
armaTool(argc, argv);
return 0;
}
|
SnakeManPMC/arma-2-ArmATool
|
main.cpp
|
C++
|
gpl-2.0
| 175
|
function displayThumbs(scrollId) {
$("#thumbs img:first").addClass("selected");
$(".jTscroller").removeAttr("style");
$(".jTscrollerContainer").removeAttr("style");
$(".jThumbnailScroller").removeAttr("style");
$(".jThumbnailScroller").attr("id", scrollId);
$("#" + scrollId).thumbnailScroller({
scrollerType:"hoverPrecise",
scrollerOrientation:"horizontal",
scrollSpeed:2,
scrollEasing:"easeOutCirc",
scrollEasingAmount:600,
acceleration:4,
scrollSpeed:800,
noScrollCenterSpace:10,
autoScrolling:0,
autoScrollingSpeed:2000,
autoScrollingEasing:"easeInOutQuad",
autoScrollingDelay:500
});
}
|
Tibo-R/chocobox
|
js/thumbnail_manager.js
|
JavaScript
|
gpl-2.0
| 653
|
<?php
/* --------------------------------------------------------------
RedirectHttpControllerResponse.inc.php 2015-03-12 gm
Gambio GmbH
http://www.gambio.de
Copyright (c) 2015 Gambio GmbH
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
*/
MainFactory::load_class('HttpControllerResponse');
/**
* Value object
*
* Class RedirectHttpControllerResponse
*
* @category System
* @package Http
* @subpackage ValueObjects
* @extends HttpControllerResponse
*/
class RedirectHttpControllerResponse extends HttpControllerResponse
{
/**
* @param string $p_location
* @param bool $p_movedPermanently
*/
public function __construct($p_location, $p_movedPermanently = false)
{
if($p_movedPermanently)
{
$this->httpHeadersArray[] = 'HTTP/1.1 301 Moved Permanently';
}
$this->httpHeadersArray[] = 'Location: ' . $p_location;
}
}
|
carlosway89/testshop
|
GXEngine/Classes/SystemServices/Http/ValueObjects/RedirectHttpControllerResponse.inc.php
|
PHP
|
gpl-2.0
| 985
|
# devitawinardi
Halo halo, ini Dwi Devitasari :D
|
devitawinardi/devitawinardi
|
README.md
|
Markdown
|
gpl-2.0
| 49
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Kinoraw Tools: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="jump_to_cut_panel_001.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Kinoraw Tools
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
</div><!-- top -->
<div class="contents">
<div class="textblock">Here is a list of all namespace members with links to the namespace documentation for each member:</div>
<h3><a class="anchor" id="index_a"></a>- a -</h3><ul>
<li>act_strip()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#adac038d3e61d8fba3e0d526695f767b6">kinoraw_tools::functions</a>
</li>
<li>add_marker()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a213c725e829d988f84105c54f35d1051">kinoraw_tools::functions</a>
</li>
<li>align
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#af29c72f5ffed70d5a5a283221eb4d4a3">kinoraw_tools::jumptocut</a>
</li>
</ul>
<h3><a class="anchor" id="index_b"></a>- b -</h3><ul>
<li>basestring
: <a class="el" href="namespacekinoraw__tools_1_1exiftool.html#ae9ba889b7e9446b78d42cd8a837653cd">kinoraw_tools::exiftool</a>
</li>
<li>bl_description
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#a63f210ae1df7473a61a1271bb9c3762e">kinoraw_tools::jumptocut</a>
</li>
<li>bl_idname
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#a90837065caae87ff942aefc88095a87b">kinoraw_tools::jumptocut</a>
</li>
<li>bl_info
: <a class="el" href="namespacekinoraw__tools.html#acfb532d1827a93d7503aa8d3571b33aa">kinoraw_tools</a>
</li>
<li>bl_label
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#a438a100c19901ff0ebe5097dde76bda8">kinoraw_tools::jumptocut</a>
</li>
<li>bl_options
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#aa3a7dc1e2e9aa4233a97ab53e4b9cfc4">kinoraw_tools::jumptocut</a>
</li>
<li>block_size
: <a class="el" href="namespacekinoraw__tools_1_1exiftool.html#ad7bac69337a171ae5dd180fd48841ad3">kinoraw_tools::exiftool</a>
</li>
</ul>
<h3><a class="anchor" id="index_c"></a>- c -</h3><ul>
<li>clip_clip_menu_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#a4dc959c37357fb6b86a0162109ce1e55">kinoraw_tools::ui</a>
</li>
<li>clip_header_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#a16d97651e9af07765e2d890c2a1ded85">kinoraw_tools::ui</a>
</li>
<li>create_folder()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a6f2c970d249a88451b8d81f485d1f819">kinoraw_tools::functions</a>
</li>
<li>create_proxy()
: <a class="el" href="namespacekinoraw__tools_1_1proxy__tools.html#a23c553d0b6264f28b946722ab1dcd3ca">kinoraw_tools::proxy_tools</a>
</li>
<li>create_proxy_scripts()
: <a class="el" href="namespacekinoraw__tools_1_1proxy__tools.html#a6bcb7f3e3429e4cedc7f9a67f6fb0da3">kinoraw_tools::proxy_tools</a>
</li>
<li>createavi()
: <a class="el" href="namespacekinoraw__tools_1_1datamosh.html#a7ecee003214ecc51dfc29cfbe3ad2f00">kinoraw_tools::datamosh</a>
</li>
<li>createavimjpeg()
: <a class="el" href="namespacekinoraw__tools_1_1datamosh.html#abccbddf84a9105b5fa5a8a61530f0e49">kinoraw_tools::datamosh</a>
</li>
<li>createdatamosh()
: <a class="el" href="namespacekinoraw__tools_1_1datamosh.html#aed3ecd7c508760b803cefe2cde0951e5">kinoraw_tools::datamosh</a>
</li>
<li>createsyncfile()
: <a class="el" href="namespacekinoraw__tools_1_1audio__tools.html#aa781edbb610c0fcb8aaa467a0052025a">kinoraw_tools::audio_tools</a>
</li>
</ul>
<h3><a class="anchor" id="index_d"></a>- d -</h3><ul>
<li>detect_strip_type()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a77e0e7766ac1eb9b5ae5940a9d01b89a">kinoraw_tools::functions</a>
</li>
<li>draw_color_balance()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#abe839c21f66eed3748719a8a4c6a5b5d">kinoraw_tools::ui</a>
</li>
</ul>
<h3><a class="anchor" id="index_e"></a>- e -</h3><ul>
<li>executable
: <a class="el" href="namespacekinoraw__tools_1_1exiftool.html#a84ecc4dad00e48c6f4288a36b85893e0">kinoraw_tools::exiftool</a>
</li>
<li>execute()
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#ac5595fcbacf254a88e95c36121d3ad2d">kinoraw_tools::jumptocut</a>
</li>
</ul>
<h3><a class="anchor" id="index_f"></a>- f -</h3><ul>
<li>fsencode
: <a class="el" href="namespacekinoraw__tools_1_1exiftool.html#a7b8e9249cacc366be42da33b7c92a271">kinoraw_tools::exiftool</a>
</li>
</ul>
<h3><a class="anchor" id="index_g"></a>- g -</h3><ul>
<li>generate_subsets_list()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a09196451c93f518f5b91f0c820d47639">kinoraw_tools::functions</a>
</li>
<li>get_cut_dict()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#ac7209744df499a6886827880df706ffa">kinoraw_tools::functions</a>
</li>
<li>get_marker_dict()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a0310a140c297671df78f7aa1ed003869">kinoraw_tools::functions</a>
</li>
<li>get_matching_markers()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a43f8432b6f53d12b7ed407d065671126">kinoraw_tools::functions</a>
</li>
<li>get_selected_strips()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a0f24c5673d466069109618c903461d44">kinoraw_tools::functions</a>
</li>
<li>getfilepathfrombrowser()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a5c7c2bf35faf1c1938474f0db854287e">kinoraw_tools::functions</a>
</li>
<li>getpathfrombrowser()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#aa51b6d6b00254b35ee6fcd4e1822a112">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_i"></a>- i -</h3><ul>
<li>imb_ext_audio
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#ab28e9c9e6f561913a5d6f9693714f933">kinoraw_tools::functions</a>
</li>
<li>imb_ext_image
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#acf7240b191f8546a7a39cf3117123137">kinoraw_tools::functions</a>
</li>
<li>imb_ext_movie
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a2da8d4e8ac8324659a139a4f76d0493b">kinoraw_tools::functions</a>
</li>
<li>initSceneProperties()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a05b273850356cd1af9955215a3cb5d3b">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_m"></a>- m -</h3><ul>
<li>marker_handler()
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#a87751d3a1cd9398f974ff05786a4ccb4">kinoraw_tools::jumptocut</a>
</li>
<li>movieextdict
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#ae7ca1e89c86400f8d5c3676e9429fc40">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_o"></a>- o -</h3><ul>
<li>onefolder()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#abb0b4ce4b13e43ba63b216adf8f6cda0">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_p"></a>- p -</h3><ul>
<li>poll()
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#a1ed16c2e212ff34b31b4fe5039be7721">kinoraw_tools::jumptocut</a>
</li>
<li>proxy_qualities
: <a class="el" href="namespacekinoraw__tools_1_1audio__tools.html#a30c903fb0872711a5dd08e8af543c7de">kinoraw_tools::audio_tools</a>
, <a class="el" href="namespacekinoraw__tools_1_1datamosh.html#a2256201eb5ac37f64e17a8c9b7bcdeeb">kinoraw_tools::datamosh</a>
, <a class="el" href="namespacekinoraw__tools_1_1proxy__tools.html#abb967cb0b010e2b2c7be7681497aa88e">kinoraw_tools::proxy_tools</a>
</li>
</ul>
<h3><a class="anchor" id="index_r"></a>- r -</h3><ul>
<li>random_edit_from_random_subset()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#af93853e4146a29a92adf9345f4cf1f3f">kinoraw_tools::functions</a>
</li>
<li>randomframe()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a9081271653f9f152ea07dd72a4064165">kinoraw_tools::functions</a>
</li>
<li>randompartition()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a204f661afb0040ca3bf85acea94e9b3e">kinoraw_tools::functions</a>
</li>
<li>readsyncfile()
: <a class="el" href="namespacekinoraw__tools_1_1audio__tools.html#ac2dad93a34c911508a6257777c01bed0">kinoraw_tools::audio_tools</a>
</li>
<li>recursive()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#aa376f7db9db38b4672e3cb347305d61f">kinoraw_tools::functions</a>
</li>
<li>register()
: <a class="el" href="namespacekinoraw__tools.html#a7c3974a99f9b0ec9ba475be6e7559f15">kinoraw_tools</a>
</li>
</ul>
<h3><a class="anchor" id="index_s"></a>- s -</h3><ul>
<li>sentinel
: <a class="el" href="namespacekinoraw__tools_1_1exiftool.html#adafd0bcfd46814787a4ca69a19b07006">kinoraw_tools::exiftool</a>
</li>
<li>sequencer_add_menu_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#ac2a6b13757086fe50e8a9840553b43d9">kinoraw_tools::ui</a>
</li>
<li>sequencer_header_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#aab5d2683632718f8f596d805180a25bc">kinoraw_tools::ui</a>
</li>
<li>sequencer_select_menu_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#a282f23f9d96b7fcec1889642368b7a15">kinoraw_tools::ui</a>
</li>
<li>sequencer_strip_menu_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#a52b5d9c52cd827c1fd7e34abcd9fec31">kinoraw_tools::ui</a>
</li>
<li>setpathinbrowser()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a9c6f2ac0bad05e9d6dc9ffe00ad5126b">kinoraw_tools::functions</a>
</li>
<li>setup_proxy()
: <a class="el" href="namespacekinoraw__tools_1_1proxy__tools.html#a1c57755a4eeeaa11d3787c6284644a06">kinoraw_tools::proxy_tools</a>
</li>
<li>side
: <a class="el" href="namespacekinoraw__tools_1_1jumptocut.html#aeb3a26355c83cf62d006e2e71232ac69">kinoraw_tools::jumptocut</a>
</li>
<li>sortlist()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#a0873f423ee4e30ebab56d27816b2c107">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_t"></a>- t -</h3><ul>
<li>time_frame_menu_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#ad291e62f95e34c3c8c4fb95e11779070">kinoraw_tools::ui</a>
</li>
<li>time_header_func()
: <a class="el" href="namespacekinoraw__tools_1_1ui.html#a6920ebaeba30586ffaa7dff8d4a1a188">kinoraw_tools::ui</a>
</li>
<li>triminout()
: <a class="el" href="namespacekinoraw__tools_1_1functions.html#aa68db671c1363e6024a3f90e78448e29">kinoraw_tools::functions</a>
</li>
</ul>
<h3><a class="anchor" id="index_u"></a>- u -</h3><ul>
<li>unregister()
: <a class="el" href="namespacekinoraw__tools.html#a935e6e38524d78e4b1adb5d477ffa1c9">kinoraw_tools</a>
</li>
</ul>
<h3><a class="anchor" id="index_w"></a>- w -</h3><ul>
<li>writesyncfile()
: <a class="el" href="namespacekinoraw__tools_1_1audio__tools.html#a99cdd7f6d285595a3e3c8e51378dc821">kinoraw_tools::audio_tools</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Apr 7 2015 18:19:16 for Kinoraw Tools by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
|
kinoraw/kinoraw_tools
|
doc/html/namespacemembers.html
|
HTML
|
gpl-2.0
| 11,874
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Review\Test\TestCase;
use Magento\Review\Test\Fixture\Rating;
use Magento\Review\Test\Fixture\Review;
use Magento\Review\Test\Page\Adminhtml\RatingEdit;
use Magento\Review\Test\Page\Adminhtml\RatingIndex;
use Magento\Review\Test\Page\Adminhtml\ReviewEdit;
use Magento\Review\Test\Page\Adminhtml\ReviewIndex;
use Magento\Mtf\TestCase\Injectable;
/**
* Preconditions:
* 1. Simple Product created.
*
* Steps:
* 1. Login to backend.
* 2. Navigate to Marketing > User Content > Reviews.
* 3. Click the "+" (Add New Review) button.
* 4. Select the product in the Products Grid.
* 5. Fill data according to DataSet.
* 6. Click "Save Review" button.
* 7. Perform Asserts.
*
* @group Reviews_and_Ratings
* @ZephyrId MAGETWO-26476
*/
class CreateProductReviewBackendEntityTest extends Injectable
{
/* tags */
const MVP = 'no';
const TO_MAINTAIN = 'yes';
/* end tags */
/**
* ReviewIndex page.
*
* @var ReviewIndex
*/
protected $reviewIndex;
/**
* ReviewEdit page.
*
* @var ReviewEdit
*/
protected $reviewEdit;
/**
* RatingIndex page.
*
* @var RatingIndex
*/
protected $ratingIndex;
/**
* RatingEdit page.
*
* @var RatingEdit
*/
protected $ratingEdit;
/**
* Product rating fixture.
*
* @var Rating
*/
protected $productRating;
/**
* Review fixture.
*
* @var Review
*/
protected $review;
/**
* Inject pages into test.
*
* @param ReviewIndex $reviewIndex
* @param ReviewEdit $reviewEdit
* @param RatingIndex $ratingIndex
* @param RatingEdit $ratingEdit
* @return void
*/
public function __inject(
ReviewIndex $reviewIndex,
ReviewEdit $reviewEdit,
RatingIndex $ratingIndex,
RatingEdit $ratingEdit
) {
$this->reviewIndex = $reviewIndex;
$this->reviewEdit = $reviewEdit;
$this->ratingIndex = $ratingIndex;
$this->ratingEdit = $ratingEdit;
}
/**
* Run Create Product Review Entity Backend Test.
*
* @param Review $review
* @return array
*/
public function test(Review $review)
{
// Precondition:
$product = $review->getDataFieldConfig('entity_id')['source']->getEntity();
$filter = ['sku' => $product->getSku()];
$this->review = $review;
// Steps:
$this->reviewIndex->open();
$this->reviewIndex->getReviewActions()->addNew();
$this->reviewEdit->getProductGrid()->search($filter);
$this->reviewEdit->getProductGrid()->openFirstRow();
$this->reviewEdit->getReviewForm()->fill($this->review);
$this->reviewEdit->getPageActions()->save();
return ['product' => $product];
}
/**
* Clear data after test.
*
* @return void
*/
public function tearDown()
{
$this->ratingIndex->open();
if ($this->review instanceof Review) {
foreach ($this->review->getRatings() as $rating) {
$this->ratingIndex->getRatingGrid()->searchAndOpen(['rating_code' => $rating['title']]);
$this->ratingEdit->getPageActions()->delete();
$this->ratingEdit->getModalBlock()->acceptAlert();
}
}
}
}
|
kunj1988/Magento2
|
dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewBackendEntityTest.php
|
PHP
|
gpl-2.0
| 3,468
|
<?php
/*
* This file is a part of HDS (HeBIS Discovery System). HDS is an
* extension of the open source library search engine VuFind, that
* allows users to search and browse beyond resources. More
* Information about VuFind you will find on http://www.vufind.org
*
* Copyright (C) 2016
* HeBIS Verbundzentrale des HeBIS-Verbundes
* Goethe-Universität Frankfurt / Goethe University of Frankfurt
* http://www.hebis.de
*
* 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.
*/
namespace Hebis\View\Helper\Record;
use Hebis\RecordDriver\SolrMarc;
use Hebis\Marc\Helper;
/**
* Class RecordGetSubFieldDataOfField
* @package Hebis\View\Helper\Record
*
* @author Sebastian Böttger <boettger@hebis.uni-frankfurt.de>
*/
class RecordGetSubFieldDataOfField extends AbstractRecordViewHelper
{
/**
* returns the data of the subField if field and subField exists, otherwise false
*
* @param SolrMarc $record
* @param $fieldCode
* @param $subFieldCode
* @return bool|string
*/
public function __invoke(SolrMarc $record, $fieldCode, $subFieldCode)
{
return Helper::getSubFieldDataOfField($record->getMarcRecord(), $fieldCode, $subFieldCode);
}
}
|
HeBIS-VZ/vufind-module-hebis
|
src/Hebis/View/Helper/Record/RecordGetSubFieldDataOfField.php
|
PHP
|
gpl-2.0
| 1,878
|
/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */
const Clutter = imports.gi.Clutter;
const Pango = imports.gi.Pango;
const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
const Shell = imports.gi.Shell;
const Lang = imports.lang;
const Signals = imports.signals;
const St = imports.gi.St;
const Mainloop = imports.mainloop;
const AppFavorites = imports.ui.appFavorites;
const DND = imports.ui.dnd;
const Main = imports.ui.main;
const Overview = imports.ui.overview;
const PopupMenu = imports.ui.popupMenu;
const Search = imports.ui.search;
const Tweener = imports.ui.tweener;
const Workspace = imports.ui.workspace;
const AppDisplay = imports.ui.appDisplay;
const AltTab = imports.ui.altTab;
const Gettext = imports.gettext.domain('gnome-shell-extensions');
const _ = Gettext.gettext;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;
// Settings
const DOCK_POSITION_KEY = 'position';
const DOCK_SIZE_KEY = 'size';
const DOCK_HIDE_KEY = 'autohide';
const DOCK_EFFECTHIDE_KEY = 'hide-effect';
const DOCK_AUTOHIDE_ANIMATION_TIME_KEY = 'hide-effect-duration';
const DOCK_MONITOR_KEY = 'monitor';
// Keep enums in sync with GSettings schemas
const PositionMode = {
LEFT: 0,
RIGHT: 1
};
const AutoHideEffect = {
RESIZE: 0,
RESCALE: 1,
MOVE: 2
};
const DND_RAISE_APP_TIMEOUT = 500;
// Utility function to make the dock clipped to the primary monitor
function updateClip(actor, monitorNumber) {
let monitor;
if (monitorNumber > -1 && monitorNumber < Main.layoutManager.monitors.length)
monitor = Main.layoutManager.monitors[monitorNumber];
else
monitor = Main.layoutManager.primaryMonitor;
let allocation = actor.allocation;
// Here we implicitly assume that the stage and actor's parent
// share the same coordinate space
let clip = new Clutter.ActorBox({ x1: Math.max(monitor.x, allocation.x1),
y1: Math.max(monitor.y, allocation.y1),
x2: Math.min(monitor.x + monitor.width, allocation.x2),
y2: Math.min(monitor.y + monitor.height, allocation.y2) });
// Translate back into actor's coordinate space
clip.x1 -= actor.x;
clip.x2 -= actor.x;
clip.y1 -= actor.y;
clip.y2 -= actor.y;
// Apply the clip
actor.set_clip(clip.x1, clip.y1, clip.x2-clip.x1, clip.y2 - clip.y1);
}
/*************************************************************************************/
/**** start resize's Dock functions *****************/
/*************************************************************************************/
function hideDock_size () {
if (!this._hideable)
return;
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let position_x = monitor.x;
let height = (this._nicons)*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
Tweener.addTween(this, {
_item_size: 1,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function () {
height = (this._nicons)*(this._item_size + this._spacing) + 2*this._spacing;
width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
position_x=monitor.x-2*this._spacing;
break;
case PositionMode.RIGHT:
default:
position_x = monitor.x + (monitor.width-1-this._item_size-2*this._spacing);
}
this.actor.set_position (position_x,monitor.y+(monitor.height-height)/2);
this.actor.set_size(width,height);
updateClip(this.actor, this._displayMonitor);
},
});
this._hidden = true;
}
function showDock_size () {
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let height = (this._nicons)*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
let position_x = monitor.x;
Tweener.addTween(this, {
_item_size: this._settings.get_int(DOCK_SIZE_KEY),
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function () {
height = (this._nicons)*(this._item_size + this._spacing) + 2*this._spacing;
width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
position_x=monitor.x-2*this._spacing;
break;
case PositionMode.RIGHT:
default:
position_x=monitor.x + (monitor.width-this._item_size-2*this._spacing);
}
this.actor.set_position (position_x, monitor.y+(monitor.height-height)/2);
this.actor.set_size(width,height);
updateClip(this.actor, this._displayMonitor);
}
});
this._hidden = false;
}
function showEffectAddItem_size () {
let primary = Main.layoutManager.primaryMonitor;
let height = (this._nicons)*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
Tweener.addTween(this.actor, {
y: primary.y + (primary.height-height)/2,
height: height,
width: width,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function (monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
}
/**************************************************************************************/
/**** start rescale's Dock functions *****************/
/**************************************************************************************/
function hideDock_scale () {
if (!this._hideable)
return;
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let cornerX = 0;
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
cornerX=monitor.x;
break;
case PositionMode.RIGHT:
default:
cornerX = monitor.x + monitor.width-1;
}
Tweener.addTween(this.actor,{
y: monitor.y + (monitor.height-height)/2,
x: cornerX,
height:height,
width: width,
scale_x: 0.025,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
this._hidden = true;
}
function showDock_scale () {
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let position_x = monitor.x;
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
position_x=monitor.x-2*this._spacing;
break;
case PositionMode.RIGHT:
default:
position_x=monitor.x + (monitor.width-this._item_size-2*this._spacing);
}
Tweener.addTween(this.actor, {
y: monitor.y + (monitor.height-height)/2,
x: monitor.x + position_x,
height: height,
width: width,
scale_x: 1,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
this._hidden = false;
}
function showEffectAddItem_scale () {
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
Tweener.addTween(this.actor, {
y: monitor.y + (monitor.height-height)/2,
height: height,
width: width,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
}
/**************************************************************************************/
/**** start move Dock functions *****************/
/**************************************************************************************/
function hideDock_move () {
if (!this._hideable)
return;
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let cornerX = 0;
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
cornerX= monitor.x - width + this._spacing;
break;
case PositionMode.RIGHT:
default:
cornerX = monitor.x + monitor.width - this._spacing;
}
Tweener.addTween(this.actor,{
x: cornerX,
y: monitor.y + (monitor.height - height)/2,
width: width,
height: height,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
this._hidden = true;
}
function showDock_move () {
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let position_x = monitor.x;
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
position_x=monitor.x - 2*this._spacing;
break;
case PositionMode.RIGHT:
default:
position_x=monitor.x + (monitor.width-this._item_size-2*this._spacing);
}
Tweener.addTween(this.actor, {
x: position_x,
y: monitor.y + (monitor.height - height)/2,
width: width,
height: height,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
this._hidden = false;
}
function showEffectAddItem_move () {
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let height = this._nicons*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
Tweener.addTween(this.actor, {
y: monitor.y + (monitor.height-height)/2,
height: height,
width: width,
time: this._settings.get_double(DOCK_AUTOHIDE_ANIMATION_TIME_KEY),
transition: 'easeOutQuad',
onUpdate: function(monitor) {
updateClip(this, monitor);
},
onUpdateParams: [this._displayMonitor]
});
}
const Dock = new Lang.Class({
Name: 'Dock.Dock',
_init : function() {
this._placeholderText = null;
this._menus = [];
this._menuDisplays = [];
this._favorites = [];
// Load Settings
this._settings = Convenience.getSettings();
this._hidden = false;
this._hideable = this._settings.get_boolean(DOCK_HIDE_KEY);
this._displayMonitor = this._settings.get_int(DOCK_MONITOR_KEY);
this._spacing = 4;
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
this._nicons = 0;
this._selectEffectFunctions(this._settings.get_enum(DOCK_EFFECTHIDE_KEY));
let [_x, _y, _w, _h] = this.get_start_position();
this.actor = new St.BoxLayout({ name: 'dock', vertical: true, reactive: true,
x: _x, y: _y, width: _w, height: _h });
this._grid = new Shell.GenericContainer();
this.actor.add(this._grid, { expand: true, y_align: St.Align.START });
this.actor.connect('style-changed', Lang.bind(this, this._onStyleChanged));
this._grid.connect('get-preferred-width', Lang.bind(this, this._getPreferredWidth));
this._grid.connect('get-preferred-height', Lang.bind(this, this._getPreferredHeight));
this._grid.connect('allocate', Lang.bind(this, this._allocate));
this._workId = Main.initializeDeferredWork(this.actor, Lang.bind(this, this._redisplay));
this._tracker = Shell.WindowTracker.get_default();
this._appSystem = Shell.AppSystem.get_default();
this._installedChangedId = this._appSystem.connect('installed-changed', Lang.bind(this, this._queueRedisplay));
this._appFavoritesChangedId = AppFavorites.getAppFavorites().connect('changed', Lang.bind(this, this._queueRedisplay));
this._appStateChangedId = this._appSystem.connect('app-state-changed', Lang.bind(this, this._queueRedisplay));
this._overviewShowingId = Main.overview.connect('showing', Lang.bind(this, function() {
this.actor.hide();
}));
this._overviewHiddenId = Main.overview.connect('hidden', Lang.bind(this, function() {
this.actor.show();
}));
Main.layoutManager.addChrome(this.actor,
{ affectsStruts: !this._settings.get_boolean(DOCK_HIDE_KEY) });
//hidden
this._settings.connect('changed::'+DOCK_POSITION_KEY, Lang.bind(this, this._redisplay));
this._settings.connect('changed::'+DOCK_SIZE_KEY, Lang.bind(this, this._redisplay));
this._settings.connect('changed::'+DOCK_MONITOR_KEY, Lang.bind(this, function (){
this._displayMonitor = this._settings.get_int(DOCK_MONITOR_KEY);
this._redisplay();
}));
this._settings.connect('changed::'+DOCK_HIDE_KEY, Lang.bind(this, function (){
Main.layoutManager.removeChrome(this.actor);
Main.layoutManager.addChrome(this.actor,
{ affectsStruts: !this._settings.get_boolean(DOCK_HIDE_KEY) });
this._hideable = this._settings.get_boolean(DOCK_HIDE_KEY);
if (this._hideable)
this._hideDock();
else
this._showDock();
}));
this._settings.connect('changed::' + DOCK_EFFECTHIDE_KEY, Lang.bind(this, function () {
let hideEffect = this._settings.get_enum(DOCK_EFFECTHIDE_KEY);
// restore the effects of the other functions
switch (hideEffect) {
case AutoHideEffect.RESCALE:
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
break;
case AutoHideEffect.RESIZE:
this.actor.set_scale(1, 1);
break;
case AutoHideEffect.MOVE:
this.actor.set_scale(1, 1);
this._item_size = this._settings.get_int(DOCK_SIZE_KEY);
}
this.actor.disconnect(this._leave_event);
this.actor.disconnect(this._enter_event);
this._selectEffectFunctions(hideEffect);
this._leave_event = this.actor.connect('leave-event', Lang.bind(this, this._hideDock));
this._enter_event = this.actor.connect('enter-event', Lang.bind(this, this._showDock));
this._redisplay();
}));
this._leave_event = this.actor.connect('leave-event', Lang.bind(this, this._hideDock));
this._enter_event = this.actor.connect('enter-event', Lang.bind(this, this._showDock));
this._hideDock();
},
get_start_position: function() {
let item_size = this._settings.get_int(DOCK_SIZE_KEY);
let monitor = Main.layoutManager.primaryMonitor;
if (this._displayMonitor > -1 && this._displayMonitor < Main.layoutManager.monitors.length) {
monitor = Main.layoutManager.monitors[this._displayMonitor];
}
let position_x = monitor.x;
let width = item_size + 4 * this._spacing;
switch (this._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
position_x=monitor.x - 2 * this._spacing;
break;
case PositionMode.RIGHT:
default:
position_x=monitor.x + (monitor.width - item_size - 2 * this._spacing);
}
return [ position_x, monitor.y, width, monitor.height ];
},
destroy: function() {
if (this._installedChangedId) {
this._appSystem.disconnect(this._installedChangedId);
this._installedChangedId = 0;
}
if (this._appFavoritesChangedId) {
AppFavorites.getAppFavorites().disconnect(this._appFavoritesChangedId);
this._appFavoritesChangedId = 0;
}
if (this._appStateChangedId) {
this._appSystem.disconnect(this._appStateChangedId);
this._appStateChangedId = 0;
}
if (this._overviewShowingId) {
Main.overview.disconnect(this._overviewShowingId);
this._overviewShowingId = 0;
}
if (this._overviewHiddenId) {
Main.overview.disconnect(this._overviewHiddenId);
this._overviewHiddenId = 0;
}
this.actor.destroy();
// Break reference cycles
this._settings.run_dispose();
this._settings = null;
this._appSystem = null;
this._tracker = null;
},
// fuctions hide
_restoreHideDock: function() {
this._hideable = this._settings.get_boolean(DOCK_HIDE_KEY);
},
_disableHideDock: function() {
this._hideable = false;
},
_selectEffectFunctions: function(hideEffect) {
switch (hideEffect) {
case AutoHideEffect.RESCALE:
this._hideDock = hideDock_scale;
this._showDock = showDock_scale;
this._showEffectAddItem = showEffectAddItem_scale;
break;
case AutoHideEffect.MOVE:
this._hideDock = hideDock_move;
this._showDock = showDock_move;
this._showEffectAddItem = showEffectAddItem_move;
break;
case AutoHideEffect.RESIZE:
default:
this._hideDock = hideDock_size;
this._showDock = showDock_size;
this._showEffectAddItem = showEffectAddItem_size;
}
},
_appIdListToHash: function(apps) {
let ids = {};
for (let i = 0; i < apps.length; i++)
ids[apps[i].get_id()] = apps[i];
return ids;
},
_queueRedisplay: function () {
Main.queueDeferredWork(this._workId);
},
_redisplay: function () {
this.removeAll();
let favorites = AppFavorites.getAppFavorites().getFavoriteMap();
let running = this._appSystem.get_running();
let runningIds = this._appIdListToHash(running);
let icons = 0;
let nFavorites = 0;
for (let id in favorites) {
let app = favorites[id];
let display = new DockIcon(app,this);
this.addItem(display.actor);
nFavorites++;
icons++;
}
for (let i = 0; i < running.length; i++) {
let app = running[i];
if (app.get_id() in favorites)
continue;
let display = new DockIcon(app,this);
icons++;
this.addItem(display.actor);
}
this._nicons=icons;
if (this._placeholderText) {
this._placeholderText.destroy();
this._placeholderText = null;
}
if (running.length == 0 && nFavorites == 0) {
this._placeholderText = new St.Label({ text: _("Drag here to add favorites") });
this.actor.add_actor(this._placeholderText);
}
let primary = Main.layoutManager.primaryMonitor;
let height = (icons)*(this._item_size + this._spacing) + 2*this._spacing;
let width = this._item_size + 4*this._spacing;
if (this._hideable && this._hidden) {
this._hideDock();
} else {
if (this._settings.get_int(DOCK_SIZE_KEY) == this._item_size) {
// only add/delete icon
this._showEffectAddItem ();
} else {
// change size icon
this._showDock ();
}
}
},
_getPreferredWidth: function (grid, forHeight, alloc) {
alloc.min_size = this._item_size;
alloc.natural_size = this._item_size + this._spacing;
},
_getPreferredHeight: function (grid, forWidth, alloc) {
let children = this._grid.get_children();
let nRows = children.length;
let totalSpacing = Math.max(0, nRows - 1) * this._spacing;
let height = nRows * this._item_size + totalSpacing;
alloc.min_size = height;
alloc.natural_size = height;
},
_allocate: function (grid, box, flags) {
let children = this._grid.get_children();
let x = box.x1 + this._spacing;
if (this._settings.get_enum(DOCK_POSITION_KEY) == PositionMode.LEFT)
x = box.x1 + 2*this._spacing;
let y = box.y1 + this._spacing;
for (let i = 0; i < children.length; i++) {
let childBox = new Clutter.ActorBox();
childBox.x1 = x;
childBox.y1 = y;
childBox.x2 = childBox.x1 + this._item_size;
childBox.y2 = childBox.y1 + this._item_size;
children[i].allocate(childBox, flags);
y += this._item_size + this._spacing;
}
},
_onStyleChanged: function() {
let themeNode = this.actor.get_theme_node();
let [success, len] = themeNode.get_length('spacing', false);
if (success)
this._spacing = len;
[success, len] = themeNode.get_length('-shell-grid-item-size', false);
if (success)
this._item_size = len;
this._grid.queue_relayout();
},
removeAll: function () {
this._grid.get_children().forEach(Lang.bind(this, function (child) {
child.destroy();
}));
},
addItem: function(actor) {
this._grid.add_actor(actor);
}
});
Signals.addSignalMethods(Dock.prototype);
const DockIcon = new Lang.Class({
Name: 'Dock.DockIcon',
_init : function(app, dock) {
this._dock = dock;
this._settings = dock._settings;
this.app = app;
this.actor = new St.Button({ style_class: 'app-well-app',
button_mask: St.ButtonMask.ONE | St.ButtonMask.TWO,
reactive: true,
x_fill: true,
y_fill: true });
this.actor._delegate = this;
this._icon = new AppDisplay.AppIcon(app, { setSizeManually: true,
showLabel: false });
this.actor.set_child(this._icon.actor);
this._icon.setIconSize(this._settings.get_int(DOCK_SIZE_KEY));
this.actor.connect('clicked', Lang.bind(this, this._onClicked));
this._menu = null;
this._menuManager = new PopupMenu.PopupMenuManager(this);
this._has_focus = false;
let tracker = Shell.WindowTracker.get_default();
tracker.connect('notify::focus-app', Lang.bind(this, this._onStateChanged));
this.actor.connect('button-press-event', Lang.bind(this, this._onButtonPress));
this.actor.connect('destroy', Lang.bind(this, this._onDestroy));
this.actor.connect('notify::hover', Lang.bind(this, this._hoverChanged));
this._menuTimeoutId = 0;
this._stateChangedId = this.app.connect('notify::state',
Lang.bind(this, this._onStateChanged));
this._onStateChanged();
},
_onDestroy: function() {
if (this._stateChangedId > 0)
this.app.disconnect(this._stateChangedId);
this._stateChangedId = 0;
this._removeMenuTimeout();
},
_removeMenuTimeout: function() {
if (this._menuTimeoutId > 0) {
Mainloop.source_remove(this._menuTimeoutId);
this._menuTimeoutId = 0;
}
},
_hoverChanged: function(actor) {
if (actor != this.actor)
this._has_focus = false;
else
this._has_focus = true;
return false;
},
_onStateChanged: function() {
let tracker = Shell.WindowTracker.get_default();
let focusedApp = tracker.focus_app;
if (this.app.state != Shell.AppState.STOPPED) {
this.actor.add_style_class_name('running');
if (this.app == focusedApp) {
this.actor.add_style_class_name('focused');
} else {
this.actor.remove_style_class_name('focused');
}
} else {
this.actor.remove_style_class_name('focused');
this.actor.remove_style_class_name('running');
}
},
_onButtonPress: function(actor, event) {
let button = event.get_button();
if (button == 1) {
this._removeMenuTimeout();
this._menuTimeoutId = Mainloop.timeout_add(AppDisplay.MENU_POPUP_TIMEOUT, Lang.bind(this, function() {
this.popupMenu();
}));
} else if (button == 3) {
this.popupMenu();
}
},
_onClicked: function(actor, button) {
this._removeMenuTimeout();
if (button == 1) {
this._onActivate(Clutter.get_current_event());
} else if (button == 2) {
// Last workspace is always empty
let launchWorkspace = global.screen.get_workspace_by_index(global.screen.n_workspaces - 1);
launchWorkspace.activate(global.get_current_time());
this.emit('launching');
this.app.open_new_window(-1);
}
return false;
},
getId: function() {
return this.app.get_id();
},
popupMenu: function() {
this._removeMenuTimeout();
this.actor.fake_release();
this._dock._disableHideDock();
if (!this._menu) {
this._menu = new DockIconMenu(this);
this._menu.connect('activate-window', Lang.bind(this, function (menu, window) {
this.activateWindow(window);
}));
this._menu.connect('open-state-changed', Lang.bind(this, function (menu, isPoppedUp) {
if (!isPoppedUp){
//Restore value of autohidedock
this._dock._restoreHideDock();
this._dock._hideDock();
this._onMenuPoppedDown();
}
}));
this._menuManager.addMenu(this._menu, true);
}
this._menu.redisplay();
this._menu.open();
return false;
},
activateWindow: function(metaWindow) {
if (metaWindow) {
this._didActivateWindow = true;
Main.activateWindow(metaWindow);
}
},
setSelected: function (isSelected) {
this._selected = isSelected;
if (this._selected)
this.actor.add_style_class_name('selected');
else
this.actor.remove_style_class_name('selected');
},
_onMenuPoppedDown: function() {
this.actor.sync_hover();
},
_getRunning: function() {
return this.app.state != Shell.AppState.STOPPED;
},
_onActivate: function (event) {
this.emit('launching');
let modifiers = event.get_state();
if (modifiers & Clutter.ModifierType.CONTROL_MASK
&& this.app.state == Shell.AppState.RUNNING) {
let current_workspace = global.screen.get_active_workspace().index();
this.app.open_new_window(current_workspace);
} else {
let tracker = Shell.WindowTracker.get_default();
let focusedApp = tracker.focus_app;
if (this.app == focusedApp) {
let windows = this.app.get_windows();
let current_workspace = global.screen.get_active_workspace();
for (let i = 0; i < windows.length; i++) {
let w = windows[i];
if (w.get_workspace() == current_workspace)
w.minimize();
}
} else {
this.app.activate(-1);
}
}
Main.overview.hide();
}
});
Signals.addSignalMethods(DockIcon.prototype);
const DockIconMenu = new Lang.Class({
Name: 'Dock.DockIconMenu',
Extends: PopupMenu.PopupMenu,
_init: function(source) {
let side;
switch (source._settings.get_enum(DOCK_POSITION_KEY)) {
case PositionMode.LEFT:
side = St.Side.LEFT;
break;
case PositionMode.RIGHT:
default:
side = St.Side.RIGHT;
}
this.parent(source.actor, 0.5, side);
this._source = source;
this.connect('activate', Lang.bind(this, this._onActivate));
this.actor.add_style_class_name('dock-menu');
// Chain our visibility and lifecycle to that of the source
source.actor.connect('notify::mapped', Lang.bind(this, function () {
if (!source.actor.mapped)
this.close();
}));
source.actor.connect('destroy', Lang.bind(this, function () { this.destroy(); }));
Main.layoutManager.addChrome(this.actor);
},
redisplay: function() {
this.removeAll();
let windows = this._source.app.get_windows();
// Display the app windows menu items and the separator between windows
// of the current desktop and other windows.
let activeWorkspace = global.screen.get_active_workspace();
let separatorShown = windows.length > 0 && windows[0].get_workspace() != activeWorkspace;
for (let i = 0; i < windows.length; i++) {
if (!separatorShown && windows[i].get_workspace() != activeWorkspace) {
this._appendSeparator();
separatorShown = true;
}
let item = this._appendMenuItem(windows[i].title);
item._window = windows[i];
}
if (windows.length > 0)
this._appendSeparator();
let isFavorite = AppFavorites.getAppFavorites().isFavorite(this._source.app.get_id());
this._newWindowMenuItem = windows.length > 0 ? this._appendMenuItem(_("New Window")) : null;
this._quitAppMenuItem = windows.length >0 ? this._appendMenuItem(_("Quit Application")) : null;
if (windows.length > 0)
this._appendSeparator();
this._toggleFavoriteMenuItem = this._appendMenuItem(isFavorite ?
_("Remove from Favorites")
: _("Add to Favorites"));
this._highlightedItem = null;
},
_appendSeparator: function () {
let separator = new PopupMenu.PopupSeparatorMenuItem();
this.addMenuItem(separator);
},
_appendMenuItem: function(labelText) {
// FIXME: app-well-menu-item style
let item = new PopupMenu.PopupMenuItem(labelText);
this.addMenuItem(item);
return item;
},
popup: function(activatingButton) {
this._redisplay();
this.open();
},
_onActivate: function (actor, child) {
if (child._window) {
let metaWindow = child._window;
this.emit('activate-window', metaWindow);
} else if (child == this._newWindowMenuItem) {
let current_workspace = global.screen.get_active_workspace().index();
this._source.app.open_new_window(current_workspace);
this.emit('activate-window', null);
} else if (child == this._quitAppMenuItem) {
this._source.app.request_quit();
} else if (child == this._toggleFavoriteMenuItem) {
let favs = AppFavorites.getAppFavorites();
let isFavorite = favs.isFavorite(this._source.app.get_id());
if (isFavorite)
favs.removeFavorite(this._source.app.get_id());
else
favs.addFavorite(this._source.app.get_id());
}
this.close();
}
});
function init() {
Convenience.initTranslations();
}
let dock;
function enable() {
dock = new Dock();
}
function disable() {
dock.destroy();
dock = null;
}
|
BastienDurel/gnome-shell-extensions-bd
|
extensions/dock/extension.js
|
JavaScript
|
gpl-2.0
| 34,430
|
/* This file is part of the KDE libraries
Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef __ktexteditor_editinterface_h__
#define __ktexteditor_editinterface_h__
#include <qstring.h>
#include <kdelibs_export.h>
namespace KTextEditor {
/**
* This is the main interface for accessing and modifying
* text of the Document class.
*/
class KTEXTEDITOR_EXPORT EditInterface {
friend class PrivateEditInterface;
public:
EditInterface();
virtual ~EditInterface();
uint editInterfaceNumber() const;
protected:
void setEditInterfaceDCOPSuffix(const QCString &suffix);
public:
/**
* slots !!!
*/
/**
* @return the complete document as a single QString
*/
virtual QString text() const = 0;
/**
* @return a QString
*/
virtual QString text(uint startLine, uint startCol, uint endLine, uint endCol) const = 0;
/**
* @return All the text from the requested line.
*/
virtual QString textLine(uint line) const = 0;
/**
* @return The current number of lines in the document
*/
virtual uint numLines() const = 0;
/**
* @return the number of characters in the document
*/
virtual uint length() const = 0;
/**
* @return the number of characters in the line (-1 if no line "line")
*/
virtual int lineLength(uint line) const = 0;
/**
* Set the given text into the view.
* Warning: This will overwrite any data currently held in this view.
*/
virtual bool setText(const QString &text) = 0;
/**
* clears the document
* Warning: This will overwrite any data currently held in this view.
*/
virtual bool clear() = 0;
/**
* Inserts text at line "line", column "col"
* returns true if success
* Use insertText(numLines(), ...) to append text at end of document
*/
virtual bool insertText(uint line, uint col, const QString &text) = 0;
/**
* remove text at line "line", column "col"
* returns true if success
*/
virtual bool removeText(uint startLine, uint startCol, uint endLine, uint endCol) = 0;
/**
* Insert line(s) at the given line number.
* Use insertLine(numLines(), text) to append line at end of document
*/
virtual bool insertLine(uint line, const QString &text) = 0;
/**
* Remove line(s) at the given line number.
*/
virtual bool removeLine(uint line) = 0;
/**
* signals !!!
*/
public:
virtual void textChanged() = 0;
virtual void
charactersInteractivelyInserted(int, int,
const QString &) = 0; // line, col, characters if you don't support this, don't create a signal, just overload it.
/**
* only for the interface itself - REAL PRIVATE
*/
private:
class PrivateEditInterface *d;
static uint globalEditInterfaceNumber;
uint myEditInterfaceNumber;
};
KTEXTEDITOR_EXPORT EditInterface *editInterface(class Document *doc);
}
#endif
|
serghei/kde3-kdelibs
|
interfaces/ktexteditor/editinterface.h
|
C
|
gpl-2.0
| 3,702
|
<!DOCTYPE html>
<html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-US">
<title>My Family Tree - Peters, Rose</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">My Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
<li><a href="../../../addressbook.html" title="Address Book">Address Book</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>Peters, Rose<sup><small> <a href="#sref1">1</a></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
Peters, Rose
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I0753</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">female</td>
</tr>
<tr>
<td class="ColumnAttribute">Age at Death</td>
<td class="ColumnValue">87 years</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Birth
</td>
<td class="ColumnDate">1608</td>
<td class="ColumnPlace">
<a href="../../../plc/v/w/JF3KQCQTREIXBOPWV.html" title="Hilo, HI, USA">
Hilo, HI, USA
</a>
</td>
<td class="ColumnDescription">
Birth of Peters, Rose
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
Death
</td>
<td class="ColumnDate">1695</td>
<td class="ColumnPlace">
<a href="../../../plc/u/a/QD8KQCBBBZ5NYKIVAU.html" title="Florence, Lauderdale, AL, USA">
Florence, Lauderdale, AL, USA
</a>
</td>
<td class="ColumnDescription">
Death of Peters, Rose
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
Burial
</td>
<td class="ColumnDate"> </td>
<td class="ColumnPlace">
<a href="../../../plc/t/y/SQ7KQCCJJW8KE175YT.html" title="Dunn, NC, USA">
Dunn, NC, USA
</a>
</td>
<td class="ColumnDescription">
Burial of Peters, Rose
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/t/t/9EAKQCRLJ4HZ6I37TT.html">Peters, George Sr.<span class="grampsid"> [I0851]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Mother</td>
<td class="ColumnValue">
<a href="../../../ppl/m/g/BFAKQC7HD5G3UTIXGM.html">Ramsey, Joan<span class="grampsid"> [I0852]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/y/f/9D8KQCG5XB5D7J26FY.html">Peters, Rose<span class="grampsid"> [I0753]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="../../../fam/i/n/ZK3KQCS5KNNIOOMYNI.html" title="Family of Grenier, Joseph and Peters, Rose">Family of Grenier, Joseph and Peters, Rose<span class="grampsid"> [F0223]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Husband</td>
<td class="ColumnValue">
<a href="../../../ppl/q/v/4Q7KQCDUQYRHS71UVQ.html">Grenier, Joseph<span class="grampsid"> [I0752]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Marriage
</td>
<td class="ColumnDate">1628</td>
<td class="ColumnPlace">
<a href="../../../plc/u/t/FMALQCV1Q0QGJ3U6TU.html" title="Minneapolis, MN, USA">
Minneapolis, MN, USA
</a>
</td>
<td class="ColumnDescription">
Marriage of Grenier, Joseph and Peters, Rose
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Children</td>
<td class="ColumnValue">
<ol>
<li>
<a href="../../../ppl/l/2/DK3KQCVPMBV5MM9U2L.html">Grenier, Mary<span class="grampsid"> [I0528]</span></a>
</li>
</ol>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="familymap">
<h4>Family Map</h4>
<a class="familymap" href="../../../maps/y/f/9D8KQCG5XB5D7J26FY.html" title="Family Map">Family Map</a>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/t/t/9EAKQCRLJ4HZ6I37TT.html">Peters, George Sr.<span class="grampsid"> [I0851]</span></a>
<ol>
<li class="spouse">
<a href="../../../ppl/m/g/BFAKQC7HD5G3UTIXGM.html">Ramsey, Joan<span class="grampsid"> [I0852]</span></a>
<ol>
<li class="thisperson">
Peters, Rose
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/q/v/4Q7KQCDUQYRHS71UVQ.html">Grenier, Joseph<span class="grampsid"> [I0752]</span></a>
<ol>
<li>
<a href="../../../ppl/l/2/DK3KQCVPMBV5MM9U2L.html">Grenier, Mary<span class="grampsid"> [I0528]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg female AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/y/f/9D8KQCG5XB5D7J26FY.html">
Peters, Rose
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/t/t/9EAKQCRLJ4HZ6I37TT.html">
Peters, George Sr.
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 151px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 156px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 44px; left: 386px;">
<a class="noThumb" href="../../../ppl/m/3/JDAKQCGMZ5WI4JWV3M.html">
Peters, John
</a>
</div>
<div class="shadow" style="top: 49px; left: 390px;"></div>
<div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div>
<div class="boxbg female AncCol1" style="top: 419px; left: 196px;">
<a class="noThumb" href="../../../ppl/m/g/BFAKQC7HD5G3UTIXGM.html">
Ramsey, Joan
</a>
</div>
<div class="shadow" style="top: 424px; left: 200px;"></div>
<div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1">
Import from test2.ged
<span class="grampsid"> [S0003]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25<br />Created for <a href="../../../ppl/h/o/GNUJQCL9MD64AM56OH.html">Garner von Zieliński, Lewis Anderson Sr</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
belissent/testing-example-reports
|
gramps42/gramps/example_NAVWEB1/ppl/y/f/9D8KQCG5XB5D7J26FY.html
|
HTML
|
gpl-2.0
| 11,781
|
/*
* linux/fs/exec.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* #!-checking implemented by tytso.
*/
/*
* Demand-loading implemented 01.12.91 - no need to read anything but
* the header into memory. The inode of the executable is put into
* "current->executable", and page faults do the actual loading. Clean.
*
* Once more I can proudly say that linux stood up to being changed: it
* was less than 2 hours work to get demand-loading completely implemented.
*
* Demand loading changed July 1993 by Eric Youngdale. Use mmap instead,
* current->executable is only used by the procfs. This allows a dispatch
* table to check for several different types of binary formats. We keep
* trying until we recognize the file or we run out of supported binary
* formats.
*/
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/mm.h>
#include <linux/vmacache.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/swap.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/perf_event.h>
#include <linux/highmem.h>
#include <linux/spinlock.h>
#include <linux/key.h>
#include <linux/personality.h>
#include <linux/binfmts.h>
#include <linux/utsname.h>
#include <linux/pid_namespace.h>
#include <linux/module.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/audit.h>
#include <linux/tracehook.h>
#include <linux/kmod.h>
#include <linux/fsnotify.h>
#include <linux/fs_struct.h>
#include <linux/pipe_fs_i.h>
#include <linux/oom.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/tlb.h>
#include <trace/events/task.h>
#include "internal.h"
#include <trace/events/sched.h>
int core_uses_pid;
char core_pattern[CORENAME_MAX_SIZE] = "core";
unsigned int core_pipe_limit;
int suid_dumpable = 0;
struct core_name {
char *corename;
int used, size;
};
static atomic_t call_count = ATOMIC_INIT(1);
/* The maximal length of core_pattern is also specified in sysctl.c */
static LIST_HEAD(formats);
static DEFINE_RWLOCK(binfmt_lock);
void __register_binfmt(struct linux_binfmt * fmt, int insert)
{
BUG_ON(!fmt);
write_lock(&binfmt_lock);
insert ? list_add(&fmt->lh, &formats) :
list_add_tail(&fmt->lh, &formats);
write_unlock(&binfmt_lock);
}
EXPORT_SYMBOL(__register_binfmt);
void unregister_binfmt(struct linux_binfmt * fmt)
{
write_lock(&binfmt_lock);
list_del(&fmt->lh);
write_unlock(&binfmt_lock);
}
EXPORT_SYMBOL(unregister_binfmt);
static inline void put_binfmt(struct linux_binfmt * fmt)
{
module_put(fmt->module);
}
/*
* Note that a shared library must be both readable and executable due to
* security reasons.
*
* Also note that we take the address to load from from the file itself.
*/
SYSCALL_DEFINE1(uselib, const char __user *, library)
{
struct file *file;
char *tmp = getname(library);
int error = PTR_ERR(tmp);
static const struct open_flags uselib_flags = {
.open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
.acc_mode = MAY_READ | MAY_EXEC | MAY_OPEN,
.intent = LOOKUP_OPEN
};
if (IS_ERR(tmp))
goto out;
file = do_filp_open(AT_FDCWD, tmp, &uselib_flags, LOOKUP_FOLLOW);
putname(tmp);
error = PTR_ERR(file);
if (IS_ERR(file))
goto out;
error = -EINVAL;
if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
goto exit;
error = -EACCES;
if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
goto exit;
fsnotify_open(file);
error = -ENOEXEC;
if(file->f_op) {
struct linux_binfmt * fmt;
read_lock(&binfmt_lock);
list_for_each_entry(fmt, &formats, lh) {
if (!fmt->load_shlib)
continue;
if (!try_module_get(fmt->module))
continue;
read_unlock(&binfmt_lock);
error = fmt->load_shlib(file);
read_lock(&binfmt_lock);
put_binfmt(fmt);
if (error != -ENOEXEC)
break;
}
read_unlock(&binfmt_lock);
}
exit:
fput(file);
out:
return error;
}
#ifdef CONFIG_MMU
/*
* The nascent bprm->mm is not visible until exec_mmap() but it can
* use a lot of memory, account these pages in current->mm temporary
* for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we
* change the counter back via acct_arg_size(0).
*/
static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
{
struct mm_struct *mm = current->mm;
long diff = (long)(pages - bprm->vma_pages);
if (!mm || !diff)
return;
bprm->vma_pages = pages;
add_mm_counter(mm, MM_ANONPAGES, diff);
}
static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
int write)
{
struct page *page;
int ret;
#ifdef CONFIG_STACK_GROWSUP
if (write) {
ret = expand_downwards(bprm->vma, pos);
if (ret < 0)
return NULL;
}
#endif
ret = get_user_pages(current, bprm->mm, pos,
1, write, 1, &page, NULL);
if (ret <= 0)
return NULL;
if (write) {
unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
struct rlimit *rlim;
acct_arg_size(bprm, size / PAGE_SIZE);
/*
* We've historically supported up to 32 pages (ARG_MAX)
* of argument strings even with small stacks
*/
if (size <= ARG_MAX)
return page;
/*
* Limit to 1/4-th the stack size for the argv+env strings.
* This ensures that:
* - the remaining binfmt code will not run out of stack space,
* - the program will have a reasonable amount of stack left
* to work from.
*/
rlim = current->signal->rlim;
if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur) / 4) {
put_page(page);
return NULL;
}
}
return page;
}
static void put_arg_page(struct page *page)
{
put_page(page);
}
static void free_arg_page(struct linux_binprm *bprm, int i)
{
}
static void free_arg_pages(struct linux_binprm *bprm)
{
}
static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
struct page *page)
{
flush_cache_page(bprm->vma, pos, page_to_pfn(page));
}
static int __bprm_mm_init(struct linux_binprm *bprm)
{
int err;
struct vm_area_struct *vma = NULL;
struct mm_struct *mm = bprm->mm;
bprm->vma = vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (!vma)
return -ENOMEM;
down_write(&mm->mmap_sem);
vma->vm_mm = mm;
/*
* Place the stack at the largest stack address the architecture
* supports. Later, we'll move this to an appropriate place. We don't
* use STACK_TOP because that can depend on attributes which aren't
* configured yet.
*/
BUILD_BUG_ON(VM_STACK_FLAGS & VM_STACK_INCOMPLETE_SETUP);
vma->vm_end = STACK_TOP_MAX;
vma->vm_start = vma->vm_end - PAGE_SIZE;
vma->vm_flags = VM_STACK_FLAGS | VM_STACK_INCOMPLETE_SETUP;
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
INIT_LIST_HEAD(&vma->anon_vma_chain);
err = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
if (err)
goto err;
err = insert_vm_struct(mm, vma);
if (err)
goto err;
mm->stack_vm = mm->total_vm = 1;
up_write(&mm->mmap_sem);
bprm->p = vma->vm_end - sizeof(void *);
return 0;
err:
up_write(&mm->mmap_sem);
bprm->vma = NULL;
kmem_cache_free(vm_area_cachep, vma);
return err;
}
static bool valid_arg_len(struct linux_binprm *bprm, long len)
{
return len <= MAX_ARG_STRLEN;
}
#else
static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages)
{
}
static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
int write)
{
struct page *page;
page = bprm->page[pos / PAGE_SIZE];
if (!page && write) {
page = alloc_page(GFP_HIGHUSER|__GFP_ZERO);
if (!page)
return NULL;
bprm->page[pos / PAGE_SIZE] = page;
}
return page;
}
static void put_arg_page(struct page *page)
{
}
static void free_arg_page(struct linux_binprm *bprm, int i)
{
if (bprm->page[i]) {
__free_page(bprm->page[i]);
bprm->page[i] = NULL;
}
}
static void free_arg_pages(struct linux_binprm *bprm)
{
int i;
for (i = 0; i < MAX_ARG_PAGES; i++)
free_arg_page(bprm, i);
}
static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos,
struct page *page)
{
}
static int __bprm_mm_init(struct linux_binprm *bprm)
{
bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *);
return 0;
}
static bool valid_arg_len(struct linux_binprm *bprm, long len)
{
return len <= bprm->p;
}
#endif /* CONFIG_MMU */
/*
* Create a new mm_struct and populate it with a temporary stack
* vm_area_struct. We don't have enough context at this point to set the stack
* flags, permissions, and offset, so we use temporary values. We'll update
* them later in setup_arg_pages().
*/
int bprm_mm_init(struct linux_binprm *bprm)
{
int err;
struct mm_struct *mm = NULL;
bprm->mm = mm = mm_alloc();
err = -ENOMEM;
if (!mm)
goto err;
err = init_new_context(current, mm);
if (err)
goto err;
err = __bprm_mm_init(bprm);
if (err)
goto err;
return 0;
err:
if (mm) {
bprm->mm = NULL;
mmdrop(mm);
}
return err;
}
struct user_arg_ptr {
#ifdef CONFIG_COMPAT
bool is_compat;
#endif
union {
const char __user *const __user *native;
#ifdef CONFIG_COMPAT
compat_uptr_t __user *compat;
#endif
} ptr;
};
static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr)
{
const char __user *native;
#ifdef CONFIG_COMPAT
if (unlikely(argv.is_compat)) {
compat_uptr_t compat;
if (get_user(compat, argv.ptr.compat + nr))
return ERR_PTR(-EFAULT);
return compat_ptr(compat);
}
#endif
if (get_user(native, argv.ptr.native + nr))
return ERR_PTR(-EFAULT);
return native;
}
/*
* count() counts the number of strings in array ARGV.
*/
static int count(struct user_arg_ptr argv, int max)
{
int i = 0;
if (argv.ptr.native != NULL) {
for (;;) {
const char __user *p = get_user_arg_ptr(argv, i);
if (!p)
break;
if (IS_ERR(p))
return -EFAULT;
if (i++ >= max)
return -E2BIG;
if (fatal_signal_pending(current))
return -ERESTARTNOHAND;
cond_resched();
}
}
return i;
}
/*
* 'copy_strings()' copies argument/environment strings from the old
* processes's memory to the new process's stack. The call to get_user_pages()
* ensures the destination page is created and not swapped out.
*/
static int copy_strings(int argc, struct user_arg_ptr argv,
struct linux_binprm *bprm)
{
struct page *kmapped_page = NULL;
char *kaddr = NULL;
unsigned long kpos = 0;
int ret;
while (argc-- > 0) {
const char __user *str;
int len;
unsigned long pos;
ret = -EFAULT;
str = get_user_arg_ptr(argv, argc);
if (IS_ERR(str))
goto out;
len = strnlen_user(str, MAX_ARG_STRLEN);
if (!len)
goto out;
ret = -E2BIG;
if (!valid_arg_len(bprm, len))
goto out;
/* We're going to work our way backwords. */
pos = bprm->p;
str += len;
bprm->p -= len;
while (len > 0) {
int offset, bytes_to_copy;
if (fatal_signal_pending(current)) {
ret = -ERESTARTNOHAND;
goto out;
}
cond_resched();
offset = pos % PAGE_SIZE;
if (offset == 0)
offset = PAGE_SIZE;
bytes_to_copy = offset;
if (bytes_to_copy > len)
bytes_to_copy = len;
offset -= bytes_to_copy;
pos -= bytes_to_copy;
str -= bytes_to_copy;
len -= bytes_to_copy;
if (!kmapped_page || kpos != (pos & PAGE_MASK)) {
struct page *page;
page = get_arg_page(bprm, pos, 1);
if (!page) {
ret = -E2BIG;
goto out;
}
if (kmapped_page) {
flush_kernel_dcache_page(kmapped_page);
kunmap(kmapped_page);
put_arg_page(kmapped_page);
}
kmapped_page = page;
kaddr = kmap(kmapped_page);
kpos = pos & PAGE_MASK;
flush_arg_page(bprm, kpos, kmapped_page);
}
if (copy_from_user(kaddr+offset, str, bytes_to_copy)) {
ret = -EFAULT;
goto out;
}
}
}
ret = 0;
out:
if (kmapped_page) {
flush_kernel_dcache_page(kmapped_page);
kunmap(kmapped_page);
put_arg_page(kmapped_page);
}
return ret;
}
/*
* Like copy_strings, but get argv and its values from kernel memory.
*/
int copy_strings_kernel(int argc, const char *const *__argv,
struct linux_binprm *bprm)
{
int r;
mm_segment_t oldfs = get_fs();
struct user_arg_ptr argv = {
.ptr.native = (const char __user *const __user *)__argv,
};
set_fs(KERNEL_DS);
r = copy_strings(argc, argv, bprm);
set_fs(oldfs);
return r;
}
EXPORT_SYMBOL(copy_strings_kernel);
#ifdef CONFIG_MMU
/*
* During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once
* the binfmt code determines where the new stack should reside, we shift it to
* its final location. The process proceeds as follows:
*
* 1) Use shift to calculate the new vma endpoints.
* 2) Extend vma to cover both the old and new ranges. This ensures the
* arguments passed to subsequent functions are consistent.
* 3) Move vma's page tables to the new range.
* 4) Free up any cleared pgd range.
* 5) Shrink the vma to cover only the new range.
*/
static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long old_start = vma->vm_start;
unsigned long old_end = vma->vm_end;
unsigned long length = old_end - old_start;
unsigned long new_start = old_start - shift;
unsigned long new_end = old_end - shift;
struct mmu_gather tlb;
BUG_ON(new_start > new_end);
/*
* ensure there are no vmas between where we want to go
* and where we are
*/
if (vma != find_vma(mm, new_start))
return -EFAULT;
/*
* cover the whole range: [new_start, old_end)
*/
if (vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL))
return -ENOMEM;
/*
* move the page tables downwards, on failure we rely on
* process cleanup to remove whatever mess we made.
*/
if (length != move_page_tables(vma, old_start,
vma, new_start, length))
return -ENOMEM;
lru_add_drain();
tlb_gather_mmu(&tlb, mm, 0);
if (new_end > old_start) {
/*
* when the old and new regions overlap clear from new_end.
*/
free_pgd_range(&tlb, new_end, old_end, new_end,
vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING);
} else {
/*
* otherwise, clean from old_start; this is done to not touch
* the address space in [new_end, old_start) some architectures
* have constraints on va-space that make this illegal (IA64) -
* for the others its just a little faster.
*/
free_pgd_range(&tlb, old_start, old_end, new_end,
vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING);
}
tlb_finish_mmu(&tlb, new_end, old_end);
/*
* Shrink the vma to just the new range. Always succeeds.
*/
vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL);
return 0;
}
/*
* Finalizes the stack vm_area_struct. The flags and permissions are updated,
* the stack is optionally relocated, and some extra space is added.
*/
int setup_arg_pages(struct linux_binprm *bprm,
unsigned long stack_top,
int executable_stack)
{
unsigned long ret;
unsigned long stack_shift;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = bprm->vma;
struct vm_area_struct *prev = NULL;
unsigned long vm_flags;
unsigned long stack_base;
unsigned long stack_size;
unsigned long stack_expand;
unsigned long rlim_stack;
#ifdef CONFIG_STACK_GROWSUP
/* Limit stack size to 1GB */
stack_base = rlimit_max(RLIMIT_STACK);
if (stack_base > (1 << 30))
stack_base = 1 << 30;
/* Make sure we didn't let the argument array grow too large. */
if (vma->vm_end - vma->vm_start > stack_base)
return -ENOMEM;
stack_base = PAGE_ALIGN(stack_top - stack_base);
stack_shift = vma->vm_start - stack_base;
mm->arg_start = bprm->p - stack_shift;
bprm->p = vma->vm_end - stack_shift;
#else
stack_top = arch_align_stack(stack_top);
stack_top = PAGE_ALIGN(stack_top);
if (unlikely(stack_top < mmap_min_addr) ||
unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr))
return -ENOMEM;
stack_shift = vma->vm_end - stack_top;
bprm->p -= stack_shift;
mm->arg_start = bprm->p;
#endif
if (bprm->loader)
bprm->loader -= stack_shift;
bprm->exec -= stack_shift;
down_write(&mm->mmap_sem);
vm_flags = VM_STACK_FLAGS;
/*
* Adjust stack execute permissions; explicitly enable for
* EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone
* (arch default) otherwise.
*/
if (unlikely(executable_stack == EXSTACK_ENABLE_X))
vm_flags |= VM_EXEC;
else if (executable_stack == EXSTACK_DISABLE_X)
vm_flags &= ~VM_EXEC;
vm_flags |= mm->def_flags;
vm_flags |= VM_STACK_INCOMPLETE_SETUP;
ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end,
vm_flags);
if (ret)
goto out_unlock;
BUG_ON(prev != vma);
/* Move stack pages down in memory. */
if (stack_shift) {
ret = shift_arg_pages(vma, stack_shift);
if (ret)
goto out_unlock;
}
/* mprotect_fixup is overkill to remove the temporary stack flags */
vma->vm_flags &= ~VM_STACK_INCOMPLETE_SETUP;
stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */
stack_size = vma->vm_end - vma->vm_start;
/*
* Align this down to a page boundary as expand_stack
* will align it up.
*/
rlim_stack = rlimit(RLIMIT_STACK) & PAGE_MASK;
#ifdef CONFIG_STACK_GROWSUP
if (stack_size + stack_expand > rlim_stack)
stack_base = vma->vm_start + rlim_stack;
else
stack_base = vma->vm_end + stack_expand;
#else
if (stack_size + stack_expand > rlim_stack)
stack_base = vma->vm_end - rlim_stack;
else
stack_base = vma->vm_start - stack_expand;
#endif
current->mm->start_stack = bprm->p;
ret = expand_stack(vma, stack_base);
if (ret)
ret = -EFAULT;
out_unlock:
up_write(&mm->mmap_sem);
return ret;
}
EXPORT_SYMBOL(setup_arg_pages);
#endif /* CONFIG_MMU */
struct file *open_exec(const char *name)
{
struct file *file;
int err;
static const struct open_flags open_exec_flags = {
.open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC,
.acc_mode = MAY_EXEC | MAY_OPEN,
.intent = LOOKUP_OPEN
};
file = do_filp_open(AT_FDCWD, name, &open_exec_flags, LOOKUP_FOLLOW);
if (IS_ERR(file))
goto out;
err = -EACCES;
if (!S_ISREG(file->f_path.dentry->d_inode->i_mode))
goto exit;
if (file->f_path.mnt->mnt_flags & MNT_NOEXEC)
goto exit;
fsnotify_open(file);
err = deny_write_access(file);
if (err)
goto exit;
out:
return file;
exit:
fput(file);
return ERR_PTR(err);
}
EXPORT_SYMBOL(open_exec);
int kernel_read(struct file *file, loff_t offset,
char *addr, unsigned long count)
{
mm_segment_t old_fs;
loff_t pos = offset;
int result;
old_fs = get_fs();
set_fs(get_ds());
/* The cast to a user pointer is valid due to the set_fs() */
result = vfs_read(file, (void __user *)addr, count, &pos);
set_fs(old_fs);
return result;
}
EXPORT_SYMBOL(kernel_read);
static int exec_mmap(struct mm_struct *mm)
{
struct task_struct *tsk;
struct mm_struct *old_mm, *active_mm;
/* Notify parent that we're no longer interested in the old VM */
tsk = current;
old_mm = current->mm;
mm_release(tsk, old_mm);
if (old_mm) {
sync_mm_rss(old_mm);
/*
* Make sure that if there is a core dump in progress
* for the old mm, we get out and die instead of going
* through with the exec. We must hold mmap_sem around
* checking core_state and changing tsk->mm.
*/
down_read(&old_mm->mmap_sem);
if (unlikely(old_mm->core_state)) {
up_read(&old_mm->mmap_sem);
return -EINTR;
}
}
task_lock(tsk);
active_mm = tsk->active_mm;
tsk->mm = mm;
tsk->active_mm = mm;
activate_mm(active_mm, mm);
tsk->mm->vmacache_seqnum = 0;
vmacache_flush(tsk);
task_unlock(tsk);
arch_pick_mmap_layout(mm);
if (old_mm) {
up_read(&old_mm->mmap_sem);
BUG_ON(active_mm != old_mm);
setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm);
mm_update_next_owner(old_mm);
mmput(old_mm);
return 0;
}
mmdrop(active_mm);
return 0;
}
/*
* This function makes sure the current process has its own signal table,
* so that flush_signal_handlers can later reset the handlers without
* disturbing other processes. (Other processes might share the signal
* table via the CLONE_SIGHAND option to clone().)
*/
static int de_thread(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
struct sighand_struct *oldsighand = tsk->sighand;
spinlock_t *lock = &oldsighand->siglock;
if (thread_group_empty(tsk))
goto no_thread_group;
/*
* Kill all other threads in the thread group.
*/
spin_lock_irq(lock);
if (signal_group_exit(sig)) {
/*
* Another group action in progress, just
* return so that the signal is processed.
*/
spin_unlock_irq(lock);
return -EAGAIN;
}
sig->group_exit_task = tsk;
sig->notify_count = zap_other_threads(tsk);
if (!thread_group_leader(tsk))
sig->notify_count--;
while (sig->notify_count) {
__set_current_state(TASK_UNINTERRUPTIBLE);
spin_unlock_irq(lock);
schedule();
spin_lock_irq(lock);
}
spin_unlock_irq(lock);
/*
* At this point all other threads have exited, all we have to
* do is to wait for the thread group leader to become inactive,
* and to assume its PID:
*/
if (!thread_group_leader(tsk)) {
struct task_struct *leader = tsk->group_leader;
sig->notify_count = -1; /* for exit_notify() */
for (;;) {
threadgroup_change_begin(tsk);
write_lock_irq(&tasklist_lock);
if (likely(leader->exit_state))
break;
__set_current_state(TASK_UNINTERRUPTIBLE);
write_unlock_irq(&tasklist_lock);
threadgroup_change_end(tsk);
schedule();
}
/*
* The only record we have of the real-time age of a
* process, regardless of execs it's done, is start_time.
* All the past CPU time is accumulated in signal_struct
* from sister threads now dead. But in this non-leader
* exec, nothing survives from the original leader thread,
* whose birth marks the true age of this process now.
* When we take on its identity by switching to its PID, we
* also take its birthdate (always earlier than our own).
*/
tsk->start_time = leader->start_time;
BUG_ON(!same_thread_group(leader, tsk));
BUG_ON(has_group_leader_pid(tsk));
/*
* An exec() starts a new thread group with the
* TGID of the previous thread group. Rehash the
* two threads with a switched PID, and release
* the former thread group leader:
*/
/* Become a process group leader with the old leader's pid.
* The old leader becomes a thread of the this thread group.
* Note: The old leader also uses this pid until release_task
* is called. Odd but simple and correct.
*/
detach_pid(tsk, PIDTYPE_PID);
tsk->pid = leader->pid;
attach_pid(tsk, PIDTYPE_PID, task_pid(leader));
transfer_pid(leader, tsk, PIDTYPE_PGID);
transfer_pid(leader, tsk, PIDTYPE_SID);
list_replace_rcu(&leader->tasks, &tsk->tasks);
list_replace_init(&leader->sibling, &tsk->sibling);
tsk->group_leader = tsk;
leader->group_leader = tsk;
tsk->exit_signal = SIGCHLD;
leader->exit_signal = -1;
BUG_ON(leader->exit_state != EXIT_ZOMBIE);
leader->exit_state = EXIT_DEAD;
/*
* We are going to release_task()->ptrace_unlink() silently,
* the tracer can sleep in do_wait(). EXIT_DEAD guarantees
* the tracer wont't block again waiting for this thread.
*/
if (unlikely(leader->ptrace))
__wake_up_parent(leader, leader->parent);
write_unlock_irq(&tasklist_lock);
threadgroup_change_end(tsk);
release_task(leader);
}
sig->group_exit_task = NULL;
sig->notify_count = 0;
no_thread_group:
/* we have changed execution domain */
tsk->exit_signal = SIGCHLD;
exit_itimers(sig);
flush_itimer_signals();
if (atomic_read(&oldsighand->count) != 1) {
struct sighand_struct *newsighand;
/*
* This ->sighand is shared with the CLONE_SIGHAND
* but not CLONE_THREAD task, switch to the new one.
*/
newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
if (!newsighand)
return -ENOMEM;
atomic_set(&newsighand->count, 1);
memcpy(newsighand->action, oldsighand->action,
sizeof(newsighand->action));
write_lock_irq(&tasklist_lock);
spin_lock(&oldsighand->siglock);
rcu_assign_pointer(tsk->sighand, newsighand);
spin_unlock(&oldsighand->siglock);
write_unlock_irq(&tasklist_lock);
__cleanup_sighand(oldsighand);
}
BUG_ON(!thread_group_leader(tsk));
return 0;
}
/*
* These functions flushes out all traces of the currently running executable
* so that a new one can be started
*/
static void flush_old_files(struct files_struct * files)
{
long j = -1;
struct fdtable *fdt;
spin_lock(&files->file_lock);
for (;;) {
unsigned long set, i;
j++;
i = j * BITS_PER_LONG;
fdt = files_fdtable(files);
if (i >= fdt->max_fds)
break;
set = fdt->close_on_exec[j];
if (!set)
continue;
fdt->close_on_exec[j] = 0;
spin_unlock(&files->file_lock);
for ( ; set ; i++,set >>= 1) {
if (set & 1) {
sys_close(i);
}
}
spin_lock(&files->file_lock);
}
spin_unlock(&files->file_lock);
}
char *get_task_comm(char *buf, struct task_struct *tsk)
{
/* buf must be at least sizeof(tsk->comm) in size */
task_lock(tsk);
strncpy(buf, tsk->comm, sizeof(tsk->comm));
task_unlock(tsk);
return buf;
}
EXPORT_SYMBOL_GPL(get_task_comm);
void set_task_comm(struct task_struct *tsk, char *buf)
{
task_lock(tsk);
trace_task_rename(tsk, buf);
/*
* Threads may access current->comm without holding
* the task lock, so write the string carefully.
* Readers without a lock may see incomplete new
* names but are safe from non-terminating string reads.
*/
memset(tsk->comm, 0, TASK_COMM_LEN);
wmb();
strlcpy(tsk->comm, buf, sizeof(tsk->comm));
task_unlock(tsk);
perf_event_comm(tsk);
}
static void filename_to_taskname(char *tcomm, const char *fn, unsigned int len)
{
int i, ch;
/* Copies the binary name from after last slash */
for (i = 0; (ch = *(fn++)) != '\0';) {
if (ch == '/')
i = 0; /* overwrite what we wrote */
else
if (i < len - 1)
tcomm[i++] = ch;
}
tcomm[i] = '\0';
}
int flush_old_exec(struct linux_binprm * bprm)
{
int retval;
/*
* Make sure we have a private signal table and that
* we are unassociated from the previous thread group.
*/
retval = de_thread(current);
if (retval)
goto out;
set_mm_exe_file(bprm->mm, bprm->file);
filename_to_taskname(bprm->tcomm, bprm->filename, sizeof(bprm->tcomm));
/*
* Release all of the old mmap stuff
*/
acct_arg_size(bprm, 0);
retval = exec_mmap(bprm->mm);
if (retval)
goto out;
bprm->mm = NULL; /* We're using it now */
set_fs(USER_DS);
current->flags &=
~(PF_RANDOMIZE | PF_FORKNOEXEC | PF_KTHREAD | PF_NOFREEZE);
flush_thread();
current->personality &= ~bprm->per_clear;
return 0;
out:
return retval;
}
EXPORT_SYMBOL(flush_old_exec);
void would_dump(struct linux_binprm *bprm, struct file *file)
{
if (inode_permission(file->f_path.dentry->d_inode, MAY_READ) < 0)
bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP;
}
EXPORT_SYMBOL(would_dump);
void setup_new_exec(struct linux_binprm * bprm)
{
arch_pick_mmap_layout(current->mm);
/* This is the point of no return */
current->sas_ss_sp = current->sas_ss_size = 0;
if (current_euid() == current_uid() && current_egid() == current_gid())
set_dumpable(current->mm, 1);
else
set_dumpable(current->mm, suid_dumpable);
set_task_comm(current, bprm->tcomm);
/* Set the new mm task size. We have to do that late because it may
* depend on TIF_32BIT which is only updated in flush_thread() on
* some architectures like powerpc
*/
current->mm->task_size = TASK_SIZE;
/* install the new credentials */
if (bprm->cred->uid != current_euid() ||
bprm->cred->gid != current_egid()) {
current->pdeath_signal = 0;
} else {
would_dump(bprm, bprm->file);
if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)
set_dumpable(current->mm, suid_dumpable);
}
/* An exec changes our domain. We are no longer part of the thread
group */
current->self_exec_id++;
flush_signal_handlers(current, 0);
flush_old_files(current->files);
}
EXPORT_SYMBOL(setup_new_exec);
/*
* Prepare credentials and lock ->cred_guard_mutex.
* install_exec_creds() commits the new creds and drops the lock.
* Or, if exec fails before, free_bprm() should release ->cred and
* and unlock.
*/
int prepare_bprm_creds(struct linux_binprm *bprm)
{
if (mutex_lock_interruptible(¤t->signal->cred_guard_mutex))
return -ERESTARTNOINTR;
bprm->cred = prepare_exec_creds();
if (likely(bprm->cred))
return 0;
mutex_unlock(¤t->signal->cred_guard_mutex);
return -ENOMEM;
}
void free_bprm(struct linux_binprm *bprm)
{
free_arg_pages(bprm);
if (bprm->cred) {
mutex_unlock(¤t->signal->cred_guard_mutex);
abort_creds(bprm->cred);
}
/* If a binfmt changed the interp, free it. */
if (bprm->interp != bprm->filename)
kfree(bprm->interp);
kfree(bprm);
}
int bprm_change_interp(char *interp, struct linux_binprm *bprm)
{
/* If a binfmt changed the interp, free it first. */
if (bprm->interp != bprm->filename)
kfree(bprm->interp);
bprm->interp = kstrdup(interp, GFP_KERNEL);
if (!bprm->interp)
return -ENOMEM;
return 0;
}
EXPORT_SYMBOL(bprm_change_interp);
/*
* install the new credentials for this executable
*/
void install_exec_creds(struct linux_binprm *bprm)
{
security_bprm_committing_creds(bprm);
commit_creds(bprm->cred);
bprm->cred = NULL;
/*
* Disable monitoring for regular users
* when executing setuid binaries. Must
* wait until new credentials are committed
* by commit_creds() above
*/
if (get_dumpable(current->mm) != SUID_DUMP_USER)
perf_event_exit_task(current);
/*
* cred_guard_mutex must be held at least to this point to prevent
* ptrace_attach() from altering our determination of the task's
* credentials; any time after this it may be unlocked.
*/
security_bprm_committed_creds(bprm);
mutex_unlock(¤t->signal->cred_guard_mutex);
}
EXPORT_SYMBOL(install_exec_creds);
static void bprm_fill_uid(struct linux_binprm *bprm)
{
struct inode *inode;
unsigned int mode;
uid_t uid;
gid_t gid;
/* clear any previous set[ug]id data from a previous binary */
bprm->cred->euid = current_euid();
bprm->cred->egid = current_egid();
if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
return;
inode = bprm->file->f_path.dentry->d_inode;
mode = ACCESS_ONCE(inode->i_mode);
if (!(mode & (S_ISUID|S_ISGID)))
return;
/* Be careful if suid/sgid is set */
mutex_lock(&inode->i_mutex);
/* reload atomically mode/uid/gid now that lock held */
mode = inode->i_mode;
uid = inode->i_uid;
gid = inode->i_gid;
mutex_unlock(&inode->i_mutex);
if (mode & S_ISUID) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->euid = uid;
}
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->egid = gid;
}
}
/*
* determine how safe it is to execute the proposed program
* - the caller must hold ->cred_guard_mutex to protect against
* PTRACE_ATTACH
*/
static int check_unsafe_exec(struct linux_binprm *bprm)
{
struct task_struct *p = current, *t;
unsigned n_fs;
int res = 0;
if (p->ptrace) {
if (p->ptrace & PT_PTRACE_CAP)
bprm->unsafe |= LSM_UNSAFE_PTRACE_CAP;
else
bprm->unsafe |= LSM_UNSAFE_PTRACE;
}
/*
* This isn't strictly necessary, but it makes it harder for LSMs to
* mess up.
*/
if (current->no_new_privs)
bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS;
n_fs = 1;
spin_lock(&p->fs->lock);
rcu_read_lock();
for (t = next_thread(p); t != p; t = next_thread(t)) {
if (t->fs == p->fs)
n_fs++;
}
rcu_read_unlock();
if (p->fs->users > n_fs) {
bprm->unsafe |= LSM_UNSAFE_SHARE;
} else {
res = -EAGAIN;
if (!p->fs->in_exec) {
p->fs->in_exec = 1;
res = 1;
}
}
spin_unlock(&p->fs->lock);
return res;
}
/*
* Fill the binprm structure from the inode.
* Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes
*
* This may be called multiple times for binary chains (scripts for example).
*/
int prepare_binprm(struct linux_binprm *bprm)
{
int retval;
if (bprm->file->f_op == NULL)
return -EACCES;
bprm_fill_uid(bprm);
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
EXPORT_SYMBOL(prepare_binprm);
/*
* Arguments are '\0' separated strings found at the location bprm->p
* points to; chop off the first by relocating brpm->p to right after
* the first '\0' encountered.
*/
int remove_arg_zero(struct linux_binprm *bprm)
{
int ret = 0;
unsigned long offset;
char *kaddr;
struct page *page;
if (!bprm->argc)
return 0;
do {
offset = bprm->p & ~PAGE_MASK;
page = get_arg_page(bprm, bprm->p, 0);
if (!page) {
ret = -EFAULT;
goto out;
}
kaddr = kmap_atomic(page);
for (; offset < PAGE_SIZE && kaddr[offset];
offset++, bprm->p++)
;
kunmap_atomic(kaddr);
put_arg_page(page);
if (offset == PAGE_SIZE)
free_arg_page(bprm, (bprm->p >> PAGE_SHIFT) - 1);
} while (offset == PAGE_SIZE);
bprm->p++;
bprm->argc--;
ret = 0;
out:
return ret;
}
EXPORT_SYMBOL(remove_arg_zero);
/*
* cycle the list of binary formats handler, until one recognizes the image
*/
int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs)
{
unsigned int depth = bprm->recursion_depth;
int try,retval;
struct linux_binfmt *fmt;
pid_t old_pid, old_vpid;
/* This allows 4 levels of binfmt rewrites before failing hard. */
if (depth > 5)
return -ELOOP;
retval = security_bprm_check(bprm);
if (retval)
return retval;
retval = audit_bprm(bprm);
if (retval)
return retval;
/* Need to fetch pid before load_binary changes it */
old_pid = current->pid;
rcu_read_lock();
old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent));
rcu_read_unlock();
retval = -ENOENT;
for (try=0; try<2; try++) {
read_lock(&binfmt_lock);
list_for_each_entry(fmt, &formats, lh) {
int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
if (!fn)
continue;
if (!try_module_get(fmt->module))
continue;
read_unlock(&binfmt_lock);
bprm->recursion_depth = depth + 1;
retval = fn(bprm, regs);
bprm->recursion_depth = depth;
if (retval >= 0) {
if (depth == 0) {
trace_sched_process_exec(current, old_pid, bprm);
ptrace_event(PTRACE_EVENT_EXEC, old_vpid);
}
put_binfmt(fmt);
allow_write_access(bprm->file);
if (bprm->file)
fput(bprm->file);
bprm->file = NULL;
current->did_exec = 1;
proc_exec_connector(current);
return retval;
}
read_lock(&binfmt_lock);
put_binfmt(fmt);
if (retval != -ENOEXEC || bprm->mm == NULL)
break;
if (!bprm->file) {
read_unlock(&binfmt_lock);
return retval;
}
}
read_unlock(&binfmt_lock);
#ifdef CONFIG_MODULES
if (retval != -ENOEXEC || bprm->mm == NULL) {
break;
} else {
#define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
if (printable(bprm->buf[0]) &&
printable(bprm->buf[1]) &&
printable(bprm->buf[2]) &&
printable(bprm->buf[3]))
break; /* -ENOEXEC */
if (try)
break; /* -ENOEXEC */
request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2]));
}
#else
break;
#endif
}
return retval;
}
EXPORT_SYMBOL(search_binary_handler);
/*
* sys_execve() executes a new program.
*/
static int do_execve_common(const char *filename,
struct user_arg_ptr argv,
struct user_arg_ptr envp,
struct pt_regs *regs)
{
struct linux_binprm *bprm;
struct file *file;
struct files_struct *displaced;
bool clear_in_exec;
int retval;
const struct cred *cred = current_cred();
/*
* We move the actual failure in case of RLIMIT_NPROC excess from
* set*uid() to execve() because too many poorly written programs
* don't check setuid() return code. Here we additionally recheck
* whether NPROC limit is still exceeded.
*/
if ((current->flags & PF_NPROC_EXCEEDED) &&
atomic_read(&cred->user->processes) > rlimit(RLIMIT_NPROC)) {
retval = -EAGAIN;
goto out_ret;
}
/* We're below the limit (still or again), so we don't want to make
* further execve() calls fail. */
current->flags &= ~PF_NPROC_EXCEEDED;
retval = unshare_files(&displaced);
if (retval)
goto out_ret;
retval = -ENOMEM;
bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
if (!bprm)
goto out_files;
retval = prepare_bprm_creds(bprm);
if (retval)
goto out_free;
retval = check_unsafe_exec(bprm);
if (retval < 0)
goto out_free;
clear_in_exec = retval;
current->in_execve = 1;
file = open_exec(filename);
retval = PTR_ERR(file);
if (IS_ERR(file))
goto out_unmark;
sched_exec();
bprm->file = file;
bprm->filename = filename;
bprm->interp = filename;
retval = bprm_mm_init(bprm);
if (retval)
goto out_file;
bprm->argc = count(argv, MAX_ARG_STRINGS);
if ((retval = bprm->argc) < 0)
goto out;
bprm->envc = count(envp, MAX_ARG_STRINGS);
if ((retval = bprm->envc) < 0)
goto out;
retval = prepare_binprm(bprm);
if (retval < 0)
goto out;
retval = copy_strings_kernel(1, &bprm->filename, bprm);
if (retval < 0)
goto out;
bprm->exec = bprm->p;
retval = copy_strings(bprm->envc, envp, bprm);
if (retval < 0)
goto out;
retval = copy_strings(bprm->argc, argv, bprm);
if (retval < 0)
goto out;
retval = search_binary_handler(bprm,regs);
if (retval < 0)
goto out;
/* execve succeeded */
current->fs->in_exec = 0;
current->in_execve = 0;
acct_update_integrals(current);
free_bprm(bprm);
if (displaced)
put_files_struct(displaced);
return retval;
out:
if (bprm->mm) {
acct_arg_size(bprm, 0);
mmput(bprm->mm);
}
out_file:
if (bprm->file) {
allow_write_access(bprm->file);
fput(bprm->file);
}
out_unmark:
if (clear_in_exec)
current->fs->in_exec = 0;
current->in_execve = 0;
out_free:
free_bprm(bprm);
out_files:
if (displaced)
reset_files_struct(displaced);
out_ret:
return retval;
}
int do_execve(const char *filename,
const char __user *const __user *__argv,
const char __user *const __user *__envp,
struct pt_regs *regs)
{
struct user_arg_ptr argv = { .ptr.native = __argv };
struct user_arg_ptr envp = { .ptr.native = __envp };
return do_execve_common(filename, argv, envp, regs);
}
#ifdef CONFIG_COMPAT
int compat_do_execve(char *filename,
compat_uptr_t __user *__argv,
compat_uptr_t __user *__envp,
struct pt_regs *regs)
{
struct user_arg_ptr argv = {
.is_compat = true,
.ptr.compat = __argv,
};
struct user_arg_ptr envp = {
.is_compat = true,
.ptr.compat = __envp,
};
return do_execve_common(filename, argv, envp, regs);
}
#endif
void set_binfmt(struct linux_binfmt *new)
{
struct mm_struct *mm = current->mm;
if (mm->binfmt)
module_put(mm->binfmt->module);
mm->binfmt = new;
if (new)
__module_get(new->module);
}
EXPORT_SYMBOL(set_binfmt);
static int expand_corename(struct core_name *cn)
{
char *old_corename = cn->corename;
cn->size = CORENAME_MAX_SIZE * atomic_inc_return(&call_count);
cn->corename = krealloc(old_corename, cn->size, GFP_KERNEL);
if (!cn->corename) {
kfree(old_corename);
return -ENOMEM;
}
return 0;
}
static int cn_printf(struct core_name *cn, const char *fmt, ...)
{
char *cur;
int need;
int ret;
va_list arg;
va_start(arg, fmt);
need = vsnprintf(NULL, 0, fmt, arg);
va_end(arg);
if (likely(need < cn->size - cn->used - 1))
goto out_printf;
ret = expand_corename(cn);
if (ret)
goto expand_fail;
out_printf:
cur = cn->corename + cn->used;
va_start(arg, fmt);
vsnprintf(cur, need + 1, fmt, arg);
va_end(arg);
cn->used += need;
return 0;
expand_fail:
return ret;
}
static void cn_escape(char *str)
{
for (; *str; str++)
if (*str == '/')
*str = '!';
}
static int cn_print_exe_file(struct core_name *cn)
{
struct file *exe_file;
char *pathbuf, *path;
int ret;
exe_file = get_mm_exe_file(current->mm);
if (!exe_file) {
char *commstart = cn->corename + cn->used;
ret = cn_printf(cn, "%s (path unknown)", current->comm);
cn_escape(commstart);
return ret;
}
pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
if (!pathbuf) {
ret = -ENOMEM;
goto put_exe_file;
}
path = d_path(&exe_file->f_path, pathbuf, PATH_MAX);
if (IS_ERR(path)) {
ret = PTR_ERR(path);
goto free_buf;
}
cn_escape(path);
ret = cn_printf(cn, "%s", path);
free_buf:
kfree(pathbuf);
put_exe_file:
fput(exe_file);
return ret;
}
/* format_corename will inspect the pattern parameter, and output a
* name into corename, which must have space for at least
* CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
*/
static int format_corename(struct core_name *cn, long signr)
{
const struct cred *cred = current_cred();
const char *pat_ptr = core_pattern;
int ispipe = (*pat_ptr == '|');
int pid_in_pattern = 0;
int err = 0;
cn->size = CORENAME_MAX_SIZE * atomic_read(&call_count);
cn->corename = kmalloc(cn->size, GFP_KERNEL);
cn->used = 0;
if (!cn->corename)
return -ENOMEM;
/* Repeat as long as we have more pattern to process and more output
space */
while (*pat_ptr) {
if (*pat_ptr != '%') {
if (*pat_ptr == 0)
goto out;
err = cn_printf(cn, "%c", *pat_ptr++);
} else {
switch (*++pat_ptr) {
/* single % at the end, drop that */
case 0:
goto out;
/* Double percent, output one percent */
case '%':
err = cn_printf(cn, "%c", '%');
break;
/* pid */
case 'p':
pid_in_pattern = 1;
err = cn_printf(cn, "%d",
task_tgid_vnr(current));
break;
/* uid */
case 'u':
err = cn_printf(cn, "%d", cred->uid);
break;
/* gid */
case 'g':
err = cn_printf(cn, "%d", cred->gid);
break;
/* signal that caused the coredump */
case 's':
err = cn_printf(cn, "%ld", signr);
break;
/* UNIX time of coredump */
case 't': {
struct timeval tv;
do_gettimeofday(&tv);
err = cn_printf(cn, "%lu", tv.tv_sec);
break;
}
/* hostname */
case 'h': {
char *namestart = cn->corename + cn->used;
down_read(&uts_sem);
err = cn_printf(cn, "%s",
utsname()->nodename);
up_read(&uts_sem);
cn_escape(namestart);
break;
}
/* executable */
case 'e': {
char *commstart = cn->corename + cn->used;
err = cn_printf(cn, "%s", current->comm);
cn_escape(commstart);
break;
}
case 'E':
err = cn_print_exe_file(cn);
break;
/* core limit size */
case 'c':
err = cn_printf(cn, "%lu",
rlimit(RLIMIT_CORE));
break;
default:
break;
}
++pat_ptr;
}
if (err)
return err;
}
/* Backward compatibility with core_uses_pid:
*
* If core_pattern does not include a %p (as is the default)
* and core_uses_pid is set, then .%pid will be appended to
* the filename. Do not do this for piped commands. */
if (!ispipe && !pid_in_pattern && core_uses_pid) {
err = cn_printf(cn, ".%d", task_tgid_vnr(current));
if (err)
return err;
}
out:
return ispipe;
}
static int zap_process(struct task_struct *start, int exit_code)
{
struct task_struct *t;
int nr = 0;
start->signal->flags = SIGNAL_GROUP_EXIT;
start->signal->group_exit_code = exit_code;
start->signal->group_stop_count = 0;
t = start;
do {
task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
if (t != current && t->mm) {
sigaddset(&t->pending.signal, SIGKILL);
signal_wake_up(t, 1);
nr++;
}
} while_each_thread(start, t);
return nr;
}
static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
struct core_state *core_state, int exit_code)
{
struct task_struct *g, *p;
unsigned long flags;
int nr = -EAGAIN;
spin_lock_irq(&tsk->sighand->siglock);
if (!signal_group_exit(tsk->signal)) {
mm->core_state = core_state;
nr = zap_process(tsk, exit_code);
}
spin_unlock_irq(&tsk->sighand->siglock);
if (unlikely(nr < 0))
return nr;
if (atomic_read(&mm->mm_users) == nr + 1)
goto done;
/*
* We should find and kill all tasks which use this mm, and we should
* count them correctly into ->nr_threads. We don't take tasklist
* lock, but this is safe wrt:
*
* fork:
* None of sub-threads can fork after zap_process(leader). All
* processes which were created before this point should be
* visible to zap_threads() because copy_process() adds the new
* process to the tail of init_task.tasks list, and lock/unlock
* of ->siglock provides a memory barrier.
*
* do_exit:
* The caller holds mm->mmap_sem. This means that the task which
* uses this mm can't pass exit_mm(), so it can't exit or clear
* its ->mm.
*
* de_thread:
* It does list_replace_rcu(&leader->tasks, ¤t->tasks),
* we must see either old or new leader, this does not matter.
* However, it can change p->sighand, so lock_task_sighand(p)
* must be used. Since p->mm != NULL and we hold ->mmap_sem
* it can't fail.
*
* Note also that "g" can be the old leader with ->mm == NULL
* and already unhashed and thus removed from ->thread_group.
* This is OK, __unhash_process()->list_del_rcu() does not
* clear the ->next pointer, we will find the new leader via
* next_thread().
*/
rcu_read_lock();
for_each_process(g) {
if (g == tsk->group_leader)
continue;
if (g->flags & PF_KTHREAD)
continue;
p = g;
do {
if (p->mm) {
if (unlikely(p->mm == mm)) {
lock_task_sighand(p, &flags);
nr += zap_process(p, exit_code);
unlock_task_sighand(p, &flags);
}
break;
}
} while_each_thread(g, p);
}
rcu_read_unlock();
done:
atomic_set(&core_state->nr_threads, nr);
return nr;
}
static int coredump_wait(int exit_code, struct core_state *core_state)
{
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
int core_waiters = -EBUSY;
init_completion(&core_state->startup);
core_state->dumper.task = tsk;
core_state->dumper.next = NULL;
down_write(&mm->mmap_sem);
if (!mm->core_state)
core_waiters = zap_threads(tsk, mm, core_state, exit_code);
up_write(&mm->mmap_sem);
if (core_waiters > 0)
wait_for_completion(&core_state->startup);
return core_waiters;
}
static void coredump_finish(struct mm_struct *mm)
{
struct core_thread *curr, *next;
struct task_struct *task;
next = mm->core_state->dumper.next;
while ((curr = next) != NULL) {
next = curr->next;
task = curr->task;
/*
* see exit_mm(), curr->task must not see
* ->task == NULL before we read ->next.
*/
smp_mb();
curr->task = NULL;
wake_up_process(task);
}
mm->core_state = NULL;
}
/*
* set_dumpable converts traditional three-value dumpable to two flags and
* stores them into mm->flags. It modifies lower two bits of mm->flags, but
* these bits are not changed atomically. So get_dumpable can observe the
* intermediate state. To avoid doing unexpected behavior, get get_dumpable
* return either old dumpable or new one by paying attention to the order of
* modifying the bits.
*
* dumpable | mm->flags (binary)
* old new | initial interim final
* ---------+-----------------------
* 0 1 | 00 01 01
* 0 2 | 00 10(*) 11
* 1 0 | 01 00 00
* 1 2 | 01 11 11
* 2 0 | 11 10(*) 00
* 2 1 | 11 11 01
*
* (*) get_dumpable regards interim value of 10 as 11.
*/
void set_dumpable(struct mm_struct *mm, int value)
{
switch (value) {
case 0:
clear_bit(MMF_DUMPABLE, &mm->flags);
smp_wmb();
clear_bit(MMF_DUMP_SECURELY, &mm->flags);
break;
case 1:
set_bit(MMF_DUMPABLE, &mm->flags);
smp_wmb();
clear_bit(MMF_DUMP_SECURELY, &mm->flags);
break;
case 2:
set_bit(MMF_DUMP_SECURELY, &mm->flags);
smp_wmb();
set_bit(MMF_DUMPABLE, &mm->flags);
break;
}
}
static int __get_dumpable(unsigned long mm_flags)
{
int ret;
ret = mm_flags & MMF_DUMPABLE_MASK;
return (ret >= 2) ? 2 : ret;
}
/*
* This returns the actual value of the suid_dumpable flag. For things
* that are using this for checking for privilege transitions, it must
* test against SUID_DUMP_USER rather than treating it as a boolean
* value.
*/
int get_dumpable(struct mm_struct *mm)
{
return __get_dumpable(mm->flags);
}
static void wait_for_dump_helpers(struct file *file)
{
struct pipe_inode_info *pipe;
pipe = file->f_path.dentry->d_inode->i_pipe;
pipe_lock(pipe);
pipe->readers++;
pipe->writers--;
while ((pipe->readers > 1) && (!signal_pending(current))) {
wake_up_interruptible_sync(&pipe->wait);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
pipe_wait(pipe);
}
pipe->readers--;
pipe->writers++;
pipe_unlock(pipe);
}
/*
* umh_pipe_setup
* helper function to customize the process used
* to collect the core in userspace. Specifically
* it sets up a pipe and installs it as fd 0 (stdin)
* for the process. Returns 0 on success, or
* PTR_ERR on failure.
* Note that it also sets the core limit to 1. This
* is a special value that we use to trap recursive
* core dumps
*/
static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
{
struct file *rp, *wp;
struct fdtable *fdt;
struct coredump_params *cp = (struct coredump_params *)info->data;
struct files_struct *cf = current->files;
wp = create_write_pipe(0);
if (IS_ERR(wp))
return PTR_ERR(wp);
rp = create_read_pipe(wp, 0);
if (IS_ERR(rp)) {
free_write_pipe(wp);
return PTR_ERR(rp);
}
cp->file = wp;
sys_close(0);
fd_install(0, rp);
spin_lock(&cf->file_lock);
fdt = files_fdtable(cf);
__set_open_fd(0, fdt);
__clear_close_on_exec(0, fdt);
spin_unlock(&cf->file_lock);
/* and disallow core files too */
current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
return 0;
}
void do_coredump(long signr, int exit_code, struct pt_regs *regs)
{
struct core_state core_state;
struct core_name cn;
struct mm_struct *mm = current->mm;
struct linux_binfmt * binfmt;
const struct cred *old_cred;
struct cred *cred;
int retval = 0;
int flag = 0;
int ispipe;
static atomic_t core_dump_count = ATOMIC_INIT(0);
struct coredump_params cprm = {
.signr = signr,
.regs = regs,
.limit = rlimit(RLIMIT_CORE),
/*
* We must use the same mm->flags while dumping core to avoid
* inconsistency of bit flags, since this flag is not protected
* by any locks.
*/
.mm_flags = mm->flags,
};
audit_core_dumps(signr);
binfmt = mm->binfmt;
if (!binfmt || !binfmt->core_dump)
goto fail;
if (!__get_dumpable(cprm.mm_flags))
goto fail;
cred = prepare_creds();
if (!cred)
goto fail;
/*
* We cannot trust fsuid as being the "true" uid of the
* process nor do we know its entire history. We only know it
* was tainted so we dump it as root in mode 2.
*/
if (__get_dumpable(cprm.mm_flags) == 2) {
/* Setuid core dump mode */
flag = O_EXCL; /* Stop rewrite attacks */
cred->fsuid = 0; /* Dump root private */
}
retval = coredump_wait(exit_code, &core_state);
if (retval < 0)
goto fail_creds;
old_cred = override_creds(cred);
/*
* Clear any false indication of pending signals that might
* be seen by the filesystem code called to write the core file.
*/
clear_thread_flag(TIF_SIGPENDING);
ispipe = format_corename(&cn, signr);
if (ispipe) {
int dump_count;
char **helper_argv;
if (ispipe < 0) {
printk(KERN_WARNING "format_corename failed\n");
printk(KERN_WARNING "Aborting core\n");
goto fail_corename;
}
if (cprm.limit == 1) {
/*
* Normally core limits are irrelevant to pipes, since
* we're not writing to the file system, but we use
* cprm.limit of 1 here as a speacial value. Any
* non-1 limit gets set to RLIM_INFINITY below, but
* a limit of 0 skips the dump. This is a consistent
* way to catch recursive crashes. We can still crash
* if the core_pattern binary sets RLIM_CORE = !1
* but it runs as root, and can do lots of stupid things
* Note that we use task_tgid_vnr here to grab the pid
* of the process group leader. That way we get the
* right pid if a thread in a multi-threaded
* core_pattern process dies.
*/
printk(KERN_WARNING
"Process %d(%s) has RLIMIT_CORE set to 1\n",
task_tgid_vnr(current), current->comm);
printk(KERN_WARNING "Aborting core\n");
goto fail_unlock;
}
cprm.limit = RLIM_INFINITY;
dump_count = atomic_inc_return(&core_dump_count);
if (core_pipe_limit && (core_pipe_limit < dump_count)) {
printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
task_tgid_vnr(current), current->comm);
printk(KERN_WARNING "Skipping core dump\n");
goto fail_dropcount;
}
helper_argv = argv_split(GFP_KERNEL, cn.corename+1, NULL);
if (!helper_argv) {
printk(KERN_WARNING "%s failed to allocate memory\n",
__func__);
goto fail_dropcount;
}
retval = call_usermodehelper_fns(helper_argv[0], helper_argv,
NULL, UMH_WAIT_EXEC, umh_pipe_setup,
NULL, &cprm);
argv_free(helper_argv);
if (retval) {
printk(KERN_INFO "Core dump to %s pipe failed\n",
cn.corename);
goto close_fail;
}
} else {
struct inode *inode;
if (cprm.limit < binfmt->min_coredump)
goto fail_unlock;
cprm.file = filp_open(cn.corename,
O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE | flag,
0600);
if (IS_ERR(cprm.file))
goto fail_unlock;
inode = cprm.file->f_path.dentry->d_inode;
if (inode->i_nlink > 1)
goto close_fail;
if (d_unhashed(cprm.file->f_path.dentry))
goto close_fail;
/*
* AK: actually i see no reason to not allow this for named
* pipes etc, but keep the previous behaviour for now.
*/
if (!S_ISREG(inode->i_mode))
goto close_fail;
/*
* Dont allow local users get cute and trick others to coredump
* into their pre-created files.
*/
if (inode->i_uid != current_fsuid())
goto close_fail;
if (!cprm.file->f_op || !cprm.file->f_op->write)
goto close_fail;
if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
goto close_fail;
}
retval = binfmt->core_dump(&cprm);
if (retval)
current->signal->group_exit_code |= 0x80;
if (ispipe && core_pipe_limit)
wait_for_dump_helpers(cprm.file);
close_fail:
if (cprm.file)
filp_close(cprm.file, NULL);
fail_dropcount:
if (ispipe)
atomic_dec(&core_dump_count);
fail_unlock:
kfree(cn.corename);
fail_corename:
coredump_finish(mm);
revert_creds(old_cred);
fail_creds:
put_cred(cred);
fail:
return;
}
/*
* Core dumping helper functions. These are the only things you should
* do on a core-file: use only these functions to write out all the
* necessary info.
*/
int dump_write(struct file *file, const void *addr, int nr)
{
return access_ok(VERIFY_READ, addr, nr) && file->f_op->write(file, addr, nr, &file->f_pos) == nr;
}
EXPORT_SYMBOL(dump_write);
int dump_seek(struct file *file, loff_t off)
{
int ret = 1;
if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
if (file->f_op->llseek(file, off, SEEK_CUR) < 0)
return 0;
} else {
char *buf = (char *)get_zeroed_page(GFP_KERNEL);
if (!buf)
return 0;
while (off > 0) {
unsigned long n = off;
if (n > PAGE_SIZE)
n = PAGE_SIZE;
if (!dump_write(file, buf, n)) {
ret = 0;
break;
}
off -= n;
}
free_page((unsigned long)buf);
}
return ret;
}
EXPORT_SYMBOL(dump_seek);
|
I8552-cm11/android_kernel_arubaslim
|
fs/exec.c
|
C
|
gpl-2.0
| 55,090
|
/* ============================================================
*
* This file is a part of kipi-plugins project
* http://www.digikam.org
*
* Date : 2006-10-18
* Description : images list settings page.
*
* Copyright (C) 2006-2012 by Gilles Caulier <caulier dot gilles at gmail dot 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, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* ============================================================ */
#ifndef IMAGES_PAGE_H
#define IMAGES_PAGE_H
// Local includes
#include "kpimageslist.h"
#include "emailsettingscontainer.h"
namespace KIPI
{
class Interface;
}
using namespace KIPI;
using namespace KIPIPlugins;
namespace KIPISendimagesPlugin
{
class ImagesPage : public KPImagesList
{
Q_OBJECT
public:
ImagesPage(QWidget* const parent, Interface* const iface);
~ImagesPage();
QList<EmailItem> imagesList() const;
};
} // namespace KIPISendimagesPlugin
#endif // IMAGES_PAGE_H
|
rosedu/digikam-2012-kipi-plugins
|
sendimages/imagespage.h
|
C
|
gpl-2.0
| 1,369
|
<?php
/*
* Create the templatic Slider
*/
class templatic_slider extends WP_Widget {
function templatic_slider() {
//Constructor
$widget_ops = array('classname' => 'widget Templatic Slider', 'description' => __('Home page post slider with display selected post type or display custom images on home page slider') );
$this->WP_Widget('templatic_slider', __('T → Home page Main Slider'), $widget_ops);
}
function widget($args, $instance) {
extract($args, EXTR_SKIP);
echo $before_widget;
/*
* Add flexslider script and style sheet in head tag
*/
wp_enqueue_script('flexslider_script', TEMPL_PLUGIN_URL."/js/jquery.flexslider-min.js");
wp_enqueue_script('flexslider_script', TEMPL_PLUGIN_URL."/js/modernizr.js");
wp_enqueue_style( 'flexslider_css', TEMPL_PLUGIN_URL.'/css/flexslider.css');
$custom_banner_temp = empty($instance['custom_banner_temp']) ? '' : $instance['custom_banner_temp'];
$post_type = empty($instance['post_type']) ? 'post,1' : apply_filters('widget_category', $instance['post_type']);
$posttype = explode(',',$post_type);
$post_type = $posttype[0];
$cat_id = $posttype[1];
$cat_name = $posttype[2];
$s1 = empty($instance['s1']) ? '' : apply_filters('widget_s1', $instance['s1']);
$s1_title = empty($instance['s1_title']) ? '' : apply_filters('widget_s1_title', $instance['s1_title']);
$animation = empty($instance['animation']) ? 'slide' : apply_filters('widget_number', $instance['animation']);
$number = empty($instance['number']) ? '5' : apply_filters('widget_number', $instance['number']);
$height = empty($instance['height']) ? '' : apply_filters('widget_height', $instance['height']);
$autoplay = empty($instance['autoplay']) ? '' : apply_filters('widget_autoplay', $instance['autoplay']);
$slideshowSpeed = empty($instance['slideshowSpeed']) ? '' : apply_filters('widget_autoplay', $instance['slideshowSpeed']);
$sliding_direction = empty($instance['sliding_direction']) ? 'horizontal' : $instance['sliding_direction'];
$reverse = empty($instance['reverse']) ? 'false' : $instance['reverse'];
$animation_speed = empty($instance['animation_speed']) ? '2000' : $instance['animation_speed'];
// Carousel Slider Settings
$is_Carousel = empty($instance['is_Carousel']) ? '' : $instance['is_Carousel'];
if($is_Carousel)
{
$item_width = empty($instance['item_width']) ? '0' : $instance['item_width'];
//$item_margin = empty($instance['item_margin']) ? '0' : $instance['item_margin'];
$min_item = empty($instance['min_item']) ? '0' : $instance['min_item'];
$max_items = empty($instance['max_items']) ? '0' : $instance['max_items'];
$item_move = empty($instance['item_move']) ? '0' : $instance['item_move'];
$width=apply_filters('carousel_slider_width',$item_width);
$height=apply_filters('carousel_slider_height','');
}else{
$item_width=0;
$min_item = 0;
$max_items =0;
$item_move=0;
$width=0;
$height='';
}
if($autoplay==''){ $autoplay='false'; }
if($slideshowSpeed==''){$slideshowSpeed='300000';}
if($animation_speed==''){$animation_speed='2000';}
if($autoplay=='false'){ $animation_speed='300000'; }
?>
<script type="text/javascript">
jQuery(window).load(function(){
jQuery('.flexslider').flexslider({
animation: '<?php echo $animation;?>',
slideshow: <?php echo $autoplay;?>,
direction: "<?php echo $sliding_direction;?>",
slideshowSpeed: <?php echo $slideshowSpeed;?>,
<?php if($autoplay=='true'):?>animationSpeed: <?php echo $animation_speed;?>,<?php endif;?>
reverse: <?php echo $reverse;?>,
animationLoop: true,
startAt: 0,
smoothHeight: true,
easing: "swing",
pauseOnHover: true,
video: true,
controlNav: true,
directionNav: true,
prevText: "Previous",
nextText: "Next",
// Carousel Slider Options
itemWidth: <?php echo $item_width;?>, //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
itemMargin: <?php if($min_item!=""){echo $min_item;}else echo '0'?>, //{NEW} Integer: Margin between carousel items.
minItems: <?php echo $min_item;?>, //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
maxItems: <?php echo $max_items;?>, //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
move: <?php echo $item_move;?>, //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
start: function(slider){
jQuery('body').removeClass('loading');
}
});
});
//FlexSlider: Default Settings
</script>
<div class="flexslider clearfix">
<div class="slides_container clearfix">
<?php do_action('templ_slider_search_widget',$instance);// add action for display additional field?>
<ul class="slides">
<?php if(isset($instance['custom_banner_temp']) && $instance['custom_banner_temp'] == 1):?>
<?php if(is_array($s1)):?>
<?php for($i=0;$i<count($s1);$i++):?>
<?php if($s1[$i]!=""):
?>
<li>
<div class="post_list">
<div class="post_img">
<img src="<?php echo $s1[$i]; ?>" alt="" />
</div>
<div class="slider-post">
<h2><?php echo $s1_title[$i]; ?></h2>
</div>
</div>
</li>
<?php endif;?>
<?php endfor;//finish forloop?>
<?php endif;?>
<?php else:
global $post,$wpdb;
$counter=0;
$postperslide = 1;
$taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type,'public' => true, '_builtin' => true ));
$term = get_term( $cat_id, $cat_name );
$cat_id=$term->term_id;
$args=array(
'post_type' => $post_type,
'posts_per_page' => $number,
'post_status' => 'publish' ,
'tax_query' => array(
array(
'taxonomy' =>$taxonomies[0],
'field' => 'id',
'terms' => array($cat_id),
'operator' => 'IN'
)
)
);
$slide = null;
remove_all_actions('posts_where');
$slide = new WP_Query($args);
if( $slide->have_posts() ) {
while ($slide->have_posts()) : $slide->the_post();
global $post;
//check post thumbnail image if available
if ( has_post_thumbnail()) {
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'home-page-slider');
$post_images=$large_image_url[0];
}else{
$post_images=bdw_get_images_plugin($post->ID,'home-page-slider');
$post_images = $post_images[0]['file'];
}
//$post_images = bdw_get_images_with_info($post->ID,'home_slider');
if($counter=='0' || $counter%$postperslide==0){ echo "<li>";}
?>
<div class="post_list">
<div class="post_img"> <a href="<?php the_permalink(); ?>">
<?php if($post_images != ""){?>
<img src="<?php echo $post_images;?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" width="<?php echo $width;?>" height="<?php echo $height;?>" />
<?php }else{?>
<img src="<?php echo TEMPL_PLUGIN_URL;?>tmplconnector/monetize/templatic-widgets/widget_images/add_220x220.png" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" width="<?php echo ($width!="")?$width:'875';?>" height="<?php echo ($height!="")?$height:'400';?>" />
<?php }?>
</a>
</div>
<div class="slider-post">
<h2>
<a href="<?php the_permalink() ?>" rel="bookmark"> <?php the_title(); ?> </a>
</h2>
<?php echo print_excerpt(50); ?>
<?php do_action('slider_extra_content',get_the_ID());// do action for display the extra content?>
</div>
</div>
<?php
$counter++;
if($counter%$postperslide==0){ echo "</li>"; }
endwhile;
}
?>
<?php endif;?>
</ul>
</div>
</div>
<?php
echo $after_widget;
}
function update($new_instance, $old_instance) {
//save the widget
return $new_instance;
}
function form($instance) {
//widgetform in backend
$instance = wp_parse_args( (array) $instance, array( 'search'=>'','search_post_type'=>'','location'=>'','distance'=>'','radius'=>'', 'post_type' => '', 'number' => '', 'animation'=>'', 'slideshowSpeed'=>'', 'animation_speed'=>'', 'sliding_direction'=>'', 'reverse'=>'', 'item_width'=>'','is_Carousel_temp'=>'', 'min_item'=>'', 'max_items'=>'', 'item_move'=>'', 'custom_banner_temp'=>'','s1' => '', 's1_title' => '' ) );
// Widget Get Posts settings
$custom_banner_temp = strip_tags($instance['custom_banner_temp']);
$post_type = strip_tags($instance['post_type']);
$number = strip_tags($instance['number']);
// Slider Basic Settings
$autoplay = strip_tags($instance['autoplay']);
$animation = strip_tags($instance['animation']);
$slideshowSpeed = strip_tags($instance['slideshowSpeed']);
$sliding_direction = strip_tags($instance['sliding_direction']);
$reverse = strip_tags($instance['reverse']);
$animation_speed = strip_tags($instance['animation_speed']);
// Carousel Slider Settings
// Carousel Slider Settings
$is_Carousel = strip_tags($instance['is_Carousel']);
$item_width = strip_tags($instance['item_width']);
//$item_margin = strip_tags($instance['item_margin']);
$min_item = strip_tags($instance['min_item']);
$max_items = strip_tags($instance['max_items']);
$item_move = strip_tags($instance['item_move']);
$is_Carousel_temp = strip_tags($instance['is_Carousel_temp']);
$item_width = strip_tags($instance['item_width']);
//$item_margin = strip_tags($instance['item_margin']);
$min_item = strip_tags($instance['min_item']);
$max_items = strip_tags($instance['max_items']);
$item_move = strip_tags($instance['item_move']);
// If Custom Banner Slider (Settings)
$s1 = ($instance['s1']);
$s1_title = ($instance['s1_title']);
?>
<script type="text/javascript">
function select_custom_image(id,div_def,div_custom)
{
var checked=id.checked;
jQuery('#'+div_def).slideToggle('slow');
jQuery('#'+div_custom).slideToggle('slow');
}
function select_is_Carousel(id,div_def)
{
var checked=id.checked;
jQuery('#'+div_def).slideToggle('slow');
}
</script>
<?php do_action('templ_search_slider_widget_form',$this,$instance); // add action for display additional field?>
<p>
<label for="<?php echo $this->get_field_id('animation'); ?>">
<?php _e('Animation',DOMAIN); ?>
:
<select class="widefat" name="<?php echo $this->get_field_name('animation'); ?>" id="<?php echo $this->get_field_id('animation'); ?>">
<option <?php if(esc_attr($animation)=='fade'){?> selected="selected"<?php }?> value="fade">
<?php _e("Fade","templatic");?>
</option>
<option <?php if(esc_attr($animation)=='slide'){?> selected="selected"<?php }?> value="slide">
<?php _e("Slide","templatic");?>
</option>
</select>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('autoplay'); ?>">
<?php _e('Slide show',DOMAIN); ?>
:
<select class="widefat" name="<?php echo $this->get_field_name('autoplay'); ?>" id="<?php echo $this->get_field_id('autoplay'); ?>">
<option <?php if(esc_attr($autoplay)=='true'){?> selected="selected"<?php }?> value="true">
<?php _e("Yes","templatic");?>
</option>
<option <?php if(esc_attr($autoplay)=='false'){?> selected="selected"<?php }?> value="false">
<?php _e("No","templatic");?>
</option>
</select>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('sliding_direction'); ?>">
<?php _e('Sliding Direction',DOMAIN); ?>
:
<select class="widefat" name="<?php echo $this->get_field_name('sliding_direction'); ?>" id="<?php echo $this->get_field_id('sliding_direction'); ?>">
<option <?php if(esc_attr($sliding_direction)=='horizontal'){?> selected="selected"<?php }?> value="horizontal">
<?php _e("Horizontal","templatic");?>
</option>
<option <?php if(esc_attr($sliding_direction)=='vertical'){?> selected="selected"<?php }?> value="vertical">
<?php _e("Vertical","templatic");?>
</option>
</select>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('reverse'); ?>">
<?php _e('Reverse Animation Direction',DOMAIN); ?>
:
<select class="widefat" name="<?php echo $this->get_field_name('reverse'); ?>" id="<?php echo $this->get_field_id('reverse'); ?>">
<option <?php if(esc_attr($reverse)=='false'){?> selected="selected"<?php }?> value="false">
<?php _e("False","templatic");?>
</option>
<option <?php if(esc_attr($reverse)=='true'){?> selected="selected"<?php }?> value="true">
<?php _e("True","templatic");?>
</option>
</select>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('slideshowSpeed'); ?>">
<?php _e('Slide Show Speed',DOMAIN); ?>
:
<input class="widefat" id="<?php echo $this->get_field_id('slideshowSpeed'); ?>" name="<?php echo $this->get_field_name('slideshowSpeed'); ?>" type="text" value="<?php echo esc_attr($slideshowSpeed); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('animation_speed'); ?>">
<?php _e('Animation Speed',DOMAIN); ?>
:
<input class="widefat" id="<?php echo $this->get_field_id('animation_speed'); ?>" name="<?php echo $this->get_field_name('animation_speed'); ?>" type="text" value="<?php echo esc_attr($animation_speed); ?>" />
</label>
</p>
<!--is_Carousel -->
<p><br/>
<label for="<?php echo $this->get_field_id('is_Carousel'); ?>">
<input id="<?php echo $this->get_field_id('is_Carousel'); ?>" name="<?php echo $this->get_field_name('is_Carousel'); ?>" type="checkbox" value="1" <?php if($is_Carousel =='1'){ ?>checked=checked<?php }
?>style="width:10px;" onclick="select_is_Carousel(this,'<?php echo $this->get_field_id('home_slide_carousel'); ?>');"/>
<?php _e("<b>Settings for Carousel slider option?</b>",
"templatic");?>
</label>
</p>
<div id="<?php echo $this->get_field_id('home_slide_carousel'); ?>" style="<?php if($is_Carousel =='1'){ ?>display:block;<?php }else{?>display:none;<?php }?>">
<p>
<label for="<?php echo $this->get_field_id('item_width'); ?>">
<?php _e('Item Width: <br/><small>(Box-model width of individual items, including horizontal borders and padding.)</small>',DOMAIN); ?>
:
<input class="widefat" id="<?php echo $this->get_field_id('item_width'); ?>" name="<?php echo $this->get_field_name('item_width'); ?>" type="text" value="<?php echo esc_attr($item_width); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('min_item'); ?>">
<?php _e('Min Item <br/><small>(Minimum number of items that should be visible. Items will resize fluidly when below this.)</small>',DOMAIN); ?>
<input class="widefat" id="<?php echo $this->get_field_id('min_item'); ?>" name="<?php echo $this->get_field_name('min_item'); ?>" type="text" value="<?php echo esc_attr($min_item); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('max_items'); ?>">
<?php _e('Max Item <br/><small>(Maxmimum number of items that should be visible. Items will resize fluidly when above this limit.)</small>',DOMAIN); ?>
<input class="widefat" id="<?php echo $this->get_field_id('max_items'); ?>" name="<?php echo $this->get_field_name('max_items'); ?>" type="text" value="<?php echo esc_attr($max_items); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('item_move'); ?>">
<?php _e('Items Move <br/><small>(Number of items that should move on animation. If 0, slider will move all visible items.)</small>',DOMAIN); ?>
<input class="widefat" id="<?php echo $this->get_field_id('item_move'); ?>" name="<?php echo $this->get_field_name('item_move'); ?>" type="text" value="<?php echo esc_attr($item_move); ?>" />
</label>
</p>
</div>
<!-- Finish is_Carousel -->
<p><br/>
<label for="<?php echo $this->get_field_id('custom_banner_temp'); ?>">
<input id="<?php echo $this->get_field_id('custom_banner_temp'); ?>" name="<?php echo $this->get_field_name('custom_banner_temp'); ?>" type="checkbox" value="1" <?php if($custom_banner_temp =='1'){ ?>checked=checked<?php } ?>style="width:10px;" onclick="select_custom_image(this,'<?php echo $this->get_field_id('home_slide_default_temp'); ?>','<?php echo $this->get_field_id('home_slide_custom_temp'); ?>');" />
<?php _e('<b>Use custom images?</b>',DOMAIN);?>
<br/>
</label>
<br/>
</p>
<div id="<?php echo $this->get_field_id('home_slide_default_temp'); ?>" style="<?php if($custom_banner_temp =='1'){ ?>display:none;<?php }else{?>display:block;<?php }?>">
<p>
<label for="<?php echo $this->get_field_id('post_type');?>" >
<?php _e('Select Taxonomy:');?>
<select id="<?php echo $this->get_field_id('post_type'); ?>" name="<?php echo $this->get_field_name('post_type'); ?>" class="widefat" >
<?php
$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );
$taxonomies = array_filter( $taxonomies, 'templatic_exclude_taxonomies' );
?>
<?php
foreach ( $taxonomies as $taxonomy ) {
$query_label = '';
if ( !empty( $taxonomy->query_var ) )
$query_label = $taxonomy->query_var;
else
$query_label = $taxonomy->name;
if($taxonomy->labels->name!='Tags' && $taxonomy->labels->name!='Format'):
?>
<optgroup label="<?php echo esc_attr( $taxonomy->object_type[0])."-".esc_attr($taxonomy->labels->name); ?>">
<?php
$terms = get_terms( $taxonomy->name, 'orderby=name&hide_empty=1' );
foreach ( $terms as $term ) {
$term_value=esc_attr($taxonomy->object_type[0]). ',' .$term->term_id.','.$query_label;
?>
<option style="margin-left: 8px; padding-right:10px;" value="<?php echo $term_value ?>" <?php if($post_type==$term_value) echo "selected";?>><?php echo '-' . esc_attr( $term->name ); ?></option>
<?php } ?>
?> </optgroup>
<?php
endif;
}
?>
</select>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('number'); ?>">
<?php _e('Number of posts:',DOMAIN);?>
<input class="widefat" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo esc_attr($number); ?>" />
</label>
</p>
</div>
<div id="<?php echo $this->get_field_id('home_slide_custom_temp'); ?>" style="<?php if($custom_banner_temp =='1'){ ?>display:block;<?php }else{?>display:none;<?php }?>">
<div id="TextBoxesGroup" class="TextBoxesGroup">
<div id="TextBoxDiv1" class="TextBoxDiv1">
<p>
<?php global $textbox_title;
$textbox_title=$this->get_field_name('s1_title');
?>
<label for="<?php echo $this->get_field_id('s1_title'); ?>">
<?php _e('Banner Slider Title 1');?>
<input type="text" class="widefat" name="<?php echo $textbox_title; ?>[]" value="<?php echo esc_attr($s1_title[0]); ?>">
</label>
</p>
<p>
<?php global $textbox_name;
$textbox_name=$this->get_field_name('s1');
?>
<label for="<?php echo $this->get_field_id('s1'); ?>">
<?php _e('Banner Slider Image 1 full URL <small>(ex.http://templatic.com/images/banner1.png, Image size 980x425 )</small> :');?>
<input type="text" class="widefat" name="<?php echo $textbox_name; ?>[]" value="<?php echo esc_attr($s1[0]); ?>">
</label>
</p>
</div>
<?php
for($i=1;$i<count($s1);$i++)
{
if($s1[$i]!="")
{
$j=$i+1;
echo '<div class="TextBoxDiv-'.$j.'">';
echo '<p>';
echo '<label>Banner Slider Text '.$j;
echo ' <input type="text" class="widefat" name="'.$textbox_title.'[]" value="'.esc_attr($s1_title[$i]).'"></label>';
echo '</label>';
echo '</p>';
echo '<p>';
echo '<label>Banner Slider Image '.$j.' full URL';
echo ' <input type="text" class="widefat" name="'.$textbox_name.'[]" value="'.esc_attr($s1[$i]).'"></label>';
echo '</label>';
echo '</p>';
echo '</div>';
}
}
?>
</div>
<input value="Add Textbox" id="addButton" class="addButton" type="button" onclick="add_textbox('<?php echo $textbox_name;?>','<?php echo $textbox_title;?>');"/>
<input value="Remove Textbox" id="removeButton" class="removeButton" type="button" onclick="remove_textbox();" />
</div>
<?php
}
}
/*
* templatic Slider widget init
*/
add_action( 'widgets_init', create_function('', 'return register_widget("templatic_slider");') );
add_action('admin_footer','multitext_box');
function multitext_box()
{
global $textbox_name,$textbox_title;
?>
<script type="application/javascript">
var counter = 2;
function add_textbox(name,title)
{
var newTextBoxDiv = jQuery(document.createElement('div')).attr("class", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<p><label>Banner Slider Title '+ counter + ' </label>'+'<input type="text" class="widefat" name="'+title+'[]" id="textbox' + counter + '" value="" ></p><p><label>Banner Slider Image '+ counter + ' full URL : </label>'+'<input type="text" class="widefat" name="'+name+'[]" id="textbox' + counter + '" value="" ></p>');
newTextBoxDiv.appendTo(".TextBoxesGroup");
counter++;
}
function remove_textbox()
{
if(counter-1==1){
alert("you need one textbox required.");
return false;
}
counter--;
jQuery(".TextBoxDiv" + counter).remove();
}
</script>
<?php
}
?>
|
imshashank/osuevents
|
wp-content/plugins/Tevolution/tmplconnector/monetize/templatic-widgets/templatic_slider_widget.php
|
PHP
|
gpl-2.0
| 22,605
|
/**
* @mainpage Flex Sector Remapper : LinuStoreIII_1.2.0_b035-FSR_1.2.1p1_b129_RTM
*
* @section Intro
* Flash Translation Layer for Flex-OneNAND and OneNAND
*
* @section Copyright
*---------------------------------------------------------------------------*
* *
* Copyright (C) 2003-2010 Samsung Electronics *
* 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. *
* *
*---------------------------------------------------------------------------*
*
* @section Description
*
*/
/**
* @file FSR_LLD_FlexOND.c
* @brief This file implements Low Level Driver for Flex-OneNAND
* @author NamOh Hwang
* @author SongHo Yoon
* @date 10-JAN-2007
* @remark
* REVISION HISTORY
* @n 10-JAN-2007 [NamOh Hwang] : first writing
*
*/
/******************************************************************************/
/* Header file inclusions */
/******************************************************************************/
#define FSR_NO_INCLUDE_BML_HEADER
#define FSR_NO_INCLUDE_STL_HEADER
#include "FSR.h"
#include "FSR_LLD_FlexOND.h"
/******************************************************************************/
/* Local Configurations */
/* */
/* - FSR_LLD_BIG_ENDIAN : to support big endianess */
/* - FSR_LLD_STRICT_CHK : to check parameters strictly */
/* - FSR_ONENAND_EMULATOR : to use Flex-OneNAND emulator */
/* instead of real device (for debugging only) */
/* - FSR_FLEXIA : to build with Flexia (FSR image tool) */
/* - FSR_LLD_STATISTICS : to accumulate statistics. */
/* - FSR_LLD_LOGGING_HISTORY : to log history */
/* - FSR_LLD_HANDSHAKE_ERR_INF : to support TINY FSR */
/******************************************************************************/
//#define FSR_LLD_BIG_ENDIAN
#define FSR_LLD_STRICT_CHK
//#define FSR_LLD_STATISTICS
#define FSR_LLD_LOGGING_HISTORY
#define FSR_LLD_USE_CACHE_PGM
//#define FSR_LLD_WAIT_ALLDIE_PGM_READY
#define FSR_LLD_USE_SUPER_LOAD
//#define FSR_LLD_WAIT_WR_PROTECT_STAT
//#define FSR_LLD_ENABLE_DEBUG_PORT
//#define FSR_LLD_PE_TEST
#if defined(FSR_BIG_ENDIAN)
#define FSR_LLD_BIG_ENDIAN
#endif
#if defined(FSR_ONENAND_EMULATOR)
#define FSR_LLD_STATISTICS
#define FSR_LLD_LOGGING_HISTORY
#endif
#if defined(FSR_NBL2)
#undef FSR_LLD_STATISTICS
#undef FSR_LLD_LOGGING_HISTORY
#endif
#if defined(FSR_ONENAND_EMULATOR)
#include "FSR_FOE_Interface.h"
#endif /* #if defined(FSR_ONENAND_EMULATOR) */
/******************************************************************************/
/* Local #defines */
/******************************************************************************/
#define FSR_FND_MAX_DEVS (FSR_MAX_DEVS)
#define FSR_FND_1ST_DIE (0)
#define FSR_FND_2ND_DIE (1)
#define FSR_FND_DID_MASK (0xFFF8) /* Device ID Register */
#define FSR_FND_DID_VCC_MASK (0x0003) /* Device ID Register */
#define FSR_FND_DID_VCC_33V (0x0001) /* Device ID Register */
#define FSR_FND_STEPPING_ID_MASK (0x000F) /* Version ID Register */
#define FSR_FND_CS_VERSION (0x0001) /* cs version not support
Erasing of PI Block */
#define FSR_FND_INT_MASTER_READY (0x8000) /* interrupt status reg. */
#define FSR_FND_INT_READ_READY (0x0080)
#define FSR_FND_INT_WRITE_READY (0x0040)
#define FSR_FND_INT_ERASE_READY (0x0020)
#define FSR_FND_INT_RESET_READY (0x0010)
#define FSR_FND_DFS_BASEBIT (15) /* start address 1 reg. */
#define FSR_FND_DFS_MASK (0x8000)
#define FSR_FND_DBS_BASEBIT (15) /* start address 2 reg. */
#define FSR_FND_DBS_MASK (0x8000)
#define FSR_FND_STATUS_ERROR (0x0400) /* controller status reg.*/
#define FSR_FND_PREV_CACHEPGM_ERROR (0x0004) /* controller status reg.*/
#define FSR_FND_CURR_CACHEPGM_ERROR (0x0002) /* controller status reg.*/
#if defined(FSR_PE_TEST)
#define FSR_FND_ECC_READ_DISTURBANCE (0x0F0F) /* ECC 1~4 bit error */
#else
#define FSR_FND_ECC_READ_DISTURBANCE (0x0C0C) /* ECC 3~4 bit error */
#endif
#define FSR_FND_ECC_UNCORRECTABLE (0x1010) /* ECC status reg.1,2,3,4*/
/* the size of array whose element can be put into command register */
#define FSR_FND_MAX_PGMCMD (2) /* the size of gnPgmCmdArray */
#define FSR_FND_MAX_LOADCMD (6) /* the size of gnLoadCmdArray*/
#define FSR_FND_MAX_ERASECMD (1) /* the size of gnEraseCmdArra*/
#define FSR_FND_MAX_CPBKCMD (3) /* the size of gnCpBkCmdArray*/
#define FSR_FND_MAX_BADMARK (4) /* the size of gnBadMarkValue*/
#define FSR_FND_MAX_BBMMETA (2) /* the size of gnBBMMetaValue*/
#define FSR_FND_MAX_ECC_STATUS_REG (4) /* # of ECC status registers */
#define FSR_FND_VALID_BLK_MARK (0xFFFF)
#define FSR_FND_SECTOR_SIZE (FSR_SECTOR_SIZE)
/* hardware ECC of Flex-OneNAND use five UINT16 (10 bytes) of spare area */
#define FSR_FND_SPARE_HW_ECC_AREA (5)
/* out of 16 bytes in spare area of 1 sector, LLD use 6 bytes */
#define FSR_FND_SPARE_USER_AREA (6)
#define FSR_FND_BUSYWAIT_TIME_LIMIT (10000000)
/* Write protect time out count */
#define FSR_FND_WR_PROTECT_TIME_LIMIT (25000000)
/* Transfering data between DataRAM & host DRAM depends on DMA & sync mode.
* Because DMA & sync burst needs some preparation,
* when the size of transferring data is small,
* it's better to use load, store command of ARM processor.
* Confer _ReadMain(), _WriteMain().
* FSR_FND_MIN_BULK_TRANS_SIZE stands for minimum transfering size.
*/
#define FSR_FND_MIN_BULK_TRANS_SIZE (16 * 2)
/* Buffer Sector Count specifies the number of sectors to load
* LLD does not support sector-based load.
* Instead, LLD always load 1 page, and selectively transfer sectors.
*/
#define FSR_FND_START_BUF_DEFAULT (0x0800)
#define FSR_FND_PI_LOCK (0x3F00)
#define FSR_FND_PI_NOLOCK (0xFF00)
#define FSR_FND_PI_RSV_MASK (0xFFFF)
#define FSR_FND_PI_LOCK_MASK (0xC000)
#define FSR_FND_OTP_LOCK_MASK (0x00FF)
#define FSR_FND_LOCK_OTP_BLOCK (0x00FC)
#define FSR_FND_LOCK_1ST_BLOCK_OTP (0x00F3)
#define FSR_FND_LOCK_BOTH_OTP (0x00F0)
#define FSR_FND_OTP_PAGE_OFFSET (49)
/* controller status register */
#define FSR_FND_CTLSTAT_OTP_MASK (0x0060)
#define FSR_FND_CTLSTAT_OTP_BLK_LOCKED (0x0040)
#define FSR_FND_CTLSTAT_1ST_OTP_LOCKED (0x0020)
/* Flex-OneNAND command which is written to Command Register */
#define FSR_FND_CMD_LOAD (0x0000)
#define FSR_FND_CMD_SUPERLOAD (0x0003)
#define FSR_FND_CMD_UPDATE_PI (0x0005)
#define FSR_FND_CMD_PROGRAM (0x0080)
#define FSR_FND_CMD_CACHEPGM (0x007F)
#define FSR_FND_CMD_UNLOCK_BLOCK (0x0023)
#define FSR_FND_CMD_LOCK_BLOCK (0x002A)
#define FSR_FND_CMD_LOCKTIGHT_BLOCK (0x002C)
#define FSR_FND_CMD_UNLOCK_ALLBLOCK (0x0027)
#define FSR_FND_CMD_ERASE (0x0094)
#define FSR_FND_CMD_RST_NFCORE (0x00F0)
#define FSR_FND_CMD_HOT_RESET (0x00F3)
#define FSR_FND_CMD_OTP_ACCESS (0x0065)
#define FSR_FND_CMD_ACCESS_PI (0x0066)
/* 14th bit of Controller Status Register (F240h) of OneNAND shows
* whether host is programming/erasing a locked block of the NAND Flash Array
* Flex-OneNAND does not use this bit, and it is fixed to zero.
*/
#define FSR_FND_LOCK_STATE (0x4000)
/* with the help of emulator, LLD can run without the Flex-OneNAND
* in that case, define FSR_ONENAND_EMULATOR
*/
#if defined (FSR_ONENAND_EMULATOR)
#define FND_WRITE(nAddr, nDQ) \
{FSR_FOE_Write((UINT32)&(nAddr), nDQ);}
#define FND_READ(nAddr) \
((UINT16) FSR_FOE_Read((UINT32)&(nAddr)))
#define FND_SET(nAddr, nDQ) \
{FSR_FOE_Write((UINT32)&(nAddr), \
(UINT16) FSR_FOE_Read((UINT32)&(nAddr)) | nDQ);}
#define FND_CLR(nAddr, nDQ) \
{FSR_FOE_Write((UINT32)&(nAddr), \
(UINT16) FSR_FOE_Read((UINT32)&(nAddr)) & nDQ);}
#define TRANSFER_TO_NAND(pDst, pSrc, nSize) \
FSR_FOE_TransferToDataRAM(pDst, pSrc, nSize)
/* nSize is the number of bytes to transfer */
#define TRANSFER_FROM_NAND(pDst, pSrc, nSize) \
FSR_FOE_TransferFromDataRAM(pDst, pSrc, nSize)
/* macro below is for emulation purpose */
#define FND_MEMSET_DATARAM(pDst, nVal, nSize) \
FSR_FOE_MemsetDataRAM((pDst), (nVal), (nSize))
#elif defined (FSR_FLEXIA)
#define FND_WRITE(nAddr, nDQ) \
{FSRDLL_FOE_Write((UINT32)&(nAddr), nDQ);}
#define FND_READ(nAddr) \
((UINT16) FSRDLL_FOE_Read((UINT32)&(nAddr)))
#define FND_SET(nAddr, nDQ) \
{FSRDLL_FOE_Write((UINT32)&(nAddr), \
(UINT16) FSRDLL_FOE_Read((UINT32)&(nAddr)) | nDQ);}
#define FND_CLR(nAddr, nDQ) \
{FSRDLL_FOE_Write((UINT32)&(nAddr), \
(UINT16) FSRDLL_FOE_Read((UINT32)&(nAddr)) & nDQ);}
#define TRANSFER_TO_NAND(pDst, pSrc, nSize) \
FSRDLL_FOE_TransferToDataRAM(pDst, pSrc, nSize)
/* nSize is the number of bytes to transfer */
#define TRANSFER_FROM_NAND(pDst, pSrc, nSize) \
FSRDLL_FOE_TransferFromDataRAM(pDst, pSrc, nSize)
/* macro below is for emulation purpose */
#define FND_MEMSET_DATARAM(pDst, nVal, nSize) \
FSRDLL_FOE_MemsetDataRAM((pDst), (nVal), (nSize))
#elif defined (FSR_MSM7200)
/* onenand controller does word access, but MSM7200 controller does 4byte access */
#define FND_WRITE(nAddr, nDQ) FSR_PAM_WriteToOneNANDRegister((UINT32)&nAddr, nDQ)
#define FND_READ(nAddr) FSR_PAM_ReadOneNANDRegister((UINT32)&nAddr)
#define FND_SET(nAddr, nDQ) \
{ \
UINT32 nData; \
nData = FND_READ(nAddr); \
FND_WRITE(nAddr, (nData | nDQ)); \
}
#define FND_CLR(nAddr, nDQ) \
{ \
UINT32 nData; \
nData = FND_READ(nAddr); \
FND_WRITE(nAddr, (nData & nDQ)); \
}
/* nSize is the number of bytes to transfer */
#define TRANSFER_TO_NAND(pDst, pSrc, nSize) \
FSR_PAM_TransToNAND(pDst, pSrc, nSize)
#define TRANSFER_FROM_NAND(pDst, pSrc, nSize) \
FSR_PAM_TransFromNAND(pDst, pSrc, nSize)
#else /* #if defined (FSR_ONENAND_EMULATOR) */
#define FND_WRITE(nAddr, nDQ) {nAddr = nDQ;}
#define FND_READ(nAddr) (nAddr )
#define FND_SET(nAddr, nDQ) {nAddr = (nAddr | nDQ);}
#define FND_CLR(nAddr, nDQ) {nAddr = (nAddr & nDQ);}
/* nSize is the number of bytes to transfer */
#define TRANSFER_TO_NAND(pDst, pSrc, nSize) \
FSR_PAM_TransToNAND(pDst, pSrc, nSize)
#define TRANSFER_FROM_NAND(pDst, pSrc, nSize) \
FSR_PAM_TransFromNAND(pDst, pSrc, nSize)
/* macro below is for emulation purpose
* in real target environment, it's same as memset()
*/
#define FND_MEMSET_DATARAM(pDst, nVal, nSize) \
FSR_OAM_MEMSET((pDst), (nVal), (nSize))
#endif /* #if defined (FSR_ONENAND_EMULATOR) */
/* In order to wait 200ns, call FND_READ(x->nInt) 12 times */
#define WAIT_FND_INT_STAT(x, a) \
{INT32 nTimeLimit = FSR_FND_BUSYWAIT_TIME_LIMIT; \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
FND_READ(x->nInt); \
while ((FND_READ(x->nInt) & (a)) != (UINT16)(a)) \
{ \
if (--nTimeLimit == 0) \
{ \
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, \
(TEXT("[FND:ERR] busy wait time-out %s(), %d line\r\n"), \
__FSR_FUNC__, __LINE__)); \
_DumpRegisters(x); \
_DumpSpareBuffer(x); \
_DumpCmdLog(); \
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG, \
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__)); \
return (FSR_LLD_NO_RESPONSE); \
} \
}}
/* In order to wait 3s, call FND_READ(x->nInt) 12 times */
#define WAIT_FND_WR_PROTECT_STAT(x, a) \
{INT32 nTimeLimit = FSR_FND_WR_PROTECT_TIME_LIMIT; \
while ((FND_READ(pstFOReg->nWrProtectStat) & (a)) != (UINT16)(a)) \
{ \
if (--nTimeLimit == 0) \
{ \
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, \
(TEXT("[FND:ERR] WR protect busy wait time-out %s(), %d line\r\n"),\
__FSR_FUNC__, __LINE__)); \
_DumpRegisters(x); \
_DumpSpareBuffer(x); \
_DumpCmdLog(); \
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG, \
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__)); \
return (FSR_LLD_NO_RESPONSE); \
} \
}}
/* MACROs below are used for the statistic */
#define FSR_FND_STAT_SLC_PGM (0x00000001)
#define FSR_FND_STAT_LSB_PGM (0x00000002)
#define FSR_FND_STAT_MSB_PGM (0x00000003)
#define FSR_FND_STAT_ERASE (0x00000004)
#define FSR_FND_STAT_SLC_LOAD (0x00000005)
#define FSR_FND_STAT_MLC_LOAD (0x00000006)
#define FSR_FND_STAT_RD_TRANS (0x00000007)
#define FSR_FND_STAT_WR_TRANS (0x00000008)
#define FSR_FND_STAT_WR_CACHEBUSY (0x00000009)
#define FSR_FND_STAT_FLUSH (0x0000000A)
/* command type for statistics */
#define FSR_FND_STAT_NORMAL_CMD (0x0)
#define FSR_FND_STAT_PLOAD (0x1)
#define FSR_FND_STAT_CACHE_PGM (0x2)
#define FSR_FND_CACHE_BUSY_TIME (25) /* in usec */
#define FSR_FND_PAGEBUF_TO_DATARAM_TIME (25) /* in usec */
/* SoftWare OverHead */
#define FSR_FND_RD_SW_OH (0) /* in usec */
#define FSR_FND_WR_SW_OH (0) /* in usec */
/* signature value about UniqueID */
#define FSR_FND_NUM_OF_UID (8)
#define FSR_FND_NUM_OF_SIG (4)
#define FSR_FND_FLUSHOP_CALLER_BASEBIT (16)
#define FSR_FND_FLUSHOP_CALLER_MASK (0xFFFF0000)
/******************************************************************************/
/* Local typedefs */
/******************************************************************************/
/** data structure of Flex-OneNAND specification */
typedef struct
{
UINT16 nMID; /**< manufacturer ID */
UINT16 nDID; /**< bits 0~2 of nDID are
masked with FSR_FND_DID_MASK */
UINT16 nGEN; /**< process information */
UINT16 nNumOfBlks; /**< the number of blocks */
UINT16 nNumOfDies; /**< # of dies in NAND device */
UINT16 nNumOfPlanes; /**< the number of planes */
UINT16 nSctsPerPG; /**< the number of sectors per page */
UINT16 nSparePerSct; /**< # of bytes of spare of a sector */
UINT32 nPgsPerBlkForSLC; /**< # of pages per block in SLC area */
UINT32 nPgsPerBlkForMLC; /**< # of pages per block in MLC area */
BOOL32 b1stBlkOTP; /**< support 1st block OTP or not */
UINT16 nUserOTPScts; /**< # of user sectors */
UINT16 nRsvBlksInDev; /**< # of total bad blocks(init + run)*/
const UINT8 *pPairedPgMap; /**< paired page mapping information */
const UINT8 *pLSBPgMap; /**< array of LSB pages */
/* TrTime, TwTime of MLC are array of size 2
* first element is for LSB TLoadTime, TProgTime
* second element is for MLB TLoadTime, TProgTime
* use macro FSR_LLD_IDX_LSB_TIME, FSR_LLD_IDX_MSB_TIME
*/
UINT32 nSLCTLoadTime; /**< Typical Load operation time */
UINT32 nMLCTLoadTime; /**< Typical Load operation time */
UINT32 nSLCTProgTime; /**< Typical Program operation time */
UINT32 nMLCTProgTime[2]; /**< Typical Program operation time */
UINT32 nTEraseTime; /**< Typical Erase operation time */
/* endurance information */
UINT32 nSLCPECycle; /**< program, erase cycle of SLC block*/
UINT32 nMLCPECycle; /**< program, erase cycle of MLC block*/
} FlexONDSpec;
/** @brief shared data structure for communication in Dual Core */
typedef struct
{
UINT32 nShMemUseCnt;
/**< previous operation data structure which can be shared among process */
UINT16 nPreOp[FSR_MAX_DIES];
UINT16 nPreOpPbn[FSR_MAX_DIES];
UINT16 nPreOpPgOffset[FSR_MAX_DIES];
UINT32 nPreOpFlag[FSR_MAX_DIES];
} FlexONDShMem;
/** data structure of Flex-OneNAND LLD context for each device number */
typedef struct
{
UINT32 nBaseAddr; /**< the base address of Flex-OneNAND */
BOOL32 bOpen; /**< open flag : TRUE32 or FALSE32 */
FlexONDSpec *pstFNDSpec; /**< pointer to FlexONDSpec */
UINT16 nFBAMask; /**< the mask of Flash Block Address */
UINT8 nFPASelSft; /**< the shift value of FPA selection */
UINT8 nDDPSelSft; /**< the shift value of DDP selection */
UINT16 nSysConf1; /**< when opening a device save value
of system configuration 1 register.
restore this value after hot reset */
UINT16 nFlushOpCaller;
BOOL32 bCachePgm; /**< supports cache program */
BOOL32 bIsPreCmdCache[FSR_MAX_DIES];
UINT16 nBlksForSLCArea[FSR_MAX_DIES];/**< # of blocks for SLC area */
UINT8 *pSpareBuffer; /**< can cover all spare area of 1 pg */
UINT8 *pTempBuffer; /**< buffer for temporary use.
is used for just allocation/free */
UINT32 nWrTranferTime; /**< write transfer time */
UINT32 nRdTranferTime; /**< read transfer time */
UINT32 nIntID; /**< interrupt ID : non-blocking I/O */
UINT8 nUID[FSR_LLD_UID_SIZE];/**< Unique ID info. about OTP block */
#if defined (FSR_LLD_STATISTICS)
UINT32 nNumOfSLCLoads; /**< the number of times of Load operations */
UINT32 nNumOfMLCLoads; /**< the number of times of Load operations */
UINT32 nNumOfSLCPgms; /**< the number of times of SLC programs */
UINT32 nNumOfLSBPgms; /**< the number of times of LSB programs */
UINT32 nNumOfMSBPgms; /**< the number of times of MSB programs */
UINT32 nNumOfCacheBusy;/**< the number of times of Cache Busy */
UINT32 nNumOfErases; /**< the number of times of Erase operations */
UINT32 nNumOfRdTrans; /**< the number of times of Read Transfer */
UINT32 nNumOfWrTrans; /**< the number of times of Write Transfer */
UINT32 nPreCmdOption[FSR_MAX_DIES]; /** previous command option */
INT32 nIntLowTime[FSR_MAX_DIES];
/**< MDP : 0
DDP : previous operation time */
UINT32 nRdTransInBytes;/**< the number of bytes transfered in read */
UINT32 nWrTransInBytes;/**< the number of bytes transfered in write */
#endif /* #if defined (FSR_LLD_STATISTICS) */
} FlexONDCxt;
/******************************************************************************/
/* Global variable definitions */
/******************************************************************************/
/* gnPgmCmdArray contains the actual COMMAND for the program
* the size of array can be changed for the future extention
* if device does not support Cache Program, LLD_Open() fills it with
* normal program command
*/
PRIVATE UINT16 gnPgmCmdArray[FSR_FND_MAX_PGMCMD] =
{ FSR_FND_CMD_PROGRAM, /* FSR_LLD_FLAG_1X_PROGRAM */
FSR_FND_CMD_CACHEPGM,/* FSR_LLD_FLAG_1X_CACHEPGM*/
/* FSR_LLD_FLAG_2X_PROGRAM */
/* FSR_LLD_FLAG_2X_CACHEPGM*/
};
/* gnLoadCmdArray contains the actual COMMAND for the load
* the size of array can be changed for the future extention
* gnLoadCmdArray is not a const type, so value can change
*/
PRIVATE UINT16 gnLoadCmdArray[FSR_FND_MAX_LOADCMD] =
{ 0xFFFF, /* FSR_LLD_FLAG_NO_LOADCMD */
FSR_FND_CMD_LOAD, /* FSR_LLD_FLAG_1X_LOAD */
FSR_FND_CMD_SUPERLOAD, /* FSR_LLD_FLAG_1X_PLOAD */
0xFFFF, /* FSR_LLD_FLAG_2X_LOAD */
0xFFFF, /* FSR_LLD_FLAG_2X_PLOAD */
0x0005, /* FSR_LLD_FLAG_LSB_RECOVERY_LOAD */
};
/* gnEraseCmdArray contains the actual COMMAND for the erase
* the size of array can be changed for the future extention
*/
PRIVATE const UINT16 gnEraseCmdArray[FSR_FND_MAX_ERASECMD] =
{ FSR_FND_CMD_ERASE,/* FSR_LLD_FLAG_1X_ERASE */
/* FSR_LLD_FLAG_2X_ERASE */
};
/* gnBadMarkValue contains the actual 2 byte value
* which is programmed into the first 2 byte of spare area
* the size of array can be changed for the future extention
*/
PRIVATE const UINT16 gnBadMarkValue[FSR_FND_MAX_BADMARK] =
{ 0xFFFF, /* FSR_LLD_FLAG_WR_NOBADMARK */
0x2222, /* FSR_LLD_FLAG_WR_EBADMARK */
0x4444, /* FSR_LLD_FLAG_WR_WBADMARK */
0x8888, /* FSR_LLD_FLAG_WR_LBADMARK */
};
/* gnCpBkCmdArray contains the actual COMMAND for the copyback
* the size of array can be changed for the future extention
*/
PRIVATE const UINT16 gnCpBkCmdArray[FSR_FND_MAX_CPBKCMD] =
{ 0xFFFF,
FSR_FND_CMD_LOAD, /* FSR_LLD_FLAG_1X_CPBK_LOAD */
FSR_FND_CMD_PROGRAM,/*FSR_LLD_FLAG_1X_CPBK_PROGR*/
/* FSR_LLD_FLAG_2X_CPBK_LOAD */
/* FSR_LLD_FLAG_2X_CPBK_PROGRAM */
/* FSR_LLD_FLAG_4X_CPBK_LOAD */
/* FSR_LLD_FLAG_4X_CPBK_PROGRAM */
};
PRIVATE const UINT16 gnBBMMetaValue[FSR_FND_MAX_BBMMETA] =
{ 0xFFFF,
FSR_LLD_BBM_META_MARK
};
#if defined (FSR_LLD_LOGGING_HISTORY) && !defined(FSR_OAM_RTLMSG_DISABLE)
PRIVATE const UINT8 *gpszLogPreOp[] =
{ (UINT8 *) "NONE ",
(UINT8 *) "READ ",
(UINT8 *) "CLOAD",
(UINT8 *) "CAPGM",
(UINT8 *) "PROG ",
(UINT8 *) "CBPGM",
(UINT8 *) "ERASE",
(UINT8 *) "IOCTL",
(UINT8 *) "HTRST",
};
#endif
PRIVATE FlexONDCxt *gpstFNDCxt[FSR_FND_MAX_DEVS];
PRIVATE FlexONDShMem *gpstFNDShMem[FSR_FND_MAX_DEVS];
#if defined (FSR_LLD_STATISTICS)
PRIVATE UINT32 gnElapsedTime;
PRIVATE UINT32 gnDevsInVol[FSR_MAX_VOLS] = {0, 0};
#endif /* #if defined (FSR_LLD_STATISTICS) */
/* FSR_FND_Open() maps this function pointer to _ReadOptWithSLoad() or
* _ReadOptWithNonSLoad() according to sync mode
*/
PRIVATE INT32 (*gpfReadOptimal)(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag);
/******************************************************************************/
/* Extern variable declarations */
/******************************************************************************/
#if defined(FSR_LLD_PE_TEST)
PUBLIC UINT16 gnECCStat0;
PUBLIC UINT16 gnECCStat1;
PUBLIC UINT16 gnECCStat2;
PUBLIC UINT16 gnECCStat3;
PUBLIC UINT32 gnPbn;
PUBLIC UINT32 gnPgOffset;
#endif
/******************************************************************************/
/* Local constant definitions */
/******************************************************************************/
/* in case of MLC partition, when Program, Cache Program, Interleave Cache
* Program, Copyback with random datain operations are abnormally aborted,
* not only page data under program but also paired page may be demaged
*/
PRIVATE const UINT8 gnPairPgMap[] =
{
0x04, 0x05, 0x08, 0x09, 0x00, 0x01, 0x0C, 0x0D,
0x02, 0x03, 0x10, 0x11, 0x06, 0x07, 0x14, 0x15,
0x0A, 0x0B, 0x18, 0x19, 0x0E, 0x0F, 0x1C, 0x1D,
0x12, 0x13, 0x20, 0x21, 0x16, 0x17, 0x24, 0x25,
0x1A, 0x1B, 0x28, 0x29, 0x1E, 0x1F, 0x2C, 0x2D,
0x22, 0x23, 0x30, 0x31, 0x26, 0x27, 0x34, 0x35,
0x2A, 0x2B, 0x38, 0x39, 0x2E, 0x2F, 0x3C, 0x3D,
0x32, 0x33, 0x40, 0x41, 0x36, 0x37, 0x44, 0x45,
0x3A, 0x3B, 0x48, 0x49, 0x3E, 0x3F, 0x4C, 0x4D,
0x42, 0x43, 0x50, 0x51, 0x46, 0x47, 0x54, 0x55,
0x4A, 0x4B, 0x58, 0x59, 0x4E, 0x4F, 0x5C, 0x5D,
0x52, 0x53, 0x60, 0x61, 0x56, 0x57, 0x64, 0x65,
0x5A, 0x5B, 0x68, 0x69, 0x5E, 0x5F, 0x6C, 0x6D,
0x62, 0x63, 0x70, 0x71, 0x66, 0x67, 0x74, 0x75,
0x6A, 0x6B, 0x78, 0x79, 0x6E, 0x6F, 0x7C, 0x7D,
0x72, 0x73, 0x7E, 0x7F, 0x76, 0x77, 0x7A, 0x7B
};
PRIVATE const UINT8 gnLSBPgs[] =
{
0x00, 0x01, 0x02, 0x03, 0x06, 0x07, 0x0A, 0x0B,
0x0E, 0x0F, 0x12, 0x13, 0x16, 0x17, 0x1A, 0x1B,
0x1E, 0x1F, 0x22, 0x23, 0x26, 0x27, 0x2A, 0x2B,
0x2E, 0x2F, 0x32, 0x33, 0x36, 0x37, 0x3A, 0x3B,
0x3E, 0x3F, 0x42, 0x43, 0x46, 0x47, 0x4A, 0x4B,
0x4E, 0x4F, 0x52, 0x53, 0x56, 0x57, 0x5A, 0x5B,
0x5E, 0x5F, 0x62, 0x63, 0x66, 0x67, 0x6A, 0x6B,
0x6E, 0x6F, 0x72, 0x73, 0x76, 0x77, 0x7A, 0x7B
};
PRIVATE const FlexONDSpec gstFNDSpec[] = {
/**********************************************************************************************************************/
/* 1. nMID */
/* 2. nDID */
/* 3. nGEN */
/* 4. nNumOfBlks */
/* 5 . nNumOfDies */
/* 6. nNumOfPlanes */
/* 7. nSctsPerPG */
/* 8 nSparePerSct */
/* 9. nPgsPerBlkForSLC */
/* 10 nPgsPerBlkForMLC */
/* 11. b1stBlkOTP */
/* 12. nUserOTPScts */
/* 13. nRsvBlksInDev */
/* 14. pPairedPgMap */
/* 15 pnLSBPgs */
/* 16 nSLCTLoadTime */
/* 17. nMLCTLoadTime */
/* 18. nSLCTProgTime */
/* 19. nMLCTProgTime[0] */
/* 20. nMLCTProgTime[1] */
/* 21. nTEraseTime */
/* 22 nSLCPECycle */
/* 23 nMLCPECycle*/
/**********************************************************************************************************************/
/* 4Gb */
{ 0x00EC, 0x0250, 0, 1024, 1, 1, 8, 16, 64, 128, TRUE32, 50, 26, gnPairPgMap, gnLSBPgs, 45, 50, 240, {240, 1760}, 500, 50000, 10000},
/* 8Gb DDP */
{ 0x00EC, 0x0268, 0, 2048, 2, 1, 8, 16, 64, 128, TRUE32, 50, 52, gnPairPgMap, gnLSBPgs, 45, 50, 240, {240, 1760}, 500, 50000, 10000},
/* 8Gb MDP */
{ 0x00EC, 0x0260, 0, 2048, 1, 1, 8, 16, 64, 128, TRUE32, 50, 52, gnPairPgMap, gnLSBPgs, 45, 50, 240, {240, 1760}, 500, 50000, 5000},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, FALSE32, 0, 0, NULL, 0, 0, 0, 0, { 0, 0}, 0, 0, 0},
};
/******************************************************************************/
/* Local function prototypes */
/******************************************************************************/
PRIVATE INT32 _ReadOptWithNonSLoad (UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag);
PRIVATE INT32 _ReadOptWithSLoad (UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag);
PRIVATE VOID _ReadMain (UINT8 *pDest,
volatile UINT8 *pSrc,
UINT32 nSize,
UINT8 *pTempBuffer);
PRIVATE VOID _ReadSpare (FlexONDCxt *pstFNDCxt,
FSRSpareBuf *pstDest,
volatile UINT8 *pSrc);
PRIVATE VOID _WriteMain( volatile UINT8 *pDest,
UINT8 *pSrc,
UINT32 nSize);
PRIVATE VOID _WriteSpare( FlexONDCxt *pstFNDCxt,
volatile UINT8 *pDest,
FSRSpareBuf *pstSrc,
UINT32 nFlag);
PRIVATE INT32 _ReadPI (UINT32 nDev,
UINT32 nDieIdx,
UINT32 *pnEndOfSLC,
BOOL32 *pbPILocked);
PRIVATE INT32 _WritePI (UINT32 nDev,
UINT32 nDieIdx,
UINT32 nPIValue);
PRIVATE INT32 _ControlLockBlk (UINT32 nDev,
UINT32 nPbn,
UINT32 nBlks,
UINT32 nLockTypeCMD,
UINT32 *pnErrPbn);
PRIVATE INT32 _LockOTP (UINT32 nDev,
UINT32 nLockValue);
PRIVATE INT32 _StrictChk (UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset);
PRIVATE VOID _DumpRegisters (volatile FlexOneNANDReg *pstReg);
PRIVATE VOID _DumpSpareBuffer (volatile FlexOneNANDReg *pstReg);
PRIVATE VOID _DumpCmdLog (VOID);
PRIVATE VOID _CalcTransferTime (UINT32 nDev,
UINT16 nSysConf1Reg,
UINT32 *pnReadCycle,
UINT32 *pnWriteCycle);
PRIVATE INT32 _GetUniqueID (UINT32 nDev,
FlexONDCxt *pstFNDCxt,
UINT32 nFlag);
#if defined (FSR_LLD_STATISTICS)
PRIVATE VOID _AddFNDStatLoad (UINT32 nDev,
UINT32 nDie,
UINT32 nPbn,
UINT32 nCmdOption);
PRIVATE VOID _AddFNDStatPgm (UINT32 nDev,
UINT32 nDie,
UINT32 nPbn,
UINT32 nPg,
UINT32 nCmdOption);
PRIVATE VOID _AddFNDStat (UINT32 nDev,
UINT32 nDie,
UINT32 nType,
UINT32 nBytes,
UINT32 nCmdOption);
#endif /* #if defined (FSR_LLD_STATISTICS) */
#if defined (FSR_LLD_LOGGING_HISTORY)
PRIVATE VOID _AddLog (UINT32 nDev,
UINT32 nDie);
#endif /* #if defined (FSR_LLD_LOGGING_HISTORY) */
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
PRIVATE VOID _SaveErrorCxt (UINT32 nDev,
UINT32 nDie,
FlexONDCxt *pstFNDCxt,
INT32 nLLDRe);
PRIVATE INT32 _CheckErrorCxt (UINT32 nDev,
UINT32 nDie,
FlexONDCxt *pstFNDCxt,
volatile FlexOneNANDReg *pstFOReg);
#endif /* #if defined (FSR_LLD_HANDSHAKE_ERR_INF) */
/******************************************************************************/
/* Code Implementation */
/******************************************************************************/
/**
* @brief This function initializes Flex-OneNAND Device Driver.
*
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_ALREADY_INITIALIZED
*
* @author NamOh Hwang
* @version 1.0.0
* @remark it initialize internal data structure
*
*/
PUBLIC INT32
FSR_FND_Init(UINT32 nFlag)
{
FsrVolParm astPAParm[FSR_MAX_VOLS];
FSRLowFuncTbl astLFT[FSR_MAX_VOLS];
FSRLowFuncTbl *apstLFT[FSR_MAX_VOLS];
FlexONDShMem *pstFNDShMem;
PRIVATE BOOL32 nInitFlg = FALSE32;
UINT32 nVol;
UINT32 nPDev;
UINT32 nIdx;
UINT32 nDie;
UINT32 nMemAllocType;
UINT32 nMemoryChunkID;
UINT32 nSharedMemoryUseCnt;
INT32 nLLDRe = FSR_LLD_SUCCESS;
INT32 nPAMRe = FSR_PAM_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nFlag));
do
{
if (nInitFlg == TRUE32)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] %s(nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" already initialized\r\n")));
nLLDRe = FSR_LLD_ALREADY_INITIALIZED;
break;
}
/* local data structure */
for (nPDev = 0; nPDev < FSR_FND_MAX_DEVS; nPDev++)
{
gpstFNDCxt[nPDev] = NULL;
}
nPAMRe = FSR_PAM_GetPAParm(astPAParm);
if (nPAMRe != FSR_PAM_SUCCESS)
{
nLLDRe = FSR_LLD_PAM_ACCESS_ERROR;
break;
}
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
FSR_OAM_MEMSET(&astLFT[nVol], 0x00, sizeof(FSRLowFuncTbl));
apstLFT[nVol] = &astLFT[nVol];
}
nPAMRe = FSR_PAM_RegLFT(apstLFT);
if (nPAMRe != FSR_PAM_SUCCESS)
{
nLLDRe = FSR_LLD_PAM_ACCESS_ERROR;
break;
}
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
/* because BML calls LLD_Init() by volume,
* FSR_FND_Init() only initializes shared memory of
* corresponding volume
*/
if ((apstLFT[nVol] == NULL) || apstLFT[nVol]->LLD_Init != FSR_FND_Init)
{
continue;
}
if (astPAParm[nVol].bProcessorSynchronization == TRUE32)
{
nMemAllocType = FSR_OAM_SHARED_MEM;
}
else
{
nMemAllocType = FSR_OAM_LOCAL_MEM;
}
nMemoryChunkID = astPAParm[nVol].nMemoryChunkID;
for (nIdx = 0; nIdx < astPAParm[nVol].nDevsInVol; nIdx++)
{
nPDev = nVol * (FSR_MAX_DEVS / FSR_MAX_VOLS) + nIdx;
pstFNDShMem = NULL;
pstFNDShMem = (FlexONDShMem *) FSR_OAM_MallocExt(nMemoryChunkID,
sizeof(FlexONDShMem),
nMemAllocType);
if (pstFNDShMem == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDShMem is NULL\r\n")));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" malloc failed!\r\n")));
nLLDRe = FSR_LLD_MALLOC_FAIL;
break;
}
if (((UINT32) pstFNDShMem & (0x03)) != 0)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDShMem is misaligned:0x%08x\r\n"),
pstFNDShMem));
nLLDRe = FSR_OAM_NOT_ALIGNED_MEMPTR;
break;
}
gpstFNDShMem[nPDev] = pstFNDShMem;
nSharedMemoryUseCnt = pstFNDShMem->nShMemUseCnt;
/* PreOp init of single process */
if (astPAParm[nVol].bProcessorSynchronization == FALSE32)
{
/* initialize shared memory used by LLD */
for (nDie = 0; nDie < FSR_MAX_DIES; nDie++)
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_NONE;
pstFNDShMem->nPreOpPbn[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpFlag[nDie] = FSR_FND_PREOP_FLAG_NONE;
}
}
/* PreOp init of dual process */
else
{
if ((nSharedMemoryUseCnt ==0) ||
(nSharedMemoryUseCnt == astPAParm[nVol].nSharedMemoryInitCycle))
{
pstFNDShMem->nShMemUseCnt = 0;
/* initialize shared memory used by LLD */
for (nDie = 0; nDie < FSR_MAX_DIES; nDie++)
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_NONE;
pstFNDShMem->nPreOpPbn[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpFlag[nDie] = FSR_FND_PREOP_FLAG_NONE;
}
}
}
pstFNDShMem->nShMemUseCnt++;
} /* for (nIdx = 0; nIdx < astPAParm[nVol].nDevsInVol; nIdx++) */
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
} /* for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++) */
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
nInitFlg = TRUE32;
gpfReadOptimal = NULL;
FSR_PAM_InitNANDController();
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function opens Flex-OneNAND device driver
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] pParam : pointer to structure for configuration
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_OPEN_FAILURE
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_MALLOC_FAIL
* @return FSR_LLD_ALREADY_OPEN
* @return FSR_OAM_NOT_ALIGNED_MEMPTR
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR }
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_Open(UINT32 nDev,
VOID *pParam,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt;
FlexONDSpec *pstFNDSpec;
volatile FlexOneNANDReg *pstFOReg;
FsrVolParm *pstParm = (FsrVolParm *) pParam;
UINT32 nCnt = 0;
UINT32 nIdx = 0;
UINT32 nEndBlkNumOfSLC = 0;
UINT32 nRdTransferTime = 0;
UINT32 nWrTransferTime = 0;
UINT32 nBytesPerPage = 0;
UINT32 nSpareBytesPerPage = 0;
UINT32 nMemoryChunkID;
#if !defined(FSR_OAM_RTLMSG_DISABLE)
#if defined(FSR_LLD_HANDSHAKE_ERR_INF)
UINT32 bHandshakeErrInfo = TRUE32;
#else
UINT32 bHandshakeErrInfo = FALSE32;
#endif
#if defined(TINY_FSR)
BOOL32 bTinyFSR = TRUE32;
#else
BOOL32 bTinyFSR = FALSE32;
#endif
#endif
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nMID; /* manufacture ID */
UINT16 nDID; /* device ID */
UINT16 nVID; /* version ID */
UINT16 nShifted;
UINT32 nDie = 0;
UINT32 nTINYFlag = FSR_LLD_FLAG_NONE; /* LLD flag for TINY FSR */
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d,nFlag:0x%x)\r\n"),
__FSR_FUNC__, nDev, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
if (pParam == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, pParam:0x%08x, nFlag:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, pParam, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pParam is NULL\r\n")));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pstFNDCxt = gpstFNDCxt[nDev];
if (pstFNDCxt == NULL)
{
nMemoryChunkID = nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS);
pstFNDCxt = (FlexONDCxt *)
FSR_OAM_MallocExt(nMemoryChunkID, sizeof(FlexONDCxt), FSR_OAM_LOCAL_MEM);
if (pstFNDCxt == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, pParam:0x%08x, nFlag:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, pParam, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt is NULL\r\n")));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" malloc failed!\r\n")));
nLLDRe = FSR_LLD_MALLOC_FAIL;
break;
}
if (((UINT32) pstFNDCxt & (0x03)) != 0)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt is misaligned:0x%08x\r\n"),
pstFNDCxt));
nLLDRe = FSR_OAM_NOT_ALIGNED_MEMPTR;
break;
}
gpstFNDCxt[nDev] = pstFNDCxt;
FSR_OAM_MEMSET(pstFNDCxt, 0x00, sizeof(FlexONDCxt));
} /* if (pstFNDCxt == NULL) */
if (pstFNDCxt->bOpen == TRUE32)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, pParam:0x%08x, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, pParam, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] dev:%d is already open\r\n"), nDev));
nLLDRe = FSR_LLD_ALREADY_OPEN;
break;
}
/* base address setting */
nIdx = nDev & (FSR_MAX_DEVS / FSR_MAX_VOLS -1);
if (pstParm->nBaseAddr[nIdx] != FSR_PAM_NOT_MAPPED)
{
pstFNDCxt->nBaseAddr = pstParm->nBaseAddr[nIdx];
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, pParam:0x%08x, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, pParam, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT(" pstFNDCxt->nBaseAddr: 0x%08x\r\n"),
pstFNDCxt->nBaseAddr));
}
else
{
pstFNDCxt->nBaseAddr = FSR_PAM_NOT_MAPPED;
}
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
nMID = FND_READ(pstFOReg->nMID);
nDID = FND_READ(pstFOReg->nDID);
nVID = FND_READ(pstFOReg->nVerID);
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT(" nDev=%d, nMID=0x%04x, nDID=0x%04x, nVID=0x%04x\r\n"),
nDev, nMID, nDID, nVID));
/* find corresponding FlexONDSpec from gstFNDSpec[]
* by looking at bits 3~15. ignore bits 0~2
*/
pstFNDCxt->pstFNDSpec = NULL;
for (nCnt = 0; gstFNDSpec[nCnt].nMID != 0; nCnt++)
{
if (((nDID & FSR_FND_DID_MASK) == (gstFNDSpec[nCnt].nDID & FSR_FND_DID_MASK)) &&
(nMID == gstFNDSpec[nCnt].nMID))
{
pstFNDCxt->pstFNDSpec = (FlexONDSpec *) &gstFNDSpec[nCnt];
break;
}
/* else continue */
}
if (pstFNDCxt->pstFNDSpec == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, pParam:0x%08x, nFlag:0x%08x / %d line\r\n"),
__FSR_FUNC__, nDev, pParam, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Unknown Device\r\n")));
nLLDRe = FSR_LLD_OPEN_FAILURE;
break;
}
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFNDCxt->nFBAMask = pstFNDSpec->nNumOfBlks / pstFNDSpec->nNumOfDies -1;
pstFNDCxt->nFPASelSft = 2;/* offset of FPA in Start Address8 register */
/* calculate nDDPSelSft */
pstFNDCxt->nDDPSelSft = 0;
nShifted = pstFNDCxt->nFBAMask << 1;
while((nShifted & FSR_FND_DFS_MASK) != FSR_FND_DFS_MASK)
{
pstFNDCxt->nDDPSelSft++;
nShifted <<= 1;
}
/* HOT-RESET initializes the value of register file, which includes
* system configuration 1 register.
* for device to function properly, save the value of system
* configuration 1 register at open time & restore it after HOT-RESET
*/
pstFNDCxt->nSysConf1 = FND_READ(pstFOReg->nSysConf1);
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] pstFNDCxt->nSysConf1:0x%04x / %d line\r\n"),
pstFNDCxt->nSysConf1, __LINE__));
pstFNDCxt->nFlushOpCaller = FSR_FND_PREOP_NONE;
/* previous operation information */
for (nCnt = 0; nCnt < FSR_MAX_DIES; nCnt++)
{
pstFNDCxt->bIsPreCmdCache[nCnt] = FALSE32;
}
#if defined(TINY_FSR)
nTINYFlag = FSR_LLD_FLAG_READ_ONLY;
#endif
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
((nDie + 0x1) & 0x01),
FSR_LLD_FLAG_NONE | nTINYFlag);
}
nLLDRe = FSR_FND_FlushOp(nDev, nDie, FSR_LLD_FLAG_NONE | nTINYFlag);
/* read PI Allocation Info */
for (nCnt = 0; nCnt < pstFNDSpec->nNumOfDies; nCnt++)
{
/* ignore return value of _ReadPI()
* LLD_Open() succeed in the presence of the PI read error
*/
_ReadPI(nDev, nCnt, &nEndBlkNumOfSLC, NULL);
pstFNDCxt->nBlksForSLCArea[nCnt] = (UINT16) nEndBlkNumOfSLC + 1;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] pstFNDCxt->nBlksForSLCArea[%d]:%d / %d line\r\n"),
nCnt, pstFNDCxt->nBlksForSLCArea[nCnt], __LINE__));
}
nSpareBytesPerPage = pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct;
nMemoryChunkID = nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS);
pstFNDCxt->pSpareBuffer =
(UINT8 *) FSR_OAM_MallocExt(nMemoryChunkID, nSpareBytesPerPage, FSR_OAM_LOCAL_MEM);
if (pstFNDCxt->pSpareBuffer == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" malloc failed!\r\n")));
nLLDRe = FSR_LLD_MALLOC_FAIL;
break;
}
if (((UINT32) pstFNDCxt->pSpareBuffer & (0x03)) != 0)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->pSpareBuffer is misaligned:0x%08x\r\n"),
pstFNDCxt->pSpareBuffer));
nLLDRe = FSR_OAM_NOT_ALIGNED_MEMPTR;
break;
}
FSR_OAM_MEMSET(pstFNDCxt->pSpareBuffer, 0xFF, nSpareBytesPerPage);
/* nBytesPerPage is 4224 byte */
nBytesPerPage = pstFNDSpec->nSctsPerPG *
(FSR_FND_SECTOR_SIZE + pstFNDSpec->nSparePerSct);
nMemoryChunkID = nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS);
pstFNDCxt->pTempBuffer =
(UINT8 *) FSR_OAM_MallocExt(nMemoryChunkID, nBytesPerPage, FSR_OAM_LOCAL_MEM);
if (pstFNDCxt->pTempBuffer == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" malloc failed!\r\n")));
nLLDRe = FSR_LLD_MALLOC_FAIL;
break;
}
if (((UINT32) pstFNDCxt->pTempBuffer & (0x03)) != 0)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->pTempBuffer is misaligned:0x%08x\r\n"),
pstFNDCxt->pTempBuffer));
nLLDRe = FSR_OAM_NOT_ALIGNED_MEMPTR;
break;
}
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0x00, nBytesPerPage);
/* time for transfering 16 bits between host & DataRAM of OneNAND */
_CalcTransferTime(nDev, pstFNDCxt->nSysConf1,
&nRdTransferTime, &nWrTransferTime);
pstFNDCxt->nRdTranferTime = nRdTransferTime; /* nano second base */
pstFNDCxt->nWrTranferTime = nWrTransferTime; /* nano second base */
nIdx = nDev & (FSR_MAX_DEVS / FSR_MAX_VOLS -1);
pstFNDCxt->nIntID = pstParm->nIntID[nIdx];
if ((pstFNDCxt->nIntID != FSR_INT_ID_NONE) && (pstFNDCxt->nIntID > FSR_INT_ID_NAND_7))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:INF] nIntID is out of range(nIntID:%d)\r\n"), pstFNDCxt->nIntID));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:INF] FSR_INT_ID_NAND_0(%d) <= nIntID <= FSR_INT_ID_NAND_7(%d)\r\n"),
FSR_INT_ID_NAND_0, FSR_INT_ID_NAND_7));
break;
}
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] pstFNDCxt->nIntID :0x%04x / %d line\r\n"),
pstFNDCxt->nIntID, __LINE__));
if (pstFNDCxt->nSysConf1 & FSR_FND_CONF1_SYNC_READ)
{
gpfReadOptimal = _ReadOptWithSLoad;
}
else
{
gpfReadOptimal = _ReadOptWithNonSLoad;
/* superload does not work in Ayncronous mode.
* so, treat FSR_LLD_FLAG_1X_PLOAD as normal load in Async mode.
*/
gnLoadCmdArray[FSR_LLD_FLAG_1X_PLOAD] = 0x0000;
}
FSR_ASSERT(gpfReadOptimal != NULL);
/* device of 3.3V does not support cache program */
if ((nDID & FSR_FND_DID_VCC_MASK) == FSR_FND_DID_VCC_33V)
{
pstFNDCxt->bCachePgm = FALSE32;
gnPgmCmdArray[FSR_LLD_FLAG_1X_CACHEPGM] = 0x0080;
}
else
{
pstFNDCxt->bCachePgm = TRUE32;
}
#if !defined(FSR_LLD_USE_CACHE_PGM)
pstFNDCxt->bCachePgm = FALSE32;
gnPgmCmdArray[FSR_LLD_FLAG_1X_CACHEPGM] = 0x0080;
#endif
#if !defined(FSR_LLD_USE_SUPER_LOAD)
gpfReadOptimal = _ReadOptWithNonSLoad;
gnLoadCmdArray[FSR_LLD_FLAG_1X_PLOAD] = 0x0000;
#endif
#if defined (FSR_LLD_STATISTICS)
gnDevsInVol[nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS)]++;
#endif
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:INF] 1X_CACHEPGM CMD : 0x%04x\r\n"),
gnPgmCmdArray[FSR_LLD_FLAG_1X_CACHEPGM]));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:INF] 1X_PLOAD CMD : 0x%04x\r\n"),
gnLoadCmdArray[FSR_LLD_FLAG_1X_PLOAD]));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:INF] %s / bHandshakeErrInfo=%d\r\n"),
(bTinyFSR == TRUE32) ? TEXT("TINY_FSR") : TEXT("FSR"), bHandshakeErrInfo));
#if defined(FSR_LLD_ENABLE_DEBUG_PORT)
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:INF] debug port addr : byte order:0x%x / word order:0x%x\r\n"),
(UINT32) (&pstFOReg->nDebugPort), (UINT32) (&pstFOReg->nDebugPort) / 2));
FND_WRITE(pstFOReg->nDebugPort, 0x4321);
#endif
pstFNDCxt->bOpen = TRUE32;
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief This function closes Flex-OneNAND device driver
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_Close(UINT32 nDev,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt;
#if defined (FSR_LLD_STATISTICS)
UINT32 nVol;
#endif
UINT32 nMemoryChunkID;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nFlag));
/* here LLD doesn't flush the previous operation, for BML flushes */
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
if (pstFNDCxt != NULL)
{
pstFNDCxt->bOpen = FALSE32;
pstFNDCxt->pstFNDSpec = NULL;
nMemoryChunkID = nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS);
FSR_OAM_FreeExt(nMemoryChunkID, pstFNDCxt->pTempBuffer, FSR_OAM_LOCAL_MEM);
FSR_OAM_FreeExt(nMemoryChunkID, pstFNDCxt->pSpareBuffer, FSR_OAM_LOCAL_MEM);
FSR_OAM_FreeExt(nMemoryChunkID, pstFNDCxt, FSR_OAM_LOCAL_MEM);
gpstFNDCxt[nDev] = NULL;
#if defined (FSR_LLD_STATISTICS)
nVol = nDev / (FSR_MAX_DEVS / FSR_MAX_VOLS);
gnDevsInVol[nVol]--;
#endif
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief This function reads 1 page from Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[out] pMBuf : Memory buffer for main array of NAND flash
* @param[out] pSBuf : Memory buffer for spare array of NAND flash
* @param[in] nFlag : Operation options such as ECC_ON, OFF
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read error return value
* @return FSR_LLD_PREV_READ_DISTURBANCE | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read disturbance error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark one function call of FSR_FND_Read() loads 1 page from
* @n Flex-OneNAND and moves data from DataRAM to pMBuf, pSBuf.
* @n In DDP environment,
* @n this version of read does not make use of load time.
* @n ( which is busy wait time, let's say it be 45us )
* @n instead, it waits till DataRAM gets filled.
* @n as a result, it does not give the best performance.
* @n To make use of die interleaving, use FSR_FND_ReadOptimal()
*
*/
PUBLIC INT32
FSR_FND_Read(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag)
{
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT32 nLLDFlag;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
do
{
nLLDFlag = ~FSR_LLD_FLAG_CMDIDX_MASK & nFlag;
nLLDRe = FSR_FND_ReadOptimal(nDev,
nPbn, nPgOffset,
pMBuf, pSBuf,
FSR_LLD_FLAG_1X_LOAD | nLLDFlag);
if (FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS)
{
break;
}
nLLDRe = FSR_FND_ReadOptimal(nDev,
nPbn, nPgOffset,
pMBuf, pSBuf,
FSR_LLD_FLAG_TRANSFER | nLLDFlag);
if (FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS)
{
break;
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return nLLDRe;
}
/**
* @brief This function reads 1 page from Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ )
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[out] pMBuf : Memory buffer for main array of NAND flash
* @param[out] pSBuf : Memory buffer for spare array of NAND flash
* @param[in] nFlag : Operation options such as ECC_ON, OFF
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read error return value
* @return FSR_LLD_PREV_READ_DISTURBANCE | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read disturbance error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark LLD_Open() links gpfReadOptimal to _ReadOptimalWithSLoad() or
* @n _ReadOptimalWithNonSLoad(), which depends on whether target
* @n supports syncronous read or not.
* @n because, superload needs data transferred in sync mode.
* @n _ReadOptimalWithSLoad() does not work in Async mode.
*
*/
PUBLIC INT32
FSR_FND_ReadOptimal(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag)
{
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
do
{
#if defined (FSR_LLD_STRICT_CHK)
nLLDRe = _StrictChk(nDev, nPbn, nPgOffset);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
nLLDRe = gpfReadOptimal(nDev, nPbn, nPgOffset, pMBuf, pSBuf, nFlag);
} while (0);
/* FSR_FND_Open() assigns appropriate function pointer to gpfReadOptimal.
* it depends on the Read Mode (whether it supports syncronous read or not).
*/
return nLLDRe;
}
/**
* @brief this function reads data from Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[out] pMBuf : Memory buffer for main array of NAND flash
* @param[out] pSBuf : Memory buffer for spare array of NAND flash
* @param[in] nFlag : Operation options such as ECC_ON, OFF
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read error return value
* @return FSR_LLD_PREV_READ_DISTURBANCE | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read disturbance error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark use of PLOAD flag issue superload command.
*
*/
PRIVATE INT32
_ReadOptWithSLoad(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
FlexONDShMem *pstFNDShMem = gpstFNDShMem[nDev];
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
UINT32 nCmdIdx;
/* start sector offset from the start */
UINT32 nStartOffset;
/* end sector offset from the end */
UINT32 nEndOffset;
UINT32 nDie;
UINT32 nFlushOpCaller;
#if defined (FSR_LLD_STATISTICS)
UINT32 nBytesTransferred = 0;
#endif /* #if defined (FSR_LLD_STATISTICS) */
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nSysConf1;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nPbn:%d, nPgOffset:%d, pMBuf:0x%08x, pSBuf:0x%08x, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nPbn, nPgOffset, pMBuf, pSBuf, nFlag));
do
{
nCmdIdx = (nFlag & FSR_LLD_FLAG_CMDIDX_MASK) >> FSR_LLD_FLAG_CMDIDX_BASEBIT;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
nFlushOpCaller = FSR_FND_PREOP_READ << FSR_FND_FLUSHOP_CALLER_BASEBIT;
if ((nCmdIdx == FSR_LLD_FLAG_1X_LOAD) ||
(nCmdIdx == FSR_LLD_FLAG_1X_PLOAD)||
(nCmdIdx == FSR_LLD_FLAG_LSB_RECOVERY_LOAD))
{
/* Flex-OneNAND doesn't support read interleaving,
therefore, wait until interrupt status is ready for both die.
if device is DDP. */
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x01),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* set DFS & FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) |
(nPbn & pstFNDCxt->nFBAMask)));
/* set FPA (Flash Page Address) */
FND_WRITE(pstFOReg->nStartAddr8,
(UINT16) (nPgOffset << pstFNDCxt->nFPASelSft));
/* set Start Buffer Register */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
if ((nFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
nSysConf1 = FND_READ(pstFOReg->nSysConf1);
/* if ECC is disabled, enable */
if (nSysConf1 & FSR_FND_CONF1_ECC_OFF)
{
FND_CLR(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_ON);
}
}
else
{
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
FND_WRITE(pstFOReg->nCmd, (UINT16) gnLoadCmdArray[nCmdIdx]);
#if defined (FSR_LLD_STATISTICS)
if (gnLoadCmdArray[nCmdIdx] == FSR_FND_CMD_SUPERLOAD)
{
_AddFNDStatLoad(nDev,
nDie,
nPbn,
FSR_FND_STAT_PLOAD);
}
else
{
_AddFNDStatLoad(nDev,
nDie,
nPbn,
FSR_FND_STAT_NORMAL_CMD);
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
} /* if ((nCmdIdx == FSR_LLD_FLAG_1X_LOAD) | (nCmdIdx == FSR_LLD_FLAG_1X_PLOAD)) */
/* transfer data */
if (nFlag & FSR_LLD_FLAG_TRANSFER)
{
if (nCmdIdx == FSR_LLD_FLAG_NO_LOADCMD)
{
/* Flex-OneNAND doesn't support read interleaving,
therefore, wait until interrupt status is ready for both die.
if device is DDP. */
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x1),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
}
if (pMBuf != NULL)
{
/* _ReadMain() can load continuous sectors within a page. */
nStartOffset = (nFlag & FSR_LLD_FLAG_1ST_SCTOFFSET_MASK)
>> FSR_LLD_FLAG_1ST_SCTOFFSET_BASEBIT;
nEndOffset = (nFlag & FSR_LLD_FLAG_LAST_SCTOFFSET_MASK)
>> FSR_LLD_FLAG_LAST_SCTOFFSET_BASEBIT;
_ReadMain(pMBuf + nStartOffset * FSR_FND_SECTOR_SIZE,
&(pstFOReg->nDataMB00[0]) + nStartOffset * FSR_FND_SECTOR_SIZE,
(pstFNDSpec->nSctsPerPG - nStartOffset - nEndOffset) * FSR_FND_SECTOR_SIZE,
pstFNDCxt->pTempBuffer);
#if defined (FSR_LLD_STATISTICS)
nBytesTransferred += FSR_FND_SECTOR_SIZE *
(pstFNDSpec->nSctsPerPG - nStartOffset - nEndOffset);
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
if ((pSBuf != NULL) && (nFlag & FSR_LLD_FLAG_USE_SPAREBUF))
{
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
_ReadSpare(pstFNDCxt, (FSRSpareBuf *) pSBuf, &(pstFOReg->nDataSB00[0]));
}
else
{
/* when dumpping NAND Image,
* _ReadMain() reads the whole spare area
*/
_ReadMain((UINT8 *) pSBuf,
&(pstFOReg->nDataSB00[0]),
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct,
pstFNDCxt->pTempBuffer);
}
#if defined (FSR_LLD_STATISTICS)
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
nBytesTransferred += (FSR_SPARE_BUF_SIZE_4KB_PAGE);
}
else
{
nBytesTransferred +=
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct;
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
/******************CAUTION ***************************************
* COMPILER MUST NOT REMOVE THIS CODE *
*****************************************************************
*/
if (nCmdIdx == FSR_LLD_FLAG_1X_PLOAD)
{
/* Read at least 4 bytes to the end of the spare area,
* Or Superload will not work properly.
* 2 lines below trigger the load from page buffer to DataRAM
* [[ CAUTION ]]
* SHOULD NOT be issued at the address of &pstFOReg->nDataSB13[0x0e]
*/
#if defined(FSR_ONENAND_EMULATOR)
/* Read at least 4 bytes to the end of the spare area,
* Or Superload will not work properly.
* 2 lines below trigger the load from page buffer to DataRAM
*/
*(UINT16 *) &(pstFNDCxt->pTempBuffer[0]) = FND_READ(*(UINT16 *) &pstFOReg->nDataSB13[0xC]);
*(UINT16 *) &(pstFNDCxt->pTempBuffer[2]) = FND_READ(*(UINT16 *) &pstFOReg->nDataSB13[0xE]);
#elif defined (FSR_MSM7200)
*(UINT32 *) &(pstFNDCxt->pTempBuffer[0]) = FND_READ(*(UINT16 *) &pstFOReg->nDataSB13[0xC]);
#else
*(UINT32 *) &(pstFNDCxt->pTempBuffer[0]) = *(UINT32 *) &pstFOReg->nDataSB13[0x0C];
#endif
}
#if defined (FSR_LLD_STATISTICS)
if (nCmdIdx == FSR_LLD_FLAG_1X_PLOAD)
{
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_RD_TRANS,
nBytesTransferred,
FSR_FND_STAT_PLOAD);
}
else
{
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_RD_TRANS,
nBytesTransferred,
FSR_FND_STAT_NORMAL_CMD);
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
} /* if (nFlag & FSR_LLD_FLAG_TRANSFER) */
} while (0);
/*
if transfer only operation, nPreOp[nDie] should be FSR_OND_PREOP_NONE.
----------------------------------------------------------------------
FSR_FND_FlushOp() wait read interrupt if nPreOp is FSR_FND_PREOP_READ.
But, if this function only has FSR_LLD_FLAG_TRANSFER, there is no read interrupt.
Therefore, In order to avoid infinite loop, nPreOp is FSR_FND_PREOP_NONE.
----------------------------------------------------------------------
*/
if ((nCmdIdx == FSR_LLD_FLAG_NO_LOADCMD) &&
(nFlag & FSR_LLD_FLAG_TRANSFER))
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_NONE;
}
else
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_READ;
}
pstFNDShMem->nPreOpPbn[nDie] = (UINT16) nPbn;
pstFNDShMem->nPreOpPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDShMem->nPreOpFlag[nDie] = nFlag;
#if defined (FSR_LLD_LOGGING_HISTORY)
_AddLog(nDev, nDie);
#endif
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief This function is for Asyncronous mode Read
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[out] pMBuf : Memory buffer for main array of NAND flash
* @param[out] pSBuf : Memory buffer for spare array of NAND flash
* @param[in] nFlag : Operation options such as ECC_ON, OFF
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read error return value
* @return FSR_LLD_PREV_READ_DISTURBANCE | {FSR_LLD_1STPLN_CURR_ERROR}
* @n previous read disturbance error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark This function does not make use of SUPERLOAD command
* @n instead it treats PLOAD flag with normal load command
*
*/
PRIVATE INT32
_ReadOptWithNonSLoad(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
FlexONDShMem *pstFNDShMem= gpstFNDShMem[nDev];
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
UINT32 nCmdIdx;
/* start sector offset from the start */
UINT32 nStartOffset;
/* end sector offset from the end */
UINT32 nEndOffset;
UINT32 nDie;
UINT32 nFlushOpCaller;
#if defined (FSR_LLD_STATISTICS)
UINT32 nBytesTransferred = 0;
#endif /* #if defined (FSR_LLD_STATISTICS) */
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nSysConf1;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nPbn:%d, nPgOffset:%d, pMBuf:0x%08x, pSBuf:0x%08x, nFlag:0x%08x)\r\n"),
__FSR_FUNC__ , nDev, nPbn, nPgOffset, pMBuf, pSBuf, nFlag));
do
{
nCmdIdx = (nFlag & FSR_LLD_FLAG_CMDIDX_MASK)
>> FSR_LLD_FLAG_CMDIDX_BASEBIT;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
nFlushOpCaller = FSR_FND_PREOP_READ << FSR_FND_FLUSHOP_CALLER_BASEBIT;
/* transfer data */
if (nFlag & FSR_LLD_FLAG_TRANSFER)
{
/* OneNAND doesn't support read interleaving,
therefore, wait until interrupt status is ready for both die.
if device is DDP. */
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x1),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16) (nDie << FSR_FND_DBS_BASEBIT));
if (pMBuf != NULL)
{
/* _ReadMain() can load continuous sectors within a page.*/
nStartOffset = (nFlag & FSR_LLD_FLAG_1ST_SCTOFFSET_MASK)
>> FSR_LLD_FLAG_1ST_SCTOFFSET_BASEBIT;
nEndOffset = (nFlag & FSR_LLD_FLAG_LAST_SCTOFFSET_MASK)
>> FSR_LLD_FLAG_LAST_SCTOFFSET_BASEBIT;
_ReadMain(pMBuf + nStartOffset * FSR_FND_SECTOR_SIZE,
&(pstFOReg->nDataMB00[0]) + nStartOffset * FSR_FND_SECTOR_SIZE,
(pstFNDSpec->nSctsPerPG - nStartOffset - nEndOffset) * FSR_FND_SECTOR_SIZE,
pstFNDCxt->pTempBuffer);
#if defined (FSR_LLD_STATISTICS)
nBytesTransferred += FSR_FND_SECTOR_SIZE *
(pstFNDSpec->nSctsPerPG - nStartOffset - nEndOffset);
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
if ((pSBuf != NULL) && (nFlag & FSR_LLD_FLAG_USE_SPAREBUF))
{
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
_ReadSpare(pstFNDCxt, (FSRSpareBuf *) pSBuf, &(pstFOReg->nDataSB00[0]));
}
else
{
/* when dumpping NAND Image,
* _ReadMain() reads the whole spare area
*/
_ReadMain((UINT8 *) pSBuf,
&(pstFOReg->nDataSB00[0]),
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct,
pstFNDCxt->pTempBuffer);
}
#if defined (FSR_LLD_STATISTICS)
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
nBytesTransferred += (FSR_SPARE_BUF_SIZE_4KB_PAGE);
}
else
{
nBytesTransferred +=
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct;
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
#if defined (FSR_LLD_STATISTICS)
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_RD_TRANS,
nBytesTransferred,
FSR_FND_STAT_NORMAL_CMD);
#endif /* #if defined (FSR_LLD_STATISTICS) */
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_NONE;
} /* if (nFlag & FSR_LLD_FLAG_TRANSFER) */
if ((nCmdIdx == FSR_LLD_FLAG_1X_LOAD) ||
(nCmdIdx == FSR_LLD_FLAG_1X_PLOAD) ||
(nCmdIdx == FSR_LLD_FLAG_LSB_RECOVERY_LOAD))
{
/* OneNAND doesn't support read interleaving,
therefore, wait until interrupt status is ready for both die.
if device is DDP. */
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x1),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* set DFS & FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) | (nPbn & pstFNDCxt->nFBAMask)));
/* set FPA (Flash Page Address) */
FND_WRITE(pstFOReg->nStartAddr8,
(UINT16) (nPgOffset << pstFNDCxt->nFPASelSft));
/* set Start Buffer Register */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
if ((nFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
nSysConf1 = FND_READ(pstFOReg->nSysConf1);
if (nSysConf1 & 0x0100)
{
FND_CLR(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_ON);
}
}
else
{
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
/* because SUPERLOAD is not working in Asynchronous Mode
* this version issue a normal load command (0x0000) for PLOAD flag
*/
FND_WRITE(pstFOReg->nCmd, (UINT16) gnLoadCmdArray[nCmdIdx]);
#if defined (FSR_LLD_STATISTICS)
_AddFNDStatLoad(nDev,
nDie,
nPbn,
FSR_FND_STAT_NORMAL_CMD);
#endif /* #if defined (FSR_LLD_STATISTICS) */
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_READ;
} /* if ((nCmdIdx == FSR_LLD_FLAG_1X_LOAD) | (nCmdIdx == FSR_LLD_FLAG_1X_PLOAD)) */
pstFNDShMem->nPreOpPbn[nDie] = (UINT16) nPbn;
pstFNDShMem->nPreOpPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDShMem->nPreOpFlag[nDie] = nFlag;
#if defined (FSR_LLD_LOGGING_HISTORY)
_AddLog(nDev, nDie);
#endif
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function reads data from main area of DataRAM
*
* @param[out] pDest : pointer to the buffer
* @param[in] pstSrc : pointer to the main area of DataRAM
* @param[in] nSize : # of bytes to read
* @param[in] pTempBuffer: temporary buffer for reading misaligned data
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark pTempBuffer is 4-byte aligned.
* @n the caller of _ReadMain() provides enough space for holding
* @n nSize bytes of data.
*
*/
PRIVATE VOID
_ReadMain( UINT8 *pDest,
volatile UINT8 *pSrc,
UINT32 nSize,
UINT8 *pTempBuffer)
{
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pDest: 0x%08x, pSrc: 0x%08x, pTempBuffer: 0x%08x)\r\n"),
__FSR_FUNC__, pDest, pSrc, pTempBuffer));
/* if pDest is not 4 byte aligned. */
if ((((UINT32) pDest & 0x3) != 0) || (nSize < FSR_FND_MIN_BULK_TRANS_SIZE))
{
TRANSFER_FROM_NAND(pTempBuffer, pSrc, nSize);
FSR_OAM_MEMCPY(pDest, pTempBuffer, nSize);
}
else /* when pDest is 4 byte aligned */
{
TRANSFER_FROM_NAND(pDest, pSrc, nSize);
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function reads data from spare area of DataRAM
*
* @param[out] pstDest : pointer to the host buffer
* @param[in] pSrc : pointer to the spare area of DataRAM
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark this function reads from spare area of 1 page.
*
*/
PRIVATE VOID
_ReadSpare( FlexONDCxt *pstFNDCxt,
FSRSpareBuf *pstDest,
volatile UINT8 *pSrc)
{
UINT32 nIdx;
UINT32 nIdx1;
UINT32 nSrcOffset;
volatile UINT16 *pSrc16;
UINT16 *pDest16;
FlexONDSpec *pstFNDSpec;
UINT32 nTransferSize;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pstDest: 0x%08x, pSrc: 0x%08x)\r\n"),
__FSR_FUNC__, pstDest, pSrc));
pstFNDSpec = pstFNDCxt->pstFNDSpec;
nTransferSize = pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct - 2 * sizeof(UINT32);
TRANSFER_FROM_NAND(pstFNDCxt->pSpareBuffer, pSrc, nTransferSize);
pSrc16 = (UINT16 *) pstFNDCxt->pSpareBuffer;
pDest16 = (UINT16 *) pstDest->pstSpareBufBase;
FSR_ASSERT(((UINT32) pstDest & 0x01) == 0);
nSrcOffset = 0;
/* read spare base */
for (nIdx = 0; nIdx < (FSR_SPARE_BUF_BASE_SIZE / 2); nIdx++)
{
*pDest16++ = *pSrc16++;
if (++nSrcOffset == 0x3)
{
nSrcOffset = 0;
/* skip 10 bytes for H/W ECC area */
pSrc16 += FSR_FND_SPARE_HW_ECC_AREA;
}
}
for (nIdx1 = 0; nIdx1 < pstDest->nNumOfMetaExt; nIdx1++)
{
pDest16 = (UINT16 *) &(pstDest->pstSTLMetaExt[nIdx1]);
for (nIdx = 0; nIdx < (FSR_SPARE_BUF_EXT_SIZE / 2); nIdx++)
{
*pDest16++ = *pSrc16++;
if (++nSrcOffset == 0x3)
{
nSrcOffset = 0;
/* skip 10 bytes for H/W ECC area */
pSrc16 += FSR_FND_SPARE_HW_ECC_AREA;
}
}
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function writes data into Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[in] pMBuf : Memory buffer for main array of NAND flash
* @param[in] pSBuf : Memory buffer for spare array of NAND flash
* @param[in] nFlag : Operation options such as ECC_ON, OFF
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n error for normal program
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_PREV_ERROR}
* @n error for cache program
* @return FSR_LLD_WR_PROTECT_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n write protetion error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_Write(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
FlexONDShMem *pstFNDShMem= NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt = NULL;
#endif
UINT32 nCmdIdx;
UINT32 nBBMMetaIdx;
UINT32 nDie;
UINT32 nFlushOpCaller;
#if defined (FSR_LLD_STATISTICS)
UINT32 nBytesTransferred = 0;
#endif /* #if defined (FSR_LLD_STATISTICS) */
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nWrProtectStat;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nPbn:%d, nPgOffset:%d, pMBuf: 0x%08x, pSBuf: 0x%08x, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nPbn, nPgOffset, pMBuf, pSBuf, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
nLLDRe = _StrictChk(nDev, nPbn, nPgOffset);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDShMem = gpstFNDShMem[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
nCmdIdx = (nFlag & FSR_LLD_FLAG_CMDIDX_MASK) >> FSR_LLD_FLAG_CMDIDX_BASEBIT;
nDie = (nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft));
nFlushOpCaller = FSR_FND_PREOP_PROGRAM << FSR_FND_FLUSHOP_CALLER_BASEBIT;
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* Write Data Into DataRAM */
if (pMBuf != NULL)
{
_WriteMain(&(pstFOReg->nDataMB00[0]),
pMBuf,
pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE);
#if defined (FSR_LLD_STATISTICS)
nBytesTransferred += pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE;
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
if (pMBuf == NULL && pSBuf != NULL)
{
if((nFlag & FSR_LLD_FLAG_BACKUP_DATA) != FSR_LLD_FLAG_BACKUP_DATA)
{
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0xFF, sizeof(pstFOReg->nDataMB00) * pstFNDSpec->nSctsPerPG);
TRANSFER_TO_NAND(pstFOReg->nDataMB00,
pstFNDCxt->pTempBuffer,
sizeof(pstFOReg->nDataMB00) * pstFNDSpec->nSctsPerPG);
}
}
if (pSBuf != NULL)
{
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_ON)
{
_WriteMain(&(pstFOReg->nDataSB00[0]),
(UINT8 *) pSBuf,
pstFNDSpec->nSparePerSct * pstFNDSpec->nSctsPerPG);
}
else
{
/* if FSR_LLD_FLAG_BBM_META_BLOCK of nFlag is set,
* write nBMLMetaBase0 of FSRSpareBuf with 0xA5A5
*/
nBBMMetaIdx = (nFlag & FSR_LLD_FLAG_BBM_META_MASK) >>
FSR_LLD_FLAG_BBM_META_BASEBIT;
pSBuf->pstSpareBufBase->nBMLMetaBase0 = gnBBMMetaValue[nBBMMetaIdx];
/* _WriteSpare does not care about bad mark which is written at
* the first word of sector 0 of the spare area
* bad mark is written individually.
*/
_WriteSpare(pstFNDCxt, &(pstFOReg->nDataSB00[0]), pSBuf, nFlag);
}
#if defined (FSR_LLD_STATISTICS)
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
nBytesTransferred += (FSR_SPARE_BUF_SIZE_4KB_PAGE);
}
else
{
nBytesTransferred +=
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct;
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
if (pMBuf != NULL && pSBuf == NULL)
{
if((nFlag & FSR_LLD_FLAG_BACKUP_DATA) != FSR_LLD_FLAG_BACKUP_DATA)
{
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0xFF, sizeof(pstFOReg->nDataSB00) * pstFNDSpec->nSctsPerPG);
TRANSFER_TO_NAND(pstFOReg->nDataSB00,
pstFNDCxt->pTempBuffer,
sizeof(pstFOReg->nDataSB00) * pstFNDSpec->nSctsPerPG);
}
}
if ((nFlag & FSR_LLD_FLAG_DUMP_MASK) == FSR_LLD_FLAG_DUMP_OFF)
{
/* write bad mark of the block
* bad mark is not written in _WriteSpare()
*/
FND_WRITE(*(volatile UINT16 *) &pstFOReg->nDataSB00[0],
gnBadMarkValue[(nFlag & FSR_LLD_FLAG_BADMARK_MASK) >> FSR_LLD_FLAG_BADMARK_BASEBIT]);
}
#if defined (FSR_LLD_WAIT_ALLDIE_PGM_READY)
/* In case of DDP, wait the other die ready.
* When there is a cache program going on the other die,
* setting the address register leads to the problem.
* that is.. data under programming will be written to the newly set address.
*/
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x01),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
#endif
/* set DFS, FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16)((nDie << FSR_FND_DFS_BASEBIT) | (nPbn & pstFNDCxt->nFBAMask)));
#if defined(FSR_LLD_WAIT_WR_PROTECT_STAT)
/* wait until lock bit is set */
do
{
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
} while (nWrProtectStat == (UINT16) 0x0000);
#else
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
#endif
/******************CAUTION ***************************************
* when cache program (0x007F) is performed on a locked block *
* Flex-OneNAND automatically resets itself *
* so makes sure that cache program command is not issued on a *
* locked block *
*****************************************************************
*/
/* write protection can be checked when DBS & FBA is set */
if ((nWrProtectStat & FSR_LLD_BLK_STAT_MASK) != FSR_LLD_BLK_STAT_UNLOCKED)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line \r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn #%d, Pg #%d is write protected\r\n"),
nPbn, nPgOffset));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_WR_PROTECT_ERROR | FSR_LLD_1STPLN_CURR_ERROR);
break;
}
/* set Start Page Address (FPA) */
FND_WRITE(pstFOReg->nStartAddr8,
(UINT16) (nPgOffset << pstFNDCxt->nFPASelSft));
/* set Start Buffer Register */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
if ((nFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
FND_CLR(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_ON);
}
else
{
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
/* issue command */
FND_WRITE(pstFOReg->nCmd, (UINT16) gnPgmCmdArray[nCmdIdx]);
#if defined(FSR_LLD_USE_CACHE_PGM)
if (gnPgmCmdArray[nCmdIdx] == FSR_FND_CMD_CACHEPGM)
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_CACHE_PGM;
pstFNDCxt->bIsPreCmdCache[nDie] = TRUE32;
}
else
{
if (pstFNDCxt->bIsPreCmdCache[nDie] == TRUE32)
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_CACHE_PGM;
}
else
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_PROGRAM;
}
pstFNDCxt->bIsPreCmdCache[nDie] = FALSE32;
}
#else
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_PROGRAM;
#endif /* #if defined(FSR_LLD_USE_CACHE_PGM) */
pstFNDShMem->nPreOpPbn[nDie] = (UINT16) nPbn;
pstFNDShMem->nPreOpPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDShMem->nPreOpFlag[nDie] = nFlag;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
pstFNDSharedCxt->nPrevFSRMode[nDie] = nFlag & FSR_LLD_FLAG_READ_ONLY;
pstFNDSharedCxt->nHostLLDOp[nDie] = pstFNDShMem->nPreOp[nDie];
pstFNDSharedCxt->nHostLLDPbn[nDie] = (UINT16) nPbn;
pstFNDSharedCxt->nHostLLDPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDSharedCxt->nHostLLDFlag[nDie] = nFlag;
#endif
#if defined (FSR_LLD_LOGGING_HISTORY)
_AddLog(nDev, nDie);
#endif
#if defined (FSR_LLD_STATISTICS)
if (gnPgmCmdArray[nCmdIdx] == FSR_FND_CMD_CACHEPGM)
{
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_WR_TRANS,
nBytesTransferred,
FSR_FND_STAT_CACHE_PGM);
_AddFNDStatPgm(nDev,
nDie,
nPbn,
nPgOffset,
FSR_FND_STAT_CACHE_PGM);
}
else
{
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_WR_TRANS,
nBytesTransferred,
FSR_FND_STAT_NORMAL_CMD);
_AddFNDStatPgm(nDev,
nDie,
nPbn,
nPgOffset,
FSR_FND_STAT_NORMAL_CMD);
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function writes data into main area of DataRAM
*
* @param[in] pDest : pointer to the main area of DataRAM
* @param[in] pSrc : pointer to the buffer
* @param[in] nSize : the number of bytes to write
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark pDest is a pointer to main DataRAM
* @n nSize is the number of bytes to write
*
*/
PRIVATE VOID
_WriteMain(volatile UINT8 *pDest,
UINT8 *pSrc,
UINT32 nSize)
{
UINT32 nCnt;
volatile UINT16 *pTgt16;
UINT16 nReg;
FlexONDCxt *pstFNDCxt = NULL;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pDest: 0x%08x, pSrc: 0x%08x, nSize: %d)\r\n"),
__FSR_FUNC__, pDest, pSrc, nSize));
pstFNDCxt = gpstFNDCxt[0];
/* if nSize is not multiple of 4, memcpy is not guaranteed.
* although here only checks that nSize is multiple of 4,
* nSize should not be an odd.
*/
if (((nSize & 0x3) != 0) &&
(((UINT32) pSrc & 0x3) != 0) &&
(nSize >= FSR_FND_MIN_BULK_TRANS_SIZE))
{
FSR_OAM_MEMCPY(pstFNDCxt->pTempBuffer, pSrc, nSize);
TRANSFER_TO_NAND(pDest, pstFNDCxt->pTempBuffer, nSize);
}
else if (((nSize & 0x3) != 0) ||
(((UINT32) pSrc & 0x3) != 0) ||
(nSize < FSR_FND_MIN_BULK_TRANS_SIZE))
{
pTgt16 = (volatile UINT16 *) pDest;
/* copy it by word, so loop it for nSize/2 */
nSize = nSize >> 1;
for (nCnt = 0; nCnt < nSize; nCnt++)
{
#if defined (FSR_LLD_BIG_ENDIAN)
nReg = *pSrc++ << 8;
nReg |= *pSrc++;
#else /* #if defined (FSR_LLD_BIG_ENDIAN) */
nReg = *pSrc++;
nReg |= *pSrc++ << 8;
#endif /* #if defined (FSR_LLD_BIG_ENDIAN) */
FND_WRITE(*pTgt16++, nReg);
}
}
else
{
/* nSize is the number of bytes to transfer */
TRANSFER_TO_NAND(pDest, pSrc, nSize);
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function writes FSRSpareBuf into spare area of DataRAM
*
* @param[in] pDest : pointer to the spare area of DataRAM
* @param[in] pstSrc : pointer to the structure, FSRSpareBuf
* @param[in] nFlag : whether to write spare buffer onto DataRAM or not.
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark this function writes FSRSpareBuf over spare area of 1 page
*
*/
PRIVATE VOID
_WriteSpare( FlexONDCxt *pstFNDCxt,
volatile UINT8 *pDest,
FSRSpareBuf *pstSrc,
UINT32 nFlag)
{
UINT32 nNumOfSct;
UINT32 nMetaIdx;
UINT8 anSpareBuf[FSR_SPARE_BUF_BASE_SIZE + 2 * sizeof(FSRSpareBufExt)];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
UINT32 nTransferSize;
UINT8 *pSrc8;
UINT8 *pTempBuffer8;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pDest: 0x%08x, pstSrc: 0x%08x)\r\n"),
__FSR_FUNC__, pDest, pstSrc));
/* when pstSrc->nNumOfMetaExt is 0, fill the rest of spare area with 0xFF */
FSR_OAM_MEMSET(&anSpareBuf[0], 0xFF, sizeof(anSpareBuf));
if (nFlag & FSR_LLD_FLAG_USE_SPAREBUF)
{
FSR_OAM_MEMCPY(&anSpareBuf[0], &pstSrc->pstSpareBufBase[0], FSR_SPARE_BUF_BASE_SIZE);
for (nMetaIdx = 0; nMetaIdx < pstSrc->nNumOfMetaExt; nMetaIdx++)
{
FSR_OAM_MEMCPY(&anSpareBuf[FSR_SPARE_BUF_BASE_SIZE + nMetaIdx * FSR_SPARE_BUF_EXT_SIZE],
&pstSrc->pstSTLMetaExt[nMetaIdx],
FSR_SPARE_BUF_EXT_SIZE);
}
}
pSrc8 = &anSpareBuf[0];
pTempBuffer8 = pstFNDCxt->pSpareBuffer;
nNumOfSct = sizeof(anSpareBuf) / FSR_FND_SPARE_USER_AREA;
do
{
FSR_OAM_MEMCPY(pTempBuffer8, pSrc8, FSR_FND_SPARE_USER_AREA);
pTempBuffer8 += pstFNDSpec->nSparePerSct;
pSrc8 += FSR_FND_SPARE_USER_AREA;
} while (--nNumOfSct > 0);
pstFNDSpec = pstFNDCxt->pstFNDSpec;
nTransferSize = pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct;
TRANSFER_TO_NAND(pDest, pstFNDCxt->pSpareBuffer, nTransferSize);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function erase a block of Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] pnPbn : array of blocks, not necessarilly consecutive.
* @n multi block erase will be supported in the future
* @param[in] nFlag : FSR_LLD_FLAG_1X_ERASE
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_PREV_ERASE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n erase error for previous erase operation
* @return FSR_LLD_WR_PROTECT_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n protection error for previous erase operation
*
* @author NamOh Hwang
* @version 1.0.0
* @remark as of now, supports only single plane, one block erase
* @ Pbn is consecutive numbers within the device
* @n i.e. for DDP device, Pbn for 1st block in 2nd chip is not 0
* @n it is one more than the last block number in 1st chip
*
*/
PUBLIC INT32
FSR_FND_Erase(UINT32 nDev,
UINT32 *pnPbn,
UINT32 nNumOfBlks,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
FlexONDShMem *pstFNDShMem= NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt;
#endif
UINT32 nCmdIdx;
UINT32 nDie;
UINT32 nPbn = *pnPbn;
UINT32 nFlushOpCaller;
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nWrProtectStat;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, *pnPbn:%d, nNumOfBlks:%d)\r\n"),
__FSR_FUNC__, nDev, *pnPbn, nNumOfBlks));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, *pnPbn:%d, nNumOfBlks:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, *pnPbn, nNumOfBlks, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"), nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDShMem= gpstFNDShMem[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
/* to support multi block erase,
* function parameter pnPbn is defined as an array
* though multi block erase is not supported yet.
* nNumOfBlks can have a value of 1 for now.
*/
FSR_ASSERT(nNumOfBlks == 1);
#if defined (FSR_LLD_STRICT_CHK)
if (nPbn >= pstFNDSpec->nNumOfBlks)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, *pnPbn:%d, nNumOfBlks:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, *pnPbn, nNumOfBlks, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn:%d is invalid\r\n"), nPbn));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
nFlushOpCaller = FSR_FND_PREOP_ERASE << FSR_FND_FLUSHOP_CALLER_BASEBIT;
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
/* WARNING : DO NOT change address setting sequence
1. set DBS
2. set FBA */
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* set DFS, FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16)((nDie << FSR_FND_DFS_BASEBIT) | (nPbn & pstFNDCxt->nFBAMask)));
#if defined(FSR_LLD_WAIT_WR_PROTECT_STAT)
/* wait until lock bit is set */
do
{
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
} while (nWrProtectStat == (UINT16) 0x0000);
#else
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
#endif
/* write protection can be checked at this point */
if ((nWrProtectStat & FSR_LLD_BLK_STAT_MASK) != FSR_LLD_BLK_STAT_UNLOCKED)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, *pnPbn:%d, nNumOfBlks:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, *pnPbn, nNumOfBlks, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn #%d is write protected\r\n"), nPbn));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_WR_PROTECT_ERROR | FSR_LLD_1STPLN_CURR_ERROR);
break;
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
nCmdIdx = (nFlag & FSR_LLD_FLAG_CMDIDX_MASK) >> FSR_LLD_FLAG_CMDIDX_BASEBIT;
FND_WRITE(pstFOReg->nCmd, (UINT16) gnEraseCmdArray[nCmdIdx]);
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_ERASE;
pstFNDShMem->nPreOpPbn[nDie] = (UINT16) nPbn;
pstFNDShMem->nPreOpPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpFlag[nDie] = nFlag;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
pstFNDSharedCxt->nPrevFSRMode[nDie] = nFlag & FSR_LLD_FLAG_READ_ONLY;
pstFNDSharedCxt->nHostLLDOp[nDie] = FSR_FND_PREOP_ERASE;
pstFNDSharedCxt->nHostLLDPbn[nDie] = (UINT16) nPbn;
pstFNDSharedCxt->nHostLLDPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDSharedCxt->nHostLLDFlag[nDie] = nFlag;
#endif
#if defined (FSR_LLD_LOGGING_HISTORY)
_AddLog(nDev, nDie);
#endif
#if defined (FSR_LLD_STATISTICS)
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_ERASE,
0,
FSR_FND_STAT_NORMAL_CMD);
#endif /* #if defined (FSR_LLD_STATISTICS) */
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function copybacks 1 page.
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] pstCpArg : pointer to the structure LLDCpBkArg
* @param[in] nFlag : FSR_LLD_FLAG_1X_CPBK_LOAD,
* @n FSR_LLD_FLAG_1X_CPBK_PROGRAM
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n uncorrectable read error for previous read operation
* @return FSR_LLD_PREV_READ_DISTURBANCE | {FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_PREV_ERROR}
* @n write error for previous write operation
* @return FSR_LLD_WR_PROTECT_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n write protetion error return value
*
* @author NamOh Hwang
* @version 1.0.0
* @remark this function loads data from Flex-OneNAND,
* @n and randomly writes data into DataRAM of Flex-OneNAND
* @n and program back into Flex-OneNAND
*
*/
PUBLIC INT32
FSR_FND_CopyBack(UINT32 nDev,
LLDCpBkArg *pstCpArg,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
FlexONDShMem *pstFNDShMem= NULL;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt = NULL;
#endif
volatile FlexOneNANDReg *pstFOReg = NULL;
LLDRndInArg *pstRIArg; /* random in argument */
UINT32 nCmdIdx;
UINT32 nCnt;
UINT32 nPgOffset = 0;
UINT32 nDie = 0;
UINT32 nPbn = 0;
UINT32 nRndOffset = 0;
UINT32 nFlushOpCaller;
BOOL32 bSpareBufRndIn;
FSRSpareBuf stSpareBuf;
FSRSpareBufBase stSpareBufBase;
FSRSpareBufExt stSpareBufExt[FSR_MAX_SPARE_BUF_EXT];
#if defined (FSR_LLD_STATISTICS)
UINT32 nBytesTransferred = 0;
#endif /* #if defined (FSR_LLD_STATISTICS) */
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nSysConf1;
UINT16 nWrProtectStat;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nFlag));
do
{
FSR_OAM_MEMSET(&stSpareBuf, 0x00, sizeof(FSRSpareBuf));
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
if (pstCpArg == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, pstCpArg:0x%08x, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, pstCpArg, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstCpArg is NULL\r\n")));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDShMem= gpstFNDShMem[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
nCmdIdx = (nFlag & FSR_LLD_FLAG_CMDIDX_MASK) >> FSR_LLD_FLAG_CMDIDX_BASEBIT;
if (nCmdIdx == FSR_LLD_FLAG_1X_CPBK_LOAD)
{
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nSrcPbn:%d, nSrcPg:%d, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, pstCpArg->nSrcPbn, pstCpArg->nSrcPgOffset, nFlag));
/* load phase of copyback() only checks the source block & page
* offset. For BML does not fill the destination block & page
* offset at this phase
*/
nPbn = pstCpArg->nSrcPbn;
nPgOffset = pstCpArg->nSrcPgOffset;
#if defined (FSR_LLD_STRICT_CHK)
nLLDRe = _StrictChk(nDev, nPbn, nPgOffset);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
nFlushOpCaller = FSR_FND_PREOP_CPBK_LOAD << FSR_FND_FLUSHOP_CALLER_BASEBIT;
/* OneNAND doesn't support read interleaving,
therefore, wait until interrupt status is ready for both die.
if device is DDP. */
if (pstFNDSpec->nNumOfDies == FSR_MAX_DIES)
{
FSR_FND_FlushOp(nDev,
nFlushOpCaller | ((nDie + 0x1) & 0x1),
nFlag | FSR_LLD_FLAG_REMAIN_PREOP_STAT);
}
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
if ((FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS) &&
(FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_PREV_READ_DISTURBANCE))
{
break;
}
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* set DFS & FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) | (nPbn & pstFNDCxt->nFBAMask)));
/* set FPA (Flash Page Address) */
FND_WRITE(pstFOReg->nStartAddr8,
(UINT16) nPgOffset << pstFNDCxt->nFPASelSft);
/* set Start Buffer Register */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
if ((nFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
nSysConf1 = FND_READ(pstFOReg->nSysConf1);
if (nSysConf1 & FSR_FND_CONF1_ECC_OFF)
{
FND_CLR(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_ON);
}
}
else
{
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
FND_WRITE(pstFOReg->nCmd, (UINT16) gnCpBkCmdArray[nCmdIdx]);
#if defined (FSR_LLD_STATISTICS)
_AddFNDStatLoad(nDev,
nDie,
nPbn,
FSR_FND_STAT_NORMAL_CMD);
#endif /* #if defined (FSR_LLD_STATISTICS) */
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_CPBK_LOAD;
}
else if (nCmdIdx == FSR_LLD_FLAG_1X_CPBK_PROGRAM)
{
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nDstPbn:%d, nDstPg:%d, nRndInCnt:%d, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, pstCpArg->nDstPbn, pstCpArg->nDstPgOffset, pstCpArg->nRndInCnt, nFlag));
nPbn = pstCpArg->nDstPbn;
nPgOffset = pstCpArg->nDstPgOffset;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
#if defined (FSR_LLD_STRICT_CHK)
nLLDRe = _StrictChk(nDev, nPbn, nPgOffset);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
nFlushOpCaller = FSR_FND_PREOP_CPBK_PGM << FSR_FND_FLUSHOP_CALLER_BASEBIT;
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | nDie, nFlag);
if ((FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS) &&
(FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_PREV_READ_DISTURBANCE))
{
break;
}
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
bSpareBufRndIn = FALSE32;
for (nCnt = 0; nCnt < pstCpArg->nRndInCnt; nCnt++)
{
pstRIArg = pstCpArg->pstRndInArg + nCnt;
if (pstRIArg->nOffset >= FSR_LLD_CPBK_SPARE)
{
bSpareBufRndIn = TRUE32;
stSpareBuf.pstSpareBufBase = &stSpareBufBase;
stSpareBuf.nNumOfMetaExt = 2;
stSpareBuf.pstSTLMetaExt = &stSpareBufExt[0];
_ReadSpare(pstFNDCxt, &stSpareBuf, &pstFOReg->nDataSB00[0]);
break;
}
}
for (nCnt = 0; nCnt < pstCpArg->nRndInCnt; nCnt++)
{
pstRIArg = pstCpArg->pstRndInArg + nCnt;
/* in case copyback of spare area is requested */
if (pstRIArg->nOffset >= FSR_LLD_CPBK_SPARE)
{
nRndOffset = pstRIArg->nOffset - FSR_LLD_CPBK_SPARE;
if (nRndOffset >= (FSR_SPARE_BUF_BASE_SIZE))
{
/* random-in to FSRSpareBufExt[] */
nRndOffset -= (FSR_SPARE_BUF_BASE_SIZE * 1);
FSR_ASSERT((pstRIArg->nNumOfBytes + nRndOffset) <= (FSR_SPARE_BUF_EXT_SIZE * FSR_MAX_SPARE_BUF_EXT));
/* random-in to FSRSpareBuf */
FSR_OAM_MEMCPY((UINT8 *) &(stSpareBuf.pstSTLMetaExt[0]) + nRndOffset,
(UINT8 *) pstRIArg->pBuf,
pstRIArg->nNumOfBytes);
}
else
{
FSR_ASSERT((pstRIArg->nNumOfBytes + nRndOffset) <= FSR_SPARE_BUF_BASE_SIZE);
/* random-in to FSRSpareBuf */
FSR_OAM_MEMCPY((UINT8 *)(stSpareBuf.pstSpareBufBase) + nRndOffset,
(UINT8 *) pstRIArg->pBuf,
pstRIArg->nNumOfBytes);
}
#if defined (FSR_LLD_STATISTICS)
nBytesTransferred += pstRIArg->nNumOfBytes;
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
else
{
_WriteMain(&pstFOReg->nDataMB00[0] + pstRIArg->nOffset,
(UINT8 *) pstRIArg->pBuf,
pstRIArg->nNumOfBytes);
#if defined (FSR_LLD_STATISTICS)
nBytesTransferred += pstRIArg->nNumOfBytes;
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
}
if (bSpareBufRndIn == TRUE32)
{
_WriteSpare(pstFNDCxt, &pstFOReg->nDataSB00[0],
&stSpareBuf,
nFlag | FSR_LLD_FLAG_USE_SPAREBUF);
}
/* set DFS & FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) | (nPbn & pstFNDCxt->nFBAMask)));
#if defined(FSR_LLD_WAIT_WR_PROTECT_STAT)
do
{
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
} while (nWrProtectStat == (UINT16) 0x0000);
#else
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
#endif
/* write protection can be checked at this point */
if ((nWrProtectStat & FSR_LLD_BLK_STAT_MASK) != FSR_LLD_BLK_STAT_UNLOCKED)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDstPbn:%d, nDstPg:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, pstCpArg->nDstPbn,
pstCpArg->nDstPgOffset, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn:%d is write protected\r\n"), nPbn));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_WR_PROTECT_ERROR | FSR_LLD_1STPLN_CURR_ERROR);
break;
}
/* set FPA (Flash Page Address) */
FND_WRITE(pstFOReg->nStartAddr8,
(UINT16) nPgOffset << pstFNDCxt->nFPASelSft);
/* set Start Buffer Register */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
if ((nFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
FND_CLR(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_ON);
}
else
{
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
}
/* in case of non-blocking mode, interrupt should be enabled */
if (nFlag & FSR_LLD_FLAG_INT_MASK)
{
FSR_OAM_ClrNEnableInt(pstFNDCxt->nIntID);
}
else
{
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
}
FND_WRITE(pstFOReg->nCmd, (UINT16) gnCpBkCmdArray[nCmdIdx]);
#if defined (FSR_LLD_STATISTICS)
_AddFNDStat(nDev,
nDie,
FSR_FND_STAT_WR_TRANS,
nBytesTransferred,
FSR_FND_STAT_NORMAL_CMD);
_AddFNDStatPgm(nDev,
nDie,
nPbn,
nPgOffset,
FSR_FND_STAT_NORMAL_CMD);
#endif /* #if defined (FSR_LLD_STATISTICS) */
/* store the type of previous operation for the deferred check */
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_CPBK_PGM;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
pstFNDSharedCxt->nPrevFSRMode[nDie] = nFlag & FSR_LLD_FLAG_READ_ONLY;
pstFNDSharedCxt->nHostLLDOp[nDie] = FSR_FND_PREOP_CPBK_PGM;
pstFNDSharedCxt->nHostLLDPbn[nDie] = (UINT16) nPbn;
pstFNDSharedCxt->nHostLLDPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDSharedCxt->nHostLLDFlag[nDie] = nFlag;
#endif
}
pstFNDShMem->nPreOpPbn[nDie] = (UINT16) nPbn;
pstFNDShMem->nPreOpPgOffset[nDie] = (UINT16) nPgOffset;
pstFNDShMem->nPreOpFlag[nDie] = nFlag;
#if defined (FSR_LLD_LOGGING_HISTORY)
_AddLog(nDev, nDie);
#endif
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief This function checks whether block is bad or not
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : physical block number
* @param[in] nFlag : FSR_LLD_FLAG_1X_CHK_BADBLOCK
*
* @return FSR_LLD_INIT_GOODBLOCK
* @return FSR_LLD_INIT_BADBLOCK | {FSR_LLD_BAD_BLK_1STPLN}
* @return FSR_LLD_INVALID_PARAM
*
* @author NamOh Hwang
* @version 1.0.0
* @remark Pbn is consecutive numbers within the device
* @n i.e. for DDP device, Pbn for 1st block in 2nd chip is not 0
* @n it is one more than the last block number in 1st chip
*
*/
PUBLIC INT32
FSR_FND_ChkBadBlk(UINT32 nDev,
UINT32 nPbn,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
INT32 nLLDRe = FSR_LLD_INIT_GOODBLOCK;
UINT16 nDQ;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nPbn:%d, nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nPbn, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nPbn:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nPbn, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif
pstFNDCxt = gpstFNDCxt[nDev];
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
nLLDRe = FSR_FND_ReadOptimal(nDev, /* Device Number */
nPbn, /* Physical Block Number */
(UINT32) 0, /* page offset to be read */
(UINT8 *) NULL, /* Buffer pointer for Main area */
(FSRSpareBuf*) NULL, /* Buffer pointer for Spare area */
(UINT32) (FSR_LLD_FLAG_ECC_OFF | FSR_LLD_FLAG_1X_LOAD));/* flag */
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_INVALID_PARAM)
{
break;
}
nLLDRe = FSR_FND_ReadOptimal(nDev, /* Device Number */
nPbn, /* Physical Block Number */
(UINT32) 0, /* page offset to be read */
(UINT8 *) NULL, /* Buffer pointer for Main area */
(FSRSpareBuf *) NULL, /* Buffer pointer for Spare area */
(UINT32) (FSR_LLD_FLAG_ECC_OFF | FSR_LLD_FLAG_TRANSFER));/* flag */
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_INVALID_PARAM)
{
break;
}
nDQ = FND_READ(*(volatile UINT16 *) &pstFOReg->nDataSB00[0]);
if (nDQ != (UINT16) FSR_FND_VALID_BLK_MARK)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR | FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nPbn:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nPbn, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR | FSR_DBZ_LLD_INF,
(TEXT(" nPbn = %d is a bad block\r\n"), nPbn));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR | FSR_DBZ_LLD_INF,
(TEXT(" bad mark: 0x%04x\r\n"), nDQ));
nLLDRe = FSR_LLD_INIT_BADBLOCK | FSR_LLD_BAD_BLK_1STPLN;
}
else
{
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nPbn:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nPbn, nFlag, __LINE__));
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_INF,
(TEXT(" nPbn = %d is a good block\r\n"), nPbn));
nLLDRe = FSR_LLD_INIT_GOODBLOCK;
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function flush previous operation
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : 0 is for 1st die
* @n : 1 is for 2nd die
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_PREV_ERROR | FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_PREV_ERASE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_INVALID_PARAM
*
* @author NamOh Hwang
* @version 1.0.0
* @remark this function completes previous operation,
* @n and returns error for previous operation
* @n After calling series of FSR_FND_Write() or FSR_FND_Erase() or
* @n FSR_FND_CopyBack(), FSR_FND_FlushOp() needs to be called.
*
*/
PUBLIC INT32
FSR_FND_FlushOp(UINT32 nDev,
UINT32 nDie,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDShMem *pstFNDShMem= NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt;
#endif
UINT32 nIdx;
UINT32 nPrevOp;
#if !defined(FSR_OAM_RTLMSG_DISABLE)
UINT32 nPrevPbn;
UINT32 nPrevPgOffset;
#endif
UINT32 nPrevFlag;
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nMasterInt;
UINT16 nECCRes; /* ECC result */
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev: %d, nDieIdx: %d, nFlag: 0x%08x)\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"), nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDShMem= gpstFNDShMem[nDev];
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
pstFNDCxt->nFlushOpCaller = (UINT16) (nDie >> FSR_FND_FLUSHOP_CALLER_BASEBIT);
nDie = nDie & ~FSR_FND_FLUSHOP_CALLER_MASK;
nPrevOp = pstFNDShMem->nPreOp[nDie];
#if !defined(FSR_OAM_RTLMSG_DISABLE)
nPrevPbn = pstFNDShMem->nPreOpPbn[nDie];
nPrevPgOffset = pstFNDShMem->nPreOpPgOffset[nDie];
#endif
nPrevFlag = pstFNDShMem->nPreOpFlag[nDie];
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
/* mode has changed between Tiny FSR & normal FSR (linux only) */
if ((nFlag & FSR_LLD_FLAG_READ_ONLY) !=
(pstFNDSharedCxt->nPrevFSRMode[nDie] & FSR_LLD_FLAG_READ_ONLY))
{
if (nFlag & FSR_LLD_FLAG_READ_ONLY)
{
nPrevOp = pstFNDSharedCxt->nHostLLDOp[nDie];
#if !defined(FSR_OAM_RTLMSG_DISABLE)
nPrevPbn = pstFNDSharedCxt->nHostLLDPbn[nDie];
nPrevPgOffset = pstFNDSharedCxt->nHostLLDPgOffset[nDie];
#endif
nPrevFlag = pstFNDSharedCxt->nHostLLDFlag[nDie];
}
/* if Erase, Pgm Error was saved in Tiny FSR path,
* restore the error context, and return the error
*/
else /* if (!(nFlag & FSR_LLD_FLAG_READ_ONLY)) */
{
nLLDRe = _CheckErrorCxt(nDev, nDie, pstFNDCxt, pstFOReg);
nPrevOp = FSR_FND_PREOP_NONE;
}
}
#endif
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16) (nDie << FSR_FND_DBS_BASEBIT));
switch (nPrevOp)
{
case FSR_FND_PREOP_NONE:
/* DO NOT remove this code : 'case FSR_OND_PREOP_NONE:'
for compiler optimization */
break;
case FSR_FND_PREOP_READ:
case FSR_FND_PREOP_CPBK_LOAD:
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_READ_READY);
if ((nPrevFlag & FSR_LLD_FLAG_ECC_MASK) == FSR_LLD_FLAG_ECC_ON)
{
/* uncorrectable read error */
if (FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->nFlushOpCaller : %d\r\n"),
pstFNDCxt->nFlushOpCaller));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" ECC Status : Uncorrectable, CtrlReg=0x%04x\r\n"),
FND_READ(pstFOReg->nCtrlStat)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" at nDev:%d, nPbn:%d, nPgOffset:%d, nFlag:0x%08x\r\n"),
nDev, nPrevPbn, nPrevPgOffset, nPrevFlag));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_PREV_READ_ERROR |
FSR_LLD_1STPLN_CURR_ERROR);
}
/* correctable error */
else
{
nIdx = FSR_FND_MAX_ECC_STATUS_REG - 1;
do
{
nECCRes = FND_READ(pstFOReg->nEccStat[nIdx]);
if (nECCRes & FSR_FND_ECC_READ_DISTURBANCE)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->nFlushOpCaller : %d\r\n"),
pstFNDCxt->nFlushOpCaller));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" read disturbance at nPbn:%d, nPgOffset:%d, nFlag:0x%08x\r\n"),
nPrevPbn, nPrevPgOffset, nPrevFlag));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" Detected at ECC Register[%d]:0x%04x\r\n"),
nIdx, FND_READ(pstFOReg->nEccStat[nIdx])));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
#if defined(FSR_LLD_PE_TEST)
gnECCStat0 = FND_READ(pstFOReg->nEccStat[0]);
gnECCStat1 = FND_READ(pstFOReg->nEccStat[1]);
gnECCStat2 = FND_READ(pstFOReg->nEccStat[2]);
gnECCStat3 = FND_READ(pstFOReg->nEccStat[3]);
gnPbn = nPrevPbn;
gnPgOffset = nPrevPgOffset;
#endif
nLLDRe = FSR_LLD_PREV_READ_DISTURBANCE |
FSR_LLD_1STPLN_CURR_ERROR;
break;
}
/* else case
* no error, 1 ~ 2 bit error
*/
} while (nIdx-- > 0);
}
}
break;
case FSR_FND_PREOP_PROGRAM:
case FSR_FND_PREOP_CACHE_PGM:
case FSR_FND_PREOP_CPBK_PGM:
/* if the the current operation is cache program operation or
interleave cache program,
master interrupt & write interrupt bit should be checked.
even though the last command is program command.
-----------------------------------------------------------
cache program operation is as follows
1. cache_pgm
2. cache_pgm
3. program
*/
if (nPrevOp == FSR_FND_PREOP_CACHE_PGM)
{
nMasterInt = FSR_FND_INT_MASTER_READY;
}
else
{
nMasterInt = 0;
}
WAIT_FND_INT_STAT(pstFOReg, nMasterInt | FSR_FND_INT_WRITE_READY);
/* previous error check
* in case of Cache Program, Error bit shows the accumulative
* error status of Cache Program
* so if an error occurs this bit stays as fail
*/
if (FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->nFlushOpCaller : %d\r\n"),
pstFNDCxt->nFlushOpCaller));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" write() error: CtrlReg=0x%04x\r\n"),
FND_READ(pstFOReg->nCtrlStat) ));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" last write() call @ nDev = %d, nPbn = %d, nPgOffset = %d, nFlag:0x%08x\r\n"),
nDev, nPrevPbn, nPrevPgOffset, nPrevFlag));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = FSR_LLD_PREV_WRITE_ERROR;
if (!(FND_READ(pstFOReg->nCtrlStat) &
(FSR_FND_CURR_CACHEPGM_ERROR | FSR_FND_PREV_CACHEPGM_ERROR)))
{
nLLDRe |= FSR_LLD_1STPLN_CURR_ERROR;
}
if (FND_READ(pstFOReg->nCtrlStat) & FSR_FND_CURR_CACHEPGM_ERROR)
{
nLLDRe |= FSR_LLD_1STPLN_CURR_ERROR;
}
if (FND_READ(pstFOReg->nCtrlStat) & FSR_FND_PREV_CACHEPGM_ERROR)
{
nLLDRe |= FSR_LLD_1STPLN_PREV_ERROR;
}
}
break;
case FSR_FND_PREOP_ERASE:
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_ERASE_READY);
/* previous error check */
if ((FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR) ==
FSR_FND_STATUS_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->nFlushOpCaller : %d\r\n"),
pstFNDCxt->nFlushOpCaller));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" erase error: CtrlReg=0x%04x\r\n"),
FND_READ(pstFOReg->nCtrlStat) ));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" last Erase() call @ nDev = %d, nPbn = %d, nFlag:0x%08x\r\n"),
nDev, nPrevPbn, nPrevFlag));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_PREV_ERASE_ERROR | FSR_LLD_1STPLN_CURR_ERROR);
}
break;
default:
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
break;
}
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
/* when this code is running for Tiny FSR and
* there is an error for Erase, Pgm, save the error
*/
if ((nFlag & FSR_LLD_FLAG_READ_ONLY) && (nLLDRe != FSR_LLD_SUCCESS))
{
_SaveErrorCxt(nDev, nDie, pstFNDCxt, nLLDRe);
nLLDRe = FSR_LLD_SUCCESS;
}
#endif
#if defined (FSR_LLD_STATISTICS)
_AddFNDStat(nDev, nDie, FSR_FND_STAT_FLUSH, 0, FSR_FND_STAT_NORMAL_CMD);
#endif
} while (0);
if (FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_INVALID_PARAM)
{
if (!(nFlag & FSR_LLD_FLAG_REMAIN_PREOP_STAT))
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_NONE;
}
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
if (!(nFlag & FSR_LLD_FLAG_READ_ONLY))
{
gstFNDSharedCxt[nDev].nHostLLDOp[nDie] = FSR_FND_PREOP_NONE;
}
/* save the mode (Tiny FSR or FSR) */
gstFNDSharedCxt[nDev].nPrevFSRMode[nDie] = nFlag & FSR_LLD_FLAG_READ_ONLY;
#endif
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function provides block information.
*
* @param[in] nDev : Physical Device Number
* @param[in] nPbn : Physical Block Number
* @param[out] pBlockType : whether nPbn is SLC block or MLC block
* @param[out] pPgsPerBlk : the number of pages per block
*
* @return FSR_LLD_SUCCESS
* @n FSR_LLD_INVALID_PARAM
*
* @author NamOh Hwang
* @version 1.0.0
* @remark i.e. SLC or MLC block, the number of pages per block
*
*/
PUBLIC INT32
FSR_FND_GetBlockInfo(UINT32 nDev,
UINT32 nPbn,
UINT32 *pBlockType,
UINT32 *pPgsPerBlk)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
UINT32 nDie;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nPbn:%d)\r\n"),
__FSR_FUNC__, nDev, nPbn));
do
{
#if defined (FSR_LLD_STRICT_CHK)
nLLDRe = _StrictChk(nDev, nPbn, 0);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
if ((nPbn & pstFNDCxt->nFBAMask) < pstFNDCxt->nBlksForSLCArea[nDie])
{
/* this block is SLC block */
if (pBlockType != NULL)
{
*pBlockType = FSR_LLD_SLC_BLOCK;
}
if (pPgsPerBlk != NULL)
{
*pPgsPerBlk = pstFNDSpec->nPgsPerBlkForSLC;
}
}
else
{
/* this block is MLC block */
if (pBlockType != NULL)
{
*pBlockType = FSR_LLD_MLC_BLOCK;
}
if (pPgsPerBlk != NULL)
{
*pPgsPerBlk = pstFNDSpec->nPgsPerBlkForMLC;
}
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return nLLDRe;
}
/**
* @brief This function reports device information to upper layer.
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[out] pstDevSpec : pointer to the device spec
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_OPEN_FAILURE
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_GetDevSpec(UINT32 nDev,
FSRDevSpec *pstDevSpec,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
UINT32 nDieIdx;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d,pstDevSpec:0x%x,nFlag:0x%08x)\r\n"),
__FSR_FUNC__, nDev, pstDevSpec, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
if (pstDevSpec == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, pstDevSpec:0x%08x, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, pstDevSpec, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nDev:%d pstDevSpec is NULL\r\n"), nDev));
nLLDRe = FSR_LLD_OPEN_FAILURE;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
FSR_OAM_MEMSET(pstDevSpec, 0xFF, sizeof(FSRDevSpec));
pstDevSpec->nNumOfBlks = pstFNDSpec->nNumOfBlks;
pstDevSpec->nNumOfPlanes = pstFNDSpec->nNumOfPlanes;
for (nDieIdx = 0; nDieIdx < pstFNDSpec->nNumOfDies; nDieIdx++)
{
pstDevSpec->nBlksForSLCArea[nDieIdx] =
pstFNDCxt->nBlksForSLCArea[nDieIdx];
}
pstDevSpec->nSparePerSct = pstFNDSpec->nSparePerSct;
pstDevSpec->nSctsPerPG = pstFNDSpec->nSctsPerPG;
pstDevSpec->nNumOfBlksIn1stDie =
pstFNDSpec->nNumOfBlks / pstFNDSpec->nNumOfDies;
/* read DID from register file.
* because DID from pstFNDSpec->nDID is masked with FSR_FND_DID_MASK
*/
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
pstDevSpec->nDID = FND_READ(pstFOReg->nDID);
pstDevSpec->nPgsPerBlkForSLC = pstFNDSpec->nPgsPerBlkForSLC;
pstDevSpec->nPgsPerBlkForMLC = pstFNDSpec->nPgsPerBlkForMLC;
pstDevSpec->nNumOfDies = pstFNDSpec->nNumOfDies;
pstDevSpec->nUserOTPScts = pstFNDSpec->nUserOTPScts;
pstDevSpec->b1stBlkOTP = pstFNDSpec->b1stBlkOTP;
pstDevSpec->nRsvBlksInDev = pstFNDSpec->nRsvBlksInDev;
pstDevSpec->pPairedPgMap = pstFNDSpec->pPairedPgMap;
pstDevSpec->pLSBPgMap = pstFNDSpec->pLSBPgMap;
pstDevSpec->nNANDType = FSR_LLD_FLEX_ONENAND;
pstDevSpec->nPgBufToDataRAMTime = FSR_FND_PAGEBUF_TO_DATARAM_TIME;
pstDevSpec->bCachePgm = pstFNDCxt->bCachePgm;
pstDevSpec->nSLCTLoadTime = pstFNDSpec->nSLCTLoadTime;
pstDevSpec->nMLCTLoadTime = pstFNDSpec->nMLCTLoadTime;
pstDevSpec->nSLCTProgTime = pstFNDSpec->nSLCTProgTime;
pstDevSpec->nMLCTProgTime[0] = pstFNDSpec->nMLCTProgTime[0];
pstDevSpec->nMLCTProgTime[1] = pstFNDSpec->nMLCTProgTime[1];
pstDevSpec->nTEraseTime = pstFNDSpec->nTEraseTime;
/* time for transfering 1 page in u sec */
pstDevSpec->nWrTranferTime =
(pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE + sizeof(FSRSpareBuf))
* pstFNDCxt->nWrTranferTime / 2 / 1000;
pstDevSpec->nRdTranferTime =
(pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE + sizeof(FSRSpareBuf))
* pstFNDCxt->nRdTranferTime / 2 / 1000;
pstDevSpec->nSLCPECycle = pstFNDSpec->nSLCPECycle;
pstDevSpec->nMLCPECycle = pstFNDSpec->nMLCPECycle;
/* get UID from OTP block */
nLLDRe = _GetUniqueID(nDev, pstFNDCxt, nFlag);
FSR_OAM_MEMCPY(&pstDevSpec->nUID[0], &pstFNDCxt->nUID[0], FSR_LLD_UID_SIZE);
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief this function provides access information
*
* @param[in] nDev : Physical Device Number
* @param[out] pLLDPltInfo : structure for platform information.
*
* @return FSR_LLD_SUCCESS
* @n FSR_LLD_INVALID_PARAM
* @n FSR_LLD_OPEN_FAILURE
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_GetPlatformInfo(UINT32 nDev,
LLDPlatformInfo *pLLDPltInfo)
{
FlexONDCxt *pstFNDCxt = NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d,pLLDPltInfo:0x%x)\r\n"), __FSR_FUNC__, nDev, pLLDPltInfo));
do
{
if (pLLDPltInfo == NULL)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pLLDPltInfo is NULL\r\n")));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#if defined (FSR_LLD_STRICT_CHK)
/* check Device Number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line \r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif
pstFNDCxt = gpstFNDCxt[nDev];
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
#if defined (FSR_LLD_STRICT_CHK)
/* check Device Open Flag */
if (pstFNDCxt->bOpen == FALSE32)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Device is not opened\r\n")));
nLLDRe = FSR_LLD_OPEN_FAILURE;
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
FSR_OAM_MEMSET(pLLDPltInfo, 0x00, sizeof(LLDPlatformInfo));
/* Type of Device : FlexOneNAND = 0 */
pLLDPltInfo->nType = 0;
/* Address of command register */
pLLDPltInfo->nAddrOfCmdReg = (UINT32) &pstFOReg->nCmd;
/* Address of address register */
pLLDPltInfo->nAddrOfAdrReg = (UINT32) &pstFOReg->nStartAddr1;
/* Address of register for reading ID */
pLLDPltInfo->nAddrOfReadIDReg = (UINT32) &pstFOReg->nMID;
/* Address of status register */
pLLDPltInfo->nAddrOfStatusReg = (UINT32) &pstFOReg->nCtrlStat;
/* Command of reading Device ID */
pLLDPltInfo->nCmdOfReadID = (UINT32) NULL;
/* Command of read page */
pLLDPltInfo->nCmdOfReadPage = (UINT32) NULL;
/* Command of read status */
pLLDPltInfo->nCmdOfReadStatus = (UINT32) NULL;
/* Mask value for Ready or Busy status */
pLLDPltInfo->nMaskOfRnB = (UINT32) NULL;
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return nLLDRe;
}
/**
* @brief this function reads data from DataRAM of Flex-OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[out] pMBuf : Memory buffer for main array of NAND flash
* @param[out] pSBuf : Memory buffer for spare array of NAND flash
* @n nDie : 0 is for 1st die for DDP device
* @n : 1 is for 2nd die for DDP device
* @param[in] nFlag :
*
* @return FSR_LLD_SUCCESS
*
* @author NamOh Hwang
* @version 1.0.0
* @remark this function does not loads data from Flex-OneNAND
* @n it just reads data which lies on DataRAM
*
*/
PUBLIC INT32
FSR_FND_GetPrevOpData(UINT32 nDev,
UINT8 *pMBuf,
FSRSpareBuf *pSBuf,
UINT32 nDie,
UINT32 nFlag)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s() / nDie : %d / nFlag : 0x%x\r\n"), __FSR_FUNC__, nDie, nFlag));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
/* nDie can be 0 (1st die) or 1 (2nd die) */
if ((nDie & 0xFFFE) != 0)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nFlag:0x%08x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nFlag, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid nDie Number (nDie = %d)\r\n"),
nDie));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
#endif
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
FND_WRITE(pstFOReg->nStartAddr2, (UINT16) (nDie << FSR_FND_DBS_BASEBIT));
_ReadMain (pMBuf,
(volatile UINT8 *) &pstFOReg->nDataMB00[0],
pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE,
pstFNDCxt->pTempBuffer);
_ReadSpare(pstFNDCxt, pSBuf,
(volatile UINT8 *) &pstFOReg->nDataSB00[0]);
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return nLLDRe;
}
/**
* @brief This function does PI operation, OTP operation,
* @n reset, write protection.
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nCode : IO Control Command
* @n FSR_LLD_IOCTL_PI_ACCESS
* @n FSR_LLD_IOCTL_PI_READ
* @n FSR_LLD_IOCTL_PI_WRITE
* @n FSR_LLD_IOCTL_OTP_ACCESS
* @n FSR_LLD_IOCTL_OTP_LOCK
* @n in case IOCTL does with OTP protection,
* @n pBufI indicates 1st OTP or OTP block or both
* @n FSR_LLD_IOCTL_GET_OTPINFO
* @n FSR_LLD_IOCTL_LOCK_TIGHT
* @n FSR_LLD_IOCTL_LOCK_BLOCK
* @n FSR_LLD_IOCTL_UNLOCK_BLOCK
* @n FSR_LLD_IOCTL_UNLOCK_ALLBLK
* @n FSR_LLD_IOCTL_GET_LOCK_STAT
* @n FSR_LLD_IOCTL_HOT_RESET
* @n FSR_LLD_IOCTL_CORE_RESET
* @param[in] pBufI : Input Buffer pointer
* @param[in] nLenI : Length of Input Buffer
* @param[out] pBufO : Output Buffer pointer
* @param[out] nLenO : Length of Output Buffer
* @param[out] pByteRet : The number of bytes (length) of Output Buffer
* @n as the result of function call
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
* @return FSR_LLD_IOCTL_NOT_SUPPORT
* @return FSR_LLD_WRITE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_ERASE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_WR_PROTECT_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @return FSR_LLD_PI_PROGRAM_ERROR
* @return FSR_LLD_PREV_READ_ERROR | {FSR_LLD_1STPLN_CURR_ERROR }
*
* @author NamOh Hwang
* @version 1.0.0
* @remark OTP read, write is performed with FSR_FND_Write(), FSR_FND_ReadOptimal(),
* @n after OTP Access
*
*/
PUBLIC INT32
FSR_FND_IOCtl(UINT32 nDev,
UINT32 nCode,
UINT8 *pBufI,
UINT32 nLenI,
UINT8 *pBufO,
UINT32 nLenO,
UINT32 *pByteRet)
{
/* first word of PI block contains partition information */
LLDPIArg *pLLDPIArg; /* PI Write Argument */
/* used to lock, unlock, lock-tight */
LLDProtectionArg *pLLDProtectionArg;
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
FlexONDShMem *pstFNDShMem= NULL;
volatile FlexOneNANDReg *pstFOReg = NULL;
volatile UINT32 nLockType;
UINT32 nDie = 0xFFFFFFFF;
UINT32 nEndOfSLC;
UINT32 nPILockValue;
UINT32 nPbn;
UINT32 nErrorPbn = 0;
UINT32 nRSVofPI;
INT32 nLLDRe = FSR_LLD_SUCCESS;
BOOL32 bPILocked;
UINT32 nLockValue;
UINT16 nLockState;
UINT16 nWrProtectStat;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nCode:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nCode));
do
{
#if defined (FSR_LLD_STRICT_CHK)
/* check device number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"), nDev));
nLLDRe = (FSR_LLD_INVALID_PARAM);
break;
}
#endif /* #if defined (FSR_LLD_STRICT_CHK) */
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDShMem= gpstFNDShMem[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
/* interrupt should be enabled in I/O Ctl */
FSR_OAM_ClrNDisableInt(pstFNDCxt->nIntID);
switch (nCode)
{
case FSR_LLD_IOCTL_PI_ACCESS:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nDie = *(UINT32 *) pBufI;
FSR_ASSERT((nDie & ~0x1) == 0);
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) (nDie << FSR_FND_DFS_BASEBIT));
/* issue PI Access command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_ACCESS_PI);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_PI_READ:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)) ||
(pBufO == NULL) || (nLenO != sizeof(LLDPIArg)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter\r\n")));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pBufI = 0x%08x, nLenI = %d, pBufO = 0x%08x, nLenO = %d\r\n"),
pBufI, nLenI, pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nDie = *(UINT32 *) pBufI;
FSR_ASSERT((nDie & ~0x1) == 0);
nLLDRe = _ReadPI(nDev, nDie, &nEndOfSLC, &bPILocked);
pLLDPIArg = (LLDPIArg *) pBufO;
pLLDPIArg->nEndOfSLC =
(UINT16) (nDie * (pstFNDSpec->nNumOfBlks / pstFNDSpec->nNumOfDies) + nEndOfSLC);
pLLDPIArg->nPad = 0;
pLLDPIArg->nPILockValue =
bPILocked ? FSR_LLD_IOCTL_LOCK_PI : FSR_LLD_IOCTL_UNLOCK_PI;
if (pByteRet != NULL)
{
*pByteRet = sizeof(LLDPIArg);
}
break;
case FSR_LLD_IOCTL_PI_WRITE:
if ((pBufI == NULL) || (nLenI != sizeof(LLDPIArg)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pLLDPIArg = (LLDPIArg *) pBufI;
nEndOfSLC = (pLLDPIArg->nEndOfSLC & pstFNDCxt->nFBAMask);
nRSVofPI = FSR_FND_PI_RSV_MASK ^ pstFNDCxt->nFBAMask;
nDie = pLLDPIArg->nEndOfSLC >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
nPILockValue = pLLDPIArg->nPILockValue;
if (nPILockValue == FSR_LLD_IOCTL_LOCK_PI)
{
nLLDRe = _WritePI(nDev, nDie, (FSR_FND_PI_LOCK & nRSVofPI) | nEndOfSLC);
}
else if (nPILockValue == FSR_LLD_IOCTL_UNLOCK_PI)
{
nLLDRe = _WritePI(nDev, nDie, (FSR_FND_PI_NOLOCK & nRSVofPI) | nEndOfSLC);
}
else
{
nLLDRe = FSR_LLD_INVALID_PARAM;
}
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_OTP_ACCESS:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nDie = *(UINT32 *) pBufI;
FSR_ASSERT((nDie & ~0x1) == 0);
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) (nDie << FSR_FND_DFS_BASEBIT));
/* issue OTP Access command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_OTP_ACCESS);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_OTP_LOCK:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nLockType = *(UINT32 *) pBufI;
/* lock 1st block OTP & OTP block */
if (nLockType == (FSR_LLD_OTP_LOCK_1ST_BLK | FSR_LLD_OTP_LOCK_OTP_BLK))
{
nLockValue = FSR_FND_LOCK_BOTH_OTP;
}
/* lock 1st block OTP only */
else if (nLockType == FSR_LLD_OTP_LOCK_1ST_BLK)
{
nLockValue = FSR_FND_LOCK_1ST_BLOCK_OTP;
}
/* lock OTP block only */
else if (nLockType == FSR_LLD_OTP_LOCK_OTP_BLK)
{
nLockValue = FSR_FND_LOCK_OTP_BLOCK;
}
else
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nLLDRe = _LockOTP(nDev, nLockValue);
nDie = 0;
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_OTP_GET_INFO:
if ((pBufO == NULL) || (nLenO != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufO = 0x%08x, nLenO = %d\r\n"), pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nDie = 0;
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) (nDie << FSR_FND_DBS_BASEBIT));
nLockType = 0;
nLockState = FND_READ(pstFOReg->nCtrlStat);
if (nLockState & FSR_FND_CTLSTAT_1ST_OTP_LOCKED)
{
nLockType |= FSR_LLD_OTP_1ST_BLK_LOCKED;
}
else
{
nLockType |= FSR_LLD_OTP_1ST_BLK_UNLKED;
}
if (nLockState & FSR_FND_CTLSTAT_OTP_BLK_LOCKED)
{
nLockType |= FSR_LLD_OTP_OTP_BLK_LOCKED;
}
else
{
nLockType |= FSR_LLD_OTP_OTP_BLK_UNLKED;
}
*(UINT32 *) pBufO = nLockType;
nLenO = sizeof(nLockType);
nDie = 0;
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_LOCK_TIGHT:
if ((pBufI == NULL) || (nLenI != sizeof(LLDProtectionArg)) ||
(pBufO == NULL) || (nLenO != sizeof(nErrorPbn)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufO = 0x%08x, nLenO = %d\r\n"), pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pLLDProtectionArg = (LLDProtectionArg *) pBufI;
nDie = pLLDProtectionArg->nStartBlk >>
(FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
nLLDRe = _ControlLockBlk(nDev,
pLLDProtectionArg->nStartBlk,
pLLDProtectionArg->nBlks,
(UINT32)FSR_FND_CMD_LOCKTIGHT_BLOCK,
&nErrorPbn);
if (nLLDRe == FSR_LLD_INVALID_BLOCK_STATE)
{
*(UINT32 *) pBufO = nErrorPbn;
if (pByteRet != NULL)
{
*pByteRet = sizeof(nErrorPbn);
}
}
else
{
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
}
break;
case FSR_LLD_IOCTL_LOCK_BLOCK:
if ((pBufI == NULL) || (nLenI != sizeof(LLDProtectionArg)) ||
(pBufO == NULL) || (nLenO != sizeof(nErrorPbn)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufO = 0x%08x, nLenO = %d\r\n"), pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pLLDProtectionArg = (LLDProtectionArg *) pBufI;
nDie = pLLDProtectionArg->nStartBlk >>
(FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
nLLDRe = _ControlLockBlk(nDev,
pLLDProtectionArg->nStartBlk,
pLLDProtectionArg->nBlks,
FSR_FND_CMD_LOCK_BLOCK,
&nErrorPbn);
if (nLLDRe == FSR_LLD_INVALID_BLOCK_STATE)
{
*(UINT32 *) pBufO = nErrorPbn;
if (pByteRet != NULL)
{
*pByteRet = sizeof(nErrorPbn);
}
}
else
{
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
}
break;
case FSR_LLD_IOCTL_UNLOCK_BLOCK:
if ((pBufI == NULL) || (nLenI != sizeof(LLDProtectionArg)) ||
(pBufO == NULL) || (nLenO != sizeof(nErrorPbn)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufO = 0x%08x, nLenO = %d\r\n"), pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pLLDProtectionArg = (LLDProtectionArg *) pBufI;
nDie = pLLDProtectionArg->nStartBlk >>
(FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
nLLDRe = _ControlLockBlk(nDev,
pLLDProtectionArg->nStartBlk,
pLLDProtectionArg->nBlks,
FSR_FND_CMD_UNLOCK_BLOCK,
&nErrorPbn);
if (nLLDRe == FSR_LLD_INVALID_BLOCK_STATE)
{
*(UINT32 *) pBufO = nErrorPbn;
if (pByteRet != NULL)
{
*pByteRet = sizeof(nErrorPbn);
}
}
else
{
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
}
break;
case FSR_LLD_IOCTL_UNLOCK_ALLBLK:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufI = 0x%08x, nLenI = %d\r\n"), pBufI, nLenI));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nPbn = *(UINT32 *) pBufI;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) ((nPbn << pstFNDCxt->nDDPSelSft) & FSR_FND_DBS_MASK));
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nPbn << pstFNDCxt->nDDPSelSft) & FSR_FND_DFS_MASK));
FND_WRITE(pstFOReg->nStartBlkAddr,
(UINT16) (nPbn & pstFNDCxt->nFBAMask));
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_UNLOCK_ALLBLOCK);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_GET_LOCK_STAT:
if ((pBufI == NULL) || (nLenI != sizeof(UINT32)) ||
(pBufO == NULL) || (nLenO != sizeof(UINT32)))
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" invalid parameter pBufO = 0x%08x, nLenO = %d\r\n"), pBufO, nLenO));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
nPbn = *(UINT32 *) pBufI;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
FSR_ASSERT((nDie & ~0x1) == 0);
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2,
(UINT16) ((nPbn << pstFNDCxt->nDDPSelSft) & FSR_FND_DBS_MASK)) ;
/* set DFS & FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) (((nPbn << pstFNDCxt->nDDPSelSft) & FSR_FND_DFS_MASK) | (nPbn & pstFNDCxt->nFBAMask)));
#if defined(FSR_LLD_WAIT_WR_PROTECT_STAT)
do
{
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
} while (nWrProtectStat == (UINT16) 0x0000);
#else
nWrProtectStat = FND_READ(pstFOReg->nWrProtectStat);
#endif
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] nDev: %d, nPbn: %d has lock status 0x%04x\r\n"),
nDev, nPbn, nWrProtectStat));
*(UINT32 *) pBufO = (UINT32) nWrProtectStat;
if (pByteRet != NULL)
{
*pByteRet = (UINT32) sizeof(UINT32);
}
nLLDRe = FSR_LLD_SUCCESS;
break;
case FSR_LLD_IOCTL_HOT_RESET:
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_HOT_RESET);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_RESET_READY);
/* hot reset initialize the nSysConf1 register */
FND_WRITE(pstFOReg->nSysConf1, pstFNDCxt->nSysConf1);
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
case FSR_LLD_IOCTL_CORE_RESET:
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_RST_NFCORE);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_RESET_READY);
if (pByteRet != NULL)
{
*pByteRet = (UINT32) 0;
}
break;
default:
nLLDRe = FSR_LLD_IOCTL_NOT_SUPPORT;
break;
}
if ((nCode == FSR_LLD_IOCTL_HOT_RESET) || (nCode == FSR_LLD_IOCTL_CORE_RESET))
{
for (nDie = 0; nDie < pstFNDSpec->nNumOfDies; nDie++)
{
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_IOCTL;
pstFNDShMem->nPreOpPbn[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpFlag[nDie] = FSR_FND_PREOP_FLAG_NONE;
}
}
else if ((nLLDRe != FSR_LLD_INVALID_PARAM) && (nLLDRe != FSR_LLD_IOCTL_NOT_SUPPORT))
{
FSR_ASSERT(nDie != 0xFFFFFFFF);
pstFNDShMem->nPreOp[nDie] = FSR_FND_PREOP_IOCTL;
pstFNDShMem->nPreOpPbn[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDShMem->nPreOpFlag[nDie] = FSR_FND_PREOP_FLAG_NONE;
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s() / nLLDRe : 0x%x\r\n"), __FSR_FUNC__, nLLDRe));
return (nLLDRe);
}
/**
* @brief This function Erase, Program & Updates PI allocation info.
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[out] *pnEndOfSLC : end block # of SLC area
* @param[out] *pbPILocked : whether PI block is locked or not.
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_NO_RESPONSE
* @return FSR_LLD_PI_READ_ERROR
*
* @author NamOh Hwang
* @version 1.0.0
* @remark EndOfSLC can be differnt by die(chip) for DDP device
*
*/
PRIVATE INT32
_ReadPI(UINT32 nDev,
UINT32 nDie,
UINT32 *pnEndOfSLC,
BOOL32 *pbPILocked)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT32 nIdx;
UINT32 nRSVofPI;
UINT16 nPIValue;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nDie:%d)\r\n"),
__FSR_FUNC__, nDev, nDie));
do
{
FSR_ASSERT((nDie & ~0x1) == 0)
FSR_ASSERT(pnEndOfSLC != NULL);
/* wait for each die ready, play for safety */
for (nIdx = 0; nIdx < pstFNDCxt->pstFNDSpec->nNumOfDies; nIdx++)
{
/* Select DataRAM for DDP */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16)(nIdx << FSR_FND_DBS_BASEBIT));
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
}
/* Select DataRAM for DDP */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16)(nDie << FSR_FND_DBS_BASEBIT));
/* Write 'DFS, FBA' of Flash (FBA could be omitted or any address) */
FND_WRITE(pstFOReg->nStartAddr1, (UINT16)(nDie << FSR_FND_DFS_BASEBIT));
/* Write 'PI Access' command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_ACCESS_PI);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
/* Write 'FPA, FSA' of Flash */
FND_WRITE(pstFOReg->nStartAddr8, 0x0 << pstFNDCxt->nFPASelSft);
/* Write 'BSA, BSC' of DataRAM */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
/* ECC off */
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
/* Write 'Load' Command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_LOAD);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_READ_READY);
/* can not check ECC status becuase of ECC off */
/* Host reads data from DataRAM */
nPIValue = FND_READ(*(UINT16 *) &pstFOReg->nDataMB00[0]);
*pnEndOfSLC = (UINT32) (nPIValue & pstFNDCxt->nFBAMask);
nRSVofPI = FSR_FND_PI_RSV_MASK ^ pstFNDCxt->nFBAMask;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nDie:%d, *pnEndOfSLC:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, *pnEndOfSLC, __LINE__));
if (pbPILocked != NULL)
{
if ((nPIValue & FSR_FND_PI_LOCK_MASK) == (UINT16)(nRSVofPI & FSR_FND_PI_LOCK & FSR_FND_PI_LOCK_MASK))
{
*pbPILocked = TRUE32;
}
else if ((nPIValue & FSR_FND_PI_LOCK_MASK) == (UINT16)(FSR_FND_PI_NOLOCK & nRSVofPI & FSR_FND_PI_LOCK_MASK))
{
*pbPILocked = FALSE32;
}
else
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] nDie: %d, undefined PI value: 0x%04x / %d line\r\n"),
nDie, nPIValue, __LINE__));
}
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] %s(nDev:%d, nDie:%d, *pbPILocked:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, *pbPILocked, __LINE__));
}
} while (0);
/* do NAND Core reset */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_RST_NFCORE);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_RESET_READY);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return (nLLDRe);
}
/**
* @brief This function Erase, Program & Updates PI allocation info.
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] nPIValue : this value is written to PI block
* @n this value does not equals to the end block # of SLC area
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_PI_ERASE_ERROR
* @return FSR_LLD_PI_PROGRAM_ERROR
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE INT32
_WritePI(UINT32 nDev,
UINT32 nDie,
UINT32 nPIValue)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nDie:%d, nPIValue:0x%04x)\r\n"),
__FSR_FUNC__, nDev, nDie, nPIValue));
do
{
/*********************************************************************/
/* Step 1: PI Block Access mode */
/*********************************************************************/
/* Select DataRAM for DDP */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16)(nDie << FSR_FND_DBS_BASEBIT));
/* Write 'DFS, FBA' of Flash (FBA could be omitted or any address) */
FND_WRITE(pstFOReg->nStartAddr1, (UINT16) (nDie << FSR_FND_DFS_BASEBIT));
/* Write 'PI Access' Command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_ACCESS_PI);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
/*********************************************************************/
/* Step 2: PI Block Erase */
/*********************************************************************/
/* Write 'FBA' of Flash (FBA must be 0x0000h) */
FND_WRITE(pstFOReg->nStartAddr1, (UINT16) (nDie << FSR_FND_DFS_BASEBIT));
/* Write Erase command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_ERASE);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_ERASE_READY);
if ((FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR) ==
FSR_FND_STATUS_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nPIValue:0x%04x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nPIValue, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" PI Erase Error, Ctrl Reg:0x%04x\r\n"),
FND_READ(pstFOReg->nCtrlStat)));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
/* if PI block is locked, error bit of ctrl status reg. is set */
nLLDRe = FSR_LLD_PI_ERASE_ERROR;
break;
}
/*********************************************************************/
/* Step 3: PI Program */
/*********************************************************************/
/* Write Data into DataRAM */
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0xFF, FSR_SECTOR_SIZE * pstFNDSpec->nSctsPerPG);
TRANSFER_TO_NAND(pstFOReg->nDataMB00,
pstFNDCxt->pTempBuffer,
FSR_SECTOR_SIZE * pstFNDSpec->nSctsPerPG);
TRANSFER_TO_NAND(pstFOReg->nDataSB00,
pstFNDCxt->pTempBuffer,
FSR_SPARE_SIZE * pstFNDSpec->nSctsPerPG);
/* Write Partition Information */
FND_WRITE(*(volatile UINT16 *) &pstFOReg->nDataMB00[0],
(UINT16) nPIValue);
/* Write 'DFS, FBA' of Flash (FBA must be 0x0000h) */
FND_WRITE(pstFOReg->nStartAddr1, (UINT16) (nDie << FSR_FND_DFS_BASEBIT));
/* Write 'FPA, FSA' of Flash (FPA must be 00h and FSA must be 00h) */
FND_WRITE(pstFOReg->nStartAddr8, 0x0 << pstFNDCxt->nFPASelSft);
/* Write 'BSA, BSC' of DataRAM (BSA must be 1000b and BSC must be 000b) */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
/* ECC off */
FND_SET(pstFOReg->nSysConf1, FSR_FND_CONF1_ECC_OFF);
/* Write Program Command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_PROGRAM);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_WRITE_READY);
/* check the result of PI program */
if ((FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR) ==
FSR_FND_STATUS_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nDie:%d, nPIValue:0x%04x) / %d line\r\n"),
__FSR_FUNC__, nDev, nDie, nPIValue, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" PI Program Error, CtrlReg=0x%04x\r\n"),
FND_READ(pstFOReg->nCtrlStat)));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = (FSR_LLD_PI_PROGRAM_ERROR);
break;
}
pstFNDCxt->nBlksForSLCArea[nDie] =
(pstFNDCxt->nFBAMask & (UINT16) nPIValue) + 1;
/*********************************************************************/
/* Step 3: PI Block Update */
/*********************************************************************/
/* Write 'DFS, FBA' of Flash (FBA must be 0x0000h) */
FND_WRITE(pstFOReg->nStartAddr1, (UINT16)(nDie << FSR_FND_DFS_BASEBIT));
/* Write 'BSA, BSC' of DataRAM (BSA must be 1000b and BSC must be 000b) */
FND_WRITE(pstFOReg->nStartBuf, FSR_FND_START_BUF_DEFAULT);
/* Write 'FPA, FSA' of Flash (FPA must be 00h and FSA must be 00h) */
FND_WRITE(pstFOReg->nStartAddr8, 0x0 << pstFNDCxt->nFPASelSft);
/* Write Update PI command */
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_UPDATE_PI);
/* Wait for INT register low to high transition */
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
} while (0);
/*********************************************************************/
/* Step 4: NAND Flash Reset */
/*********************************************************************/
FND_WRITE(pstFOReg->nCmd, FSR_FND_CMD_RST_NFCORE);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_RESET_READY);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return (nLLDRe);
}
/**
* @brief This function controls lock/unlock/lock-tight block
*
* @param[in] nDev : Physical Device Number (0 ~ 7)
* @param[in] nSbn : start block number
* @param[in] nBlks : the number of blocks to lock tight
* @param[out] pnErrorPbn : physical block number where
* @n command (lock tight) fails.
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_BLK_PROTECTION_ERROR
*
* @author NamOh Hwang / JeongWook Moon
* @version 1.0.0
* @remark
*
*/
PRIVATE INT32
_ControlLockBlk(UINT32 nDev,
UINT32 nPbn,
UINT32 nBlks,
UINT32 nLockTypeCMD,
UINT32 *pnErrPbn)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
UINT32 nDie;
UINT32 nFBA;
INT32 nLLDRe = FSR_LLD_SUCCESS;
UINT16 nLockStat;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev: %d, nPbn: %d, nBlks: %d)\r\n"),
__FSR_FUNC__, nDev, nPbn, nBlks));
while (nBlks > 0)
{
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
nFBA = nPbn & pstFNDCxt->nFBAMask;
/* set DBS */
FND_WRITE(pstFOReg->nStartAddr2, (UINT16) (nDie << FSR_FND_DBS_BASEBIT));
/* set DFS, FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) | nFBA));
#if defined(FSR_LLD_WAIT_WR_PROTECT_STAT)
do
{
nLockStat = FND_READ(pstFOReg->nWrProtectStat);
} while (nLockStat == (UINT16) 0x0000);
#else
nLockStat = FND_READ(pstFOReg->nWrProtectStat);
#endif
nLockStat = nLockStat & FSR_LLD_BLK_STAT_MASK;
/* to lock blocks tight, the block should be locked first */
switch (nLockTypeCMD)
{
case FSR_FND_CMD_LOCKTIGHT_BLOCK:
if (nLockStat == FSR_LLD_BLK_STAT_UNLOCKED)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" unlocked blk cannot be locked tight\r\n")));
nLLDRe = FSR_LLD_INVALID_BLOCK_STATE;
}
break;
case FSR_FND_CMD_LOCK_BLOCK:
case FSR_FND_CMD_UNLOCK_BLOCK:
if (nLockStat == FSR_LLD_BLK_STAT_LOCKED_TIGHT)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" lock-tight blk cannot be unlocked or locked\r\n")));
nLLDRe = FSR_LLD_INVALID_BLOCK_STATE;
}
break;
default:
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Unknown command 0x%x\r\n"), nLockTypeCMD));
nLLDRe = FSR_LLD_INVALID_BLOCK_STATE;
break;
}
if (!(nLLDRe == FSR_LLD_SUCCESS))
{
*pnErrPbn = nPbn;
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn #%d is unlocked\r\n"), nPbn));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
break;
}
FND_WRITE(pstFOReg->nStartBlkAddr,(UINT16) nFBA);
/* a command */
FND_WRITE(pstFOReg->nCmd, (UINT16)nLockTypeCMD);
WAIT_FND_INT_STAT(pstFOReg, FSR_FND_INT_MASTER_READY);
/* Check CtrlStat register */
if (FND_READ(pstFOReg->nCtrlStat) & FSR_FND_STATUS_ERROR)
{
*pnErrPbn = nPbn;
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn #%d is fail lock tight\r\n"), nPbn));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
nLLDRe = FSR_LLD_INVALID_BLOCK_STATE;
break;
}
/* set DFS, FBA */
FND_WRITE(pstFOReg->nStartAddr1,
(UINT16) ((nDie << FSR_FND_DFS_BASEBIT) | nFBA));
/* Wait WR_PROTECT_STAT */
switch (nLockTypeCMD)
{
case FSR_FND_CMD_LOCKTIGHT_BLOCK:
WAIT_FND_WR_PROTECT_STAT(pstFOReg, FSR_LLD_BLK_STAT_LOCKED_TIGHT);
break;
case FSR_FND_CMD_LOCK_BLOCK:
WAIT_FND_WR_PROTECT_STAT(pstFOReg, FSR_LLD_BLK_STAT_LOCKED);
break;
case FSR_FND_CMD_UNLOCK_BLOCK:
WAIT_FND_WR_PROTECT_STAT(pstFOReg, FSR_LLD_BLK_STAT_UNLOCKED);
break;
default:
break;
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] nDev: %d, nPbn: %d is locked tight\r\n"),
nDev, nPbn));
nBlks--;
nPbn++;
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return (nLLDRe);
}
/**
* @brief this function locks the OTP block, 1st OTP block
*
* @param[in] nDev : Physical Device Number
* @param[in] nLockValue : this is programmed into 1st word of sector0 of
* @n main of page0 in the OTP block
*
* @return FSR_LLD_SUCCESS
* @n FSR_LLD_INVALID_PARAM
* @n FSR_LLD_OTP_ALREADY_LOCKED
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE INT32
_LockOTP(UINT32 nDev,
UINT32 nLockValue)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
UINT32 nBytesRet;
UINT32 nLockState;
UINT32 nPbn;
UINT32 nFlushOpCaller;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nLockValue:0x%04x)\r\n"),
__FSR_FUNC__, nDev, nLockValue));
do
{
nLLDRe = FSR_FND_IOCtl(nDev, FSR_LLD_IOCTL_OTP_GET_INFO,
NULL, 0,
(UINT8 *) &nLockState, sizeof(nLockState),
&nBytesRet);
if (nLLDRe != FSR_LLD_SUCCESS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] FSR_FND_IOCtl(nCode:FSR_LLD_IOCTL_OTP_GET_INFO) / %s(nDev:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, __LINE__));
break;
}
if ((nLockValue & FSR_FND_OTP_LOCK_MASK) == FSR_FND_LOCK_1ST_BLOCK_OTP)
{
/* it's an Error to lock 1st block as OTP
* when this device doesn't use 1st block as OTP
*/
if ((pstFNDSpec->b1stBlkOTP) == FALSE32)
{
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
/* when OTP block is locked,
* 1st block cannot be locked as OTP
*/
if (nLockState & FSR_LLD_OTP_OTP_BLK_LOCKED)
{
nLLDRe = FSR_LLD_OTP_ALREADY_LOCKED;
break;
}
}
nPbn = 0;
/* the size of nPbn should be 4 bytes */
FSR_ASSERT(sizeof(nPbn) == sizeof(UINT32));
nLLDRe = FSR_FND_IOCtl(nDev, FSR_LLD_IOCTL_OTP_ACCESS,
(UINT8 *) &nPbn, sizeof(nPbn),
NULL, 0,
&nBytesRet);
if (nLLDRe != FSR_LLD_SUCCESS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] FSR_FND_IOCtl(nCode:FSR_LLD_IOCTL_OTP_ACCESS) / %s(nDev:%d) / %d line\r\n"),
__FSR_FUNC__, nDev, __LINE__));
break;
}
FSR_FND_ReadOptimal(nDev,
nPbn,
FSR_FND_OTP_PAGE_OFFSET,
NULL,
NULL,
FSR_LLD_FLAG_1X_LOAD);
nLLDRe = FSR_FND_ReadOptimal(nDev,
nPbn,
FSR_FND_OTP_PAGE_OFFSET,
NULL,
NULL,
FSR_LLD_FLAG_TRANSFER);
if (nLLDRe != FSR_LLD_SUCCESS)
{
break;
}
nLockValue = FND_READ(*(UINT16 *) pstFOReg->nDataMB10) & (UINT16) nLockValue;
FND_WRITE(*(UINT16 *) pstFOReg->nDataMB10, (UINT16) nLockValue);
FSR_FND_Write(nDev, nPbn, FSR_FND_OTP_PAGE_OFFSET,
NULL, NULL, FSR_LLD_FLAG_1X_PROGRAM);
nFlushOpCaller = FSR_FND_PREOP_IOCTL << FSR_FND_FLUSHOP_CALLER_BASEBIT;
nLLDRe = FSR_FND_FlushOp(nDev, nFlushOpCaller | 0, FSR_LLD_FLAG_NONE);
if (nLLDRe != FSR_LLD_SUCCESS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s(nDev:%d, nLockValue:0x%04x) / %d line\r\n"),
__FSR_FUNC__, nDev, nLockValue, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Program Error while locking OTP\r\n")));
_DumpRegisters(pstFOReg);
_DumpSpareBuffer(pstFOReg);
break;
}
} while (0);
/* exit the OTP block */
FSR_FND_IOCtl(nDev, /* nDev : Physical Device Number (0 ~ 7) */
FSR_LLD_IOCTL_CORE_RESET, /* nCode : IO Control Command */
NULL, /* *pBufI : Input Buffer pointer */
0, /* nLenI : Length of Input Buffer */
NULL, /* *pBufO : Output Buffer pointer */
0, /* nLenO : Length of Output Buffer */
&nBytesRet); /* *pByteRet : The number of bytes (length) of
Output Buffer as the result of
function call */
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return nLLDRe;
}
/**
* @brief this function checks the validity of parameter
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nPbn : Physical Block Number
* @param[in] nPgOffset : Page Offset within a block
* @param[in] pstFNDCxt : gpstFNDCxt[nDev]
* @param[in] pstFNDSpec : gpstFNDCxt[nDev]->pstFNDSpec
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_INVALID_PARAM
*
* @author NamOh Hwang
* @version 1.0.0
* @remark Pbn is consecutive numbers within the device
* @n i.e. for DDP device, Pbn for 1st block in 2nd chip is not 0
* @n it is one more than the last block number in 1st chip
*
*/
PRIVATE INT32
_StrictChk(UINT32 nDev,
UINT32 nPbn,
UINT32 nPgOffset)
{
FlexONDCxt *pstFNDCxt = NULL;
FlexONDSpec *pstFNDSpec = NULL;
UINT32 nDie;
INT32 nLLDRe = FSR_LLD_SUCCESS;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] ++%s(nDev:%d, nPbn:%d, nPgOffset:%d)\r\n"),
__FSR_FUNC__, nDev, nPbn, nPgOffset));
do
{
/* check Device Number */
if (nDev >= FSR_FND_MAX_DEVS)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Invalid Device Number (nDev = %d)\r\n"),
nDev));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
pstFNDCxt = gpstFNDCxt[nDev];
pstFNDSpec = pstFNDCxt->pstFNDSpec;
nDie = nPbn >> (FSR_FND_DFS_BASEBIT - pstFNDCxt->nDDPSelSft);
/* check Device Open Flag */
if (pstFNDCxt->bOpen == FALSE32)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Device is not opened\r\n")));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" pstFNDCxt->bOpen: 0x%08x\r\n"),
pstFNDCxt->bOpen));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
/* check Block Out of Bound */
if (nPbn >= pstFNDSpec->nNumOfBlks)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pbn:%d >= pstFNDSpec->nNumOfBlks:%d\r\n"),
nPbn, pstFNDSpec->nNumOfBlks));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
else if ((nPbn & pstFNDCxt->nFBAMask) >= pstFNDCxt->nBlksForSLCArea[nDie])
{
/* check nPgOffset Out of Bound */
/* in case of MLC, pageOffset is lower than 128 */
if (nPgOffset >= pstFNDSpec->nPgsPerBlkForMLC)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pg #%d in MLC(Pbn #%d) is invalid\r\n"),
nPgOffset, nPbn));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nBlksForSLCArea[%d] = %d\r\n"),
nDie, pstFNDCxt->nBlksForSLCArea[nDie]));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
}
else
{
/* check nPgOffset Out of Bound */
/* in case of SLC, pageOffset is lower than 64 */
if (nPgOffset >= pstFNDSpec->nPgsPerBlkForSLC)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:ERR] %s() / %d line\r\n"),
__FSR_FUNC__, __LINE__));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" Pg #%d in SLC(Pbn #%d) is invalid\r\n"),
nPgOffset, nPbn));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nBlksForSLCArea[%d] = %d\r\n"),
nDie, pstFNDCxt->nBlksForSLCArea[nDie]));
nLLDRe = FSR_LLD_INVALID_PARAM;
break;
}
}
} while (0);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return (nLLDRe);
}
/**
* @brief This function prints the contents register file
*
* @param[in] pstReg : pointer to structure FlexOneNANDReg.
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_DumpRegisters(volatile FlexOneNANDReg *pstReg)
{
UINT32 nDiesPerDev;
UINT16 nDID;
UINT16 nStartAddr2;
UINT16 nDBS;
FSR_STACK_VAR;
FSR_STACK_END;
nDID = FND_READ(pstReg->nDID);
nDiesPerDev = ((nDID >> 3) & 1) + 1;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pstReg:0x%08x)\r\n"),
__FSR_FUNC__, pstReg));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("\r\nstart dumping registers. \r\n")));
#if defined (TINY_FSR)
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, (TEXT("[FND: ] this is TINY_FSR\r\n")));
#endif
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Manufacturer ID Reg."),
&pstReg->nMID, FND_READ(pstReg->nMID)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Device ID Reg."),
&pstReg->nDID, FND_READ(pstReg->nDID)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Version ID Reg."),
&pstReg->nVerID, FND_READ(pstReg->nVerID)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Data Buffer Size Reg."),
&pstReg->nDataBufSize, FND_READ(pstReg->nDataBufSize)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Boot Buffer Size Reg."),
&pstReg->nBootBufSize, FND_READ(pstReg->nBootBufSize)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Amount of buffers Reg."),
&pstReg->nBufAmount, FND_READ(pstReg->nBufAmount)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Technology Reg."),
&pstReg->nTech, FND_READ(pstReg->nTech)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 1 Reg."),
&pstReg->nStartAddr1, FND_READ(pstReg->nStartAddr1)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 2 Reg."),
&pstReg->nStartAddr2, FND_READ(pstReg->nStartAddr2)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 8 Reg."),
&pstReg->nStartAddr8, FND_READ(pstReg->nStartAddr8)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start Buffer Reg."),
&pstReg->nStartBuf, FND_READ(pstReg->nStartBuf)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Command Reg."),
&pstReg->nCmd, FND_READ(pstReg->nCmd)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("System Conf1 Reg."),
&pstReg->nSysConf1, FND_READ(pstReg->nSysConf1)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Controller Status Reg."),
&pstReg->nCtrlStat, FND_READ(pstReg->nCtrlStat)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Interrupt Reg."),
&pstReg->nInt, FND_READ(pstReg->nInt)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start Block Address Reg."),
&pstReg->nStartBlkAddr, FND_READ(pstReg->nStartBlkAddr)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Write Protection Reg."),
&pstReg->nWrProtectStat, FND_READ(pstReg->nWrProtectStat)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 1 Reg."),
&pstReg->nEccStat[0], FND_READ(pstReg->nEccStat[0])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 2 Reg."),
&pstReg->nEccStat[1], FND_READ(pstReg->nEccStat[1])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 3 Reg."),
&pstReg->nEccStat[2], FND_READ(pstReg->nEccStat[2])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 4 Reg."),
&pstReg->nEccStat[3], FND_READ(pstReg->nEccStat[3])));
if (nDiesPerDev == 2)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("other die register dump\r\n")));
/* backup DBS */
nStartAddr2 = FND_READ(pstReg->nStartAddr2);
nDBS = nStartAddr2 >> FSR_FND_DBS_BASEBIT;
nDBS = (nDBS + 1) & 1;
/* set DBS */
FND_WRITE(pstReg->nStartAddr2,
(UINT16) (nDBS << FSR_FND_DBS_BASEBIT));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 1 Reg."),
&pstReg->nStartAddr1, FND_READ(pstReg->nStartAddr1)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 2 Reg."),
&pstReg->nStartAddr2, FND_READ(pstReg->nStartAddr2)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Start address 8 Reg."),
&pstReg->nStartAddr8, FND_READ(pstReg->nStartAddr8)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Controller Status Reg."),
&pstReg->nCtrlStat, FND_READ(pstReg->nCtrlStat)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Interrupt Reg."),
&pstReg->nInt, FND_READ(pstReg->nInt)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("Write Protection Reg."),
&pstReg->nWrProtectStat, FND_READ(pstReg->nWrProtectStat)));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 1 Reg."),
&pstReg->nEccStat[0], FND_READ(pstReg->nEccStat[0])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 2 Reg."),
&pstReg->nEccStat[1], FND_READ(pstReg->nEccStat[1])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 3 Reg."),
&pstReg->nEccStat[2], FND_READ(pstReg->nEccStat[2])));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%-25s @ 0x%08X: 0x%04X\r\n"), TEXT("ECC Status 4 Reg."),
&pstReg->nEccStat[3], FND_READ(pstReg->nEccStat[3])));
/* restore DBS */
FND_WRITE(pstReg->nStartAddr2,
(UINT16) (nStartAddr2));
}
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("end dumping registers. \r\n\r\n")));
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG, (TEXT("[FND:OUT] --%s\r\n"), __FSR_FUNC__));
}
/**
* @brief This function prints spare buffer
*
* @param[in] pstReg : pointer to structure FlexOneNANDReg.
*
* @return none
*
* @author SongHo Yoon
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_DumpSpareBuffer(volatile FlexOneNANDReg *pstReg)
{
#if !defined(FSR_OAM_RTLMSG_DISABLE)
UINT32 nSctIdx;
UINT32 nIdx;
UINT32 nDieIdx;
UINT32 nDataBufSize;
UINT32 nSctsPerDataBuf;
UINT32 nDiesPerDev;
UINT16 *pnDataSB00;
UINT16 nDID;
UINT16 nStartAddr2;
UINT16 nValue;
FSR_STACK_VAR;
FSR_STACK_END;
nDID = FND_READ(pstReg->nDID);
nDiesPerDev = ((nDID >> 3) & 1) + 1;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(pstReg:0x%08x)\r\n"),
__FSR_FUNC__, pstReg));
/* backup DBS */
nStartAddr2 = FND_READ(pstReg->nStartAddr2);
nDataBufSize = FND_READ(pstReg->nDataBufSize) * 2;
nSctsPerDataBuf = nDataBufSize / FSR_SECTOR_SIZE;
pnDataSB00 = (UINT16 *) pstReg->nDataSB00;
for (nDieIdx = 0; nDieIdx < nDiesPerDev; nDieIdx++)
{
/* set DBS */
FND_WRITE(pstReg->nStartAddr2,
(UINT16) (nDieIdx << FSR_FND_DBS_BASEBIT));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, (TEXT(" Dump Spare Buffer [die:%d]\r\n"), nDieIdx));
for (nSctIdx = 0; nSctIdx < nSctsPerDataBuf; nSctIdx++)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, (TEXT("[%02d] "), nSctIdx));
for (nIdx = 0; nIdx < 8; nIdx++)
{
nValue = (UINT16) FND_READ(pnDataSB00[nSctIdx * 8 + nIdx]);
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%04x "), nValue));
}
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, (TEXT("\r\n")));
}
}
/* restore DBS */
FND_WRITE(pstReg->nStartAddr2,
(UINT16) (nStartAddr2));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR, (TEXT("\r\n")));
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG, (TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
#endif
}
/**
* @brief This function prints error context of TimeOut error
* @n when using Tiny FSR and FSR at the same time
*
* @param[in] none
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_DumpCmdLog(VOID)
{
#if !defined(FSR_OAM_RTLMSG_DISABLE)
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt = NULL;
#endif
FlexONDCxt *pstFNDCxt = NULL;
FlexONDShMem *pstFNDShMem = NULL;
UINT32 nDev;
#if defined(FSR_LLD_LOGGING_HISTORY)
volatile FlexONDOpLog *pstFNDOpLog = NULL;
UINT32 nIdx;
UINT32 nLogHead;
UINT32 nPreOpIdx;
#endif
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG | FSR_DBZ_ERROR,
(TEXT("[FND:IN ] ++%s()\r\n\r\n"), __FSR_FUNC__));
#if defined (TINY_FSR)
FSR_DBZ_DBGMOUT(FSR_DBZ_ERROR, (TEXT("[FND: ] this is TINY_FSR\r\n")));
#endif
for (nDev = 0; nDev < FSR_MAX_DEVS; nDev++)
{
pstFNDCxt = gpstFNDCxt[nDev];
if (pstFNDCxt == NULL)
{
continue;
}
if (pstFNDCxt->bOpen == FALSE32)
{
continue;
}
pstFNDShMem = gpstFNDShMem[nDev];
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR | FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] pstFNDCxt->nFlushOpCaller : %d\r\n"),
pstFNDCxt->nFlushOpCaller));
#if defined (FSR_LLD_LOGGING_HISTORY)
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:INF] start printing nLog : nDev[%d]\r\n"), nDev));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%5s %7s %10s %10s %10s\r\n"), TEXT("nLog"),
TEXT("preOp"), TEXT("prePbn"), TEXT("prePg"), TEXT("preFlag")));
pstFNDOpLog = &gstFNDOpLog[nDev];
nLogHead = pstFNDOpLog->nLogHead;
for (nIdx = 0; nIdx < FSR_FND_MAX_LOG; nIdx++)
{
nPreOpIdx = pstFNDOpLog->nLogOp[nLogHead];
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("%5d| %7s, 0x%08x, 0x%08x, 0x%08x\r\n"),
nLogHead, gpszLogPreOp[nPreOpIdx], pstFNDOpLog->nLogPbn[nLogHead],
pstFNDOpLog->nLogPgOffset[nLogHead], pstFNDOpLog->nLogFlag[nLogHead]));
nLogHead = (nLogHead + 1) & (FSR_FND_MAX_LOG -1);
}
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] end printing nLog : nDev[%d]\r\n"), nDev));
#endif /* #if defined (FSR_LLD_LOGGING_HISTORY) */
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("\r\n[FND:INF] start printing FlexONDCxt: nDev[%d]\r\n"), nDev));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nPreOp : [0x%08x, 0x%08x]\r\n"),
pstFNDShMem->nPreOp[0], pstFNDShMem->nPreOp[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nPreOpPbn : [0x%08x, 0x%08x]\r\n"),
pstFNDShMem->nPreOpPbn[0], pstFNDShMem->nPreOpPbn[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nPreOpPgOffset : [0x%08x, 0x%08x]\r\n"),
pstFNDShMem->nPreOpPgOffset[0], pstFNDShMem->nPreOpPgOffset[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" nPreOpFlag : [0x%08x, 0x%08x]\r\n"),
pstFNDShMem->nPreOpFlag[0], pstFNDShMem->nPreOpFlag[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT(" end printing FlexONDCxt: nDev[%d]\r\n\r\n"), nDev));
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND:INF] start printing SharedCxt: nDev[%d]\r\n"), nDev));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nPrevFSRMode : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nPrevFSRMode[0], pstFNDSharedCxt->nPrevFSRMode[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nHostLLDRe : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nHostLLDRe[0], pstFNDSharedCxt->nHostLLDRe[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nHostLLDOp : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nHostLLDOp[0], pstFNDSharedCxt->nHostLLDOp[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nHostLLDPbn : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nHostLLDPbn[0], pstFNDSharedCxt->nHostLLDPbn[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nHostLLDPgOffset : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nHostLLDPgOffset[0], pstFNDSharedCxt->nHostLLDPgOffset[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] nHostLLDFlag : [0x%08x, 0x%08x]\r\n"),
pstFNDSharedCxt->nHostLLDFlag[0], pstFNDSharedCxt->nHostLLDFlag[1]));
FSR_DBZ_RTLMOUT(FSR_DBZ_ERROR,
(TEXT("[FND: ] end printing SharedCxt: nDev[%d]\r\n"), nDev));
#endif
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG | FSR_DBZ_ERROR, (TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
#endif /* #if !defined(FSR_OAM_RTLMSG_DISABLE) */
}
/**
* @brief This function calculates transfer time for word (2 bytes)
* @n between host & OneNAND
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nSysConfig1 : read mode (sync or async) depends on
* the SysConfig1 Register
* @param[out] pnWordRdCycle: read cycle (nano second) for word.
* @param[out] pnWordWrCycle: write cycle (nano second) for word.
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_CalcTransferTime(UINT32 nDev,
UINT16 nSysConf1Reg,
UINT32 *pnWordRdCycle,
UINT32 *pnWordWrCycle)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
UINT32 nPgIdx;
UINT32 nNumOfPgs = 1;
UINT32 nPageSize;
/* theoretical read cycle for word (2 byte) from OneNAND to host */
UINT32 nTheoreticalRdCycle;
UINT32 nWordRdCycle;
UINT32 nWordWrCycle;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d)\r\n"), __FSR_FUNC__, nDev));
/* nPageSize is 4096 byte */
nPageSize = pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE;
/* calculate write cycle for word */
/* here 0x55 has no meaning */
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0x55, nPageSize);
#if !defined(FSR_OAM_RTLMSG_DISABLE)
FSR_OAM_StartTimer();
#endif
for (nPgIdx = 0; nPgIdx < nNumOfPgs; nPgIdx++)
{
TRANSFER_TO_NAND(pstFOReg->nDataMB00,
pstFNDCxt->pTempBuffer,
nPageSize);
}
#if !defined(FSR_OAM_RTLMSG_DISABLE)
FSR_OAM_StopTimer();
#endif
#if !defined(FSR_OAM_RTLMSG_DISABLE)
/* nWordWrCycle is based on nano second
* FSR_OAM_GetElapsedTime() returns elapsed time in usec
*/
nWordWrCycle = 2 * 1000 * FSR_OAM_GetElapsedTime() / (nNumOfPgs * nPageSize);
#else
nWordWrCycle = 0;
#endif
if (nWordWrCycle < 70)
{
*pnWordWrCycle = nWordWrCycle = 70;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] assuming Word Write Cycle: %d nano second\r\n"),
nWordWrCycle));
}
else
{
*pnWordWrCycle = nWordWrCycle;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] Transfered %d bytes to DataRAM in %d usec\r\n"),
nNumOfPgs * nPageSize,
FSR_OAM_GetElapsedTime()));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT(" calculated Word Write Cycle: %d nano second\r\n"),
nWordWrCycle));
}
/* calculate read cycle for word */
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0xFF, nPageSize);
#if !defined(FSR_OAM_RTLMSG_DISABLE)
FSR_OAM_StartTimer();
#endif
for (nPgIdx = 0; nPgIdx < nNumOfPgs; nPgIdx++)
{
TRANSFER_FROM_NAND(pstFNDCxt->pTempBuffer,
pstFOReg->nDataMB00,
nPageSize);
}
#if !defined(FSR_OAM_RTLMSG_DISABLE)
FSR_OAM_StopTimer();
#endif
/* time for transfering 16 bits depends on bRM (read mode) */
nTheoreticalRdCycle = (nSysConf1Reg & FSR_FND_CONF1_SYNC_READ) ? 25 : 76;
#if !defined(FSR_OAM_RTLMSG_DISABLE)
/* nByteRdCycle is based on nano second
* FSR_OAM_GetElapsedTime() returns elapsed time in usec
*/
nWordRdCycle = 2 * 1000 * FSR_OAM_GetElapsedTime() / (nNumOfPgs * nPageSize);
#else
nWordRdCycle = 0;
#endif
if (nWordRdCycle < nTheoreticalRdCycle)
{
*pnWordRdCycle = nWordRdCycle = nTheoreticalRdCycle;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] assuming Word Read Cycle: %d nano second\r\n"),
nWordRdCycle));
}
else
{
*pnWordRdCycle = nWordRdCycle;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT("[FND:INF] Transfered %d bytes from DataRAM in %d usec\r\n"),
nNumOfPgs * nPageSize,
FSR_OAM_GetElapsedTime()));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF,
(TEXT(" calculated Word Read Cycle: %d nano second\r\n"),
nWordRdCycle));
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s(nDev:%d)\r\n"), __FSR_FUNC__, nDev));
}
#if defined (FSR_LLD_STATISTICS)
/**
* @brief this function is called within the LLD function
* @n to total the busy time of the device
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] nType : FSR_FND_STAT_SLC_PGM
* @n FSR_FND_STAT_LSB_PGM
* @n FSR_FND_STAT_MSB_PGM
* @n FSR_FND_STAT_ERASE
* @n FSR_FND_STAT_SLC_LOAD
* @n FSR_FND_STAT_MLC_LOAD
* @n FSR_FND_STAT_RD_TRANS
* @n FSR_FND_STAT_WR_TRANS
* @n FSR_FND_STAT_FLUSH
* @param[in] nBytes : the number of bytes to transfer from/to DataRAM
* @param[in] nCmdOption : command option such cache, superload
* @n which can hide transfer time
*
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_AddFNDStat(UINT32 nDev,
UINT32 nDie,
UINT32 nType,
UINT32 nBytes,
UINT32 nCmdOption)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
UINT32 nVol;
UINT32 nDevIdx; /* device index within a volume (0~4) */
UINT32 nPDevIdx;/* physical device index (0~7) */
UINT32 nDieIdx;
UINT32 nNumOfDies;
/* the duration of Interrupt Low after command is issued */
INT32 nIntLowTime;
INT32 nTransferTime;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
nIntLowTime = pstFNDCxt->nIntLowTime[nDie];
switch (nType)
{
case FSR_FND_STAT_SLC_PGM:
pstFNDCxt->nNumOfSLCPgms++;
if (nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
/* if nCmdOption is CACHE, transfering time can be hided */
pstFNDCxt->nPreCmdOption[nDie] = nCmdOption;
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_WR_SW_OH + pstFNDSpec->nSLCTProgTime;
if (nCmdOption == FSR_FND_STAT_CACHE_PGM)
{
pstFNDCxt->nNumOfCacheBusy++;
}
break;
case FSR_FND_STAT_LSB_PGM:
pstFNDCxt->nNumOfLSBPgms++;
if (nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
/* if nCmdOption is CACHE, transfering time can be hided */
pstFNDCxt->nPreCmdOption[nDie] = nCmdOption;
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_WR_SW_OH + pstFNDSpec->nMLCTProgTime[0];
if (nCmdOption == FSR_FND_STAT_CACHE_PGM)
{
pstFNDCxt->nNumOfCacheBusy++;
}
break;
case FSR_FND_STAT_MSB_PGM:
pstFNDCxt->nNumOfMSBPgms++;
if (nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
/* if nCmdOption is CACHE, transfering time can be hided */
pstFNDCxt->nPreCmdOption[nDie] = nCmdOption;
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_WR_SW_OH + pstFNDSpec->nMLCTProgTime[1];
if (nCmdOption == FSR_FND_STAT_CACHE_PGM)
{
pstFNDCxt->nNumOfCacheBusy++;
}
break;
case FSR_FND_STAT_ERASE:
pstFNDCxt->nNumOfErases++;
if (nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
pstFNDCxt->nIntLowTime[nDie] = pstFNDSpec->nTEraseTime;
break;
case FSR_FND_STAT_SLC_LOAD:
pstFNDCxt->nNumOfSLCLoads++;
if(nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
if (nCmdOption == FSR_FND_STAT_PLOAD)
{
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_RD_SW_OH +
pstFNDSpec->nSLCTLoadTime - FSR_FND_PAGEBUF_TO_DATARAM_TIME;
}
else
{
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_RD_SW_OH +
pstFNDSpec->nSLCTLoadTime;
}
pstFNDCxt->nPreCmdOption[nDie] = nCmdOption;
break;
case FSR_FND_STAT_MLC_LOAD:
pstFNDCxt->nNumOfMLCLoads++;
if(nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
if (nCmdOption == FSR_FND_STAT_PLOAD)
{
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_RD_SW_OH +
pstFNDSpec->nMLCTLoadTime - FSR_FND_PAGEBUF_TO_DATARAM_TIME;
}
else
{
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_RD_SW_OH +
pstFNDSpec->nMLCTLoadTime;
}
pstFNDCxt->nPreCmdOption[nDie] = nCmdOption;
break;
case FSR_FND_STAT_RD_TRANS:
pstFNDCxt->nNumOfRdTrans++;
pstFNDCxt->nRdTransInBytes += nBytes;
nTransferTime = nBytes * pstFNDCxt->nRdTranferTime / 2 / 1000;
if ((nCmdOption != FSR_FND_STAT_PLOAD) && (nIntLowTime > 0))
{
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
gnElapsedTime += nTransferTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nTransferTime;
}
}
}
}
if (nCmdOption == FSR_FND_STAT_PLOAD)
{
pstFNDCxt->nIntLowTime[nDie] = FSR_FND_PAGEBUF_TO_DATARAM_TIME;
}
else
{
pstFNDCxt->nIntLowTime[nDie] = 0;
}
break;
case FSR_FND_STAT_WR_TRANS:
pstFNDCxt->nNumOfWrTrans++;
pstFNDCxt->nWrTransInBytes += nBytes;
nTransferTime = nBytes * pstFNDCxt->nWrTranferTime / 2 / 1000;
/* cache operation can hide transfer time */
if((pstFNDCxt->nPreCmdOption[nDie] == FSR_FND_STAT_CACHE_PGM) && (nIntLowTime >= 0))
{
gnElapsedTime += nTransferTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nTransferTime;
}
}
}
}
if(nIntLowTime < nTransferTime)
{
pstFNDCxt->nIntLowTime[nDie] = 0;
}
}
else /* transfer time cannot be hided */
{
if(nIntLowTime > 0)
{
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
}
gnElapsedTime += nTransferTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nTransferTime;
}
}
}
}
pstFNDCxt->nIntLowTime[nDie] = 0;
}
break;
case FSR_FND_STAT_FLUSH:
if (nIntLowTime > 0)
{
/* wait INT for previous operation */
gnElapsedTime += nIntLowTime;
for (nVol = 0; nVol < FSR_MAX_VOLS; nVol++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVol]; nDevIdx++)
{
nPDevIdx = nVol * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx;
nNumOfDies = gpstFNDCxt[nPDevIdx]->pstFNDSpec->nNumOfDies;
for (nDieIdx = 0; nDieIdx < nNumOfDies; nDieIdx++)
{
if (gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] > 0)
{
gpstFNDCxt[nPDevIdx]->nIntLowTime[nDieIdx] -= nIntLowTime;
}
}
}
}
pstFNDCxt->nIntLowTime[nDie] = 0;
}
break;
default:
break;
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function is same as _AddFNDStat().
* @n but in the needs of classifying SLC, LSB, MSB programming
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] nPbn : Physical block Number
* @param[in] nPage : page offset within the block
* @param[in] nCmdOption : command option such as cache, superload
* @n which hide transfer time.
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark Pbn is consecutive numbers within the device
* @n i.e. for DDP device, Pbn for 1st block in 2nd chip is not 0
* @n it is one more than the last block number in 1st chip
*
*/
PRIVATE VOID
_AddFNDStatPgm(UINT32 nDev,
UINT32 nDie,
UINT32 nPbn,
UINT32 nPage,
UINT32 nCmdOption)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FlexONDSpec *pstFNDSpec = pstFNDCxt->pstFNDSpec;
UINT32 nBlkOffset;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
/* block offset within the die */
nBlkOffset = nPbn - nDie * pstFNDSpec->nNumOfBlks / pstFNDSpec->nNumOfDies;
if (pstFNDCxt->nBlksForSLCArea[nDie] <= nBlkOffset)
{
/* program is performed on MLC block */
if (nPage < gnPairPgMap[nPage])
{
_AddFNDStat(nDev, nDie, FSR_FND_STAT_LSB_PGM, 0, nCmdOption);
}
else
{
_AddFNDStat(nDev, nDie, FSR_FND_STAT_MSB_PGM, 0, nCmdOption);
}
}
else
{
/* program is performed on SLC block */
_AddFNDStat(nDev, nDie, FSR_FND_STAT_SLC_PGM, 0, nCmdOption);
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function is same as _AddFNDStat().
* @n but in need of classifying SLC, MLC load
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] nPbn : Physical block Number
* @param[in] nCmdOption : command option such as cache, superload
* @n which hides transfer time.
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark Pbn is consecutive numbers within the device
* @n i.e. for DDP device, Pbn for 1st block in 2nd chip is not 0
* @n it is one more than the last block number in 1st chip
*
*/
PRIVATE VOID
_AddFNDStatLoad(UINT32 nDev,
UINT32 nDie,
UINT32 nPbn,
UINT32 nCmdOption)
{
FlexONDCxt *pstFNDCxt = gpstFNDCxt[nDev];
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
if (pstFNDCxt->nBlksForSLCArea[nDie] <= (nPbn & pstFNDCxt->nFBAMask))
{
/* operation is performed on MLC block */
_AddFNDStat(nDev, nDie, FSR_FND_STAT_MLC_LOAD, 0, nCmdOption);
}
else
{
/* operation is performed on SLC block */
_AddFNDStat(nDev, nDie, FSR_FND_STAT_SLC_LOAD, 0, nCmdOption);
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
#endif /* #if defined (FSR_LLD_STATISTICS) */
#if defined (FSR_LLD_LOGGING_HISTORY)
/**
* @brief This function leave a trace for the LLD function call
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : Die(Chip) index
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
VOID
_AddLog(UINT32 nDev, UINT32 nDie)
{
FlexONDShMem *pstFNDShMem;
volatile FlexONDOpLog *pstFNDOpLog;
UINT32 nLogHead;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG ,
(TEXT("[FND:IN ] ++%s(nDie: %d)\r\n"), __FSR_FUNC__, nDie));
pstFNDShMem = gpstFNDShMem[nDev];
pstFNDOpLog = &gstFNDOpLog[nDev];
nLogHead = pstFNDOpLog->nLogHead;
pstFNDOpLog->nLogOp [nLogHead] = pstFNDShMem->nPreOp[nDie];
pstFNDOpLog->nLogPbn [nLogHead] = pstFNDShMem->nPreOpPbn[nDie];
pstFNDOpLog->nLogPgOffset [nLogHead] = pstFNDShMem->nPreOpPgOffset[nDie];
pstFNDOpLog->nLogFlag [nLogHead] = pstFNDShMem->nPreOpFlag[nDie];
pstFNDOpLog->nLogHead = (nLogHead + 1) & (FSR_FND_MAX_LOG -1);
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
#endif /* #if defined (FSR_LLD_LOGGING_HISTORY) */
/**
* @brief this function initialize the structure for LLD statistics
*
* @return FSR_LLD_SUCCESS
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_InitLLDStat(VOID)
{
#if defined (FSR_LLD_STATISTICS)
FlexONDCxt *pstFNDCxt;
UINT32 nVolIdx;
UINT32 nDevIdx;
UINT32 nDieIdx;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
gnElapsedTime = 0;
for (nVolIdx = 0; nVolIdx < FSR_MAX_VOLS; nVolIdx++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVolIdx]; nDevIdx++)
{
pstFNDCxt = gpstFNDCxt[nVolIdx * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx];
pstFNDCxt->nNumOfSLCLoads = 0;
pstFNDCxt->nNumOfSLCLoads = 0;
pstFNDCxt->nNumOfMLCLoads = 0;
pstFNDCxt->nNumOfSLCPgms = 0;
pstFNDCxt->nNumOfLSBPgms = 0;
pstFNDCxt->nNumOfMSBPgms = 0;
pstFNDCxt->nNumOfCacheBusy= 0;
pstFNDCxt->nNumOfErases = 0;
pstFNDCxt->nNumOfRdTrans = 0;
pstFNDCxt->nNumOfWrTrans = 0;
pstFNDCxt->nRdTransInBytes= 0;
pstFNDCxt->nWrTransInBytes= 0;
for (nDieIdx = 0; nDieIdx < FSR_MAX_DIES; nDieIdx++)
{
pstFNDCxt->nPreCmdOption[nDieIdx] = FSR_FND_STAT_NORMAL_CMD;
pstFNDCxt->nIntLowTime[nDieIdx] = 0;
}
}
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
#endif
return FSR_LLD_SUCCESS;
}
/**
* @brief this function totals the time device consumed.
*
* @param[out] pstStat : the pointer to the structure, FSRLLDStat
*
* @return total busy time of whole device
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PUBLIC INT32
FSR_FND_GetStat(FSRLLDStat *pstStat)
{
#if defined (FSR_LLD_STATISTICS)
FlexONDCxt *pstFNDCxt;
FlexONDSpec *pstFNDSpec;
UINT32 nDevIdx;
UINT32 nTotalTime;
UINT32 nVolIdx;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s()\r\n"), __FSR_FUNC__));
FSR_OAM_MEMSET(pstStat, 0x00, sizeof(FSRLLDStat));
nTotalTime = 0;
for (nVolIdx = 0; nVolIdx < FSR_MAX_VOLS; nVolIdx++)
{
for (nDevIdx = 0; nDevIdx < gnDevsInVol[nVolIdx]; nDevIdx++)
{
pstFNDCxt = gpstFNDCxt[nVolIdx * FSR_MAX_DEVS / FSR_MAX_VOLS + nDevIdx];
pstStat->nSLCPgms += pstFNDCxt->nNumOfSLCPgms;
pstStat->nLSBPgms += pstFNDCxt->nNumOfLSBPgms;
pstStat->nMSBPgms += pstFNDCxt->nNumOfMSBPgms;
pstStat->nErases += pstFNDCxt->nNumOfErases;
pstStat->nSLCLoads += pstFNDCxt->nNumOfSLCLoads;
pstStat->nMLCLoads += pstFNDCxt->nNumOfMLCLoads;
pstStat->nRdTrans += pstFNDCxt->nNumOfRdTrans;
pstStat->nWrTrans += pstFNDCxt->nNumOfWrTrans;
pstStat->nCacheBusy += pstFNDCxt->nNumOfCacheBusy;
pstStat->nRdTransInBytes += pstFNDCxt->nRdTransInBytes;
pstStat->nWrTransInBytes += pstFNDCxt->nWrTransInBytes;
pstFNDSpec = pstFNDCxt->pstFNDSpec;
/* nTotaltime can be compared with gnElapsedTime */
nTotalTime += pstStat->nSLCLoads * pstFNDSpec->nSLCTLoadTime;
nTotalTime += pstStat->nMLCLoads * pstFNDSpec->nMLCTLoadTime;
nTotalTime += pstStat->nSLCPgms * pstFNDSpec->nSLCTProgTime;
nTotalTime += pstStat->nLSBPgms * pstFNDSpec->nMLCTProgTime[0];
nTotalTime += pstStat->nMSBPgms * pstFNDSpec->nMLCTProgTime[1];
nTotalTime += pstStat->nErases * pstFNDSpec->nTEraseTime;
/* pstFNDCxt->nRdTranferTime, pstFNDCxt->nWrTranferTime is time for transfering 2 bytes
* which is nano second base
* to get a time in micro second, divide it by 1000
*/
nTotalTime += pstStat->nRdTransInBytes * pstFNDCxt->nRdTranferTime / 2 / 1000;
nTotalTime += pstStat->nWrTransInBytes * pstFNDCxt->nWrTranferTime / 2 / 1000;
nTotalTime += pstStat->nCacheBusy * FSR_FND_CACHE_BUSY_TIME;
}
}
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF | FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return gnElapsedTime;
#else
FSR_OAM_MEMSET(pstStat, 0x00, sizeof(FSRLLDStat));
return 0;
#endif /* #if defined (FSR_LLD_STATISTICS) */
}
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
/**
* @brief this function saves the contents of DataRAM & ctrl register
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] pstFNDCxt : pointer to FlexONDCxt
* @param[in] nLLDRe : error type
*
* @return none
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE VOID
_SaveErrorCxt( UINT32 nDev,
UINT32 nDie,
FlexONDCxt *pstFNDCxt,
INT32 nLLDRe)
{
FlexONDSpec *pstFNDSpec;
volatile FlexONDSharedCxt *pstFNDSharedCxt;
volatile FlexOneNANDReg *pstFOReg = (volatile FlexOneNANDReg *) pstFNDCxt->nBaseAddr;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG | FSR_DBZ_ERROR,
(TEXT("[FND:IN ] ++%s(nDev: %d, nDie:%d, nLLDRe:0x%08x)\r\n"),
__FSR_FUNC__, nDev, nDie, nLLDRe));
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
/* save the error returned */
pstFNDSharedCxt->nHostLLDRe[nDie] = nLLDRe;
/* to print debug message */
pstFNDSharedCxt->nErrCtrlReg[nDie] = FND_READ(pstFOReg->nCtrlStat);
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] pstFNDSharedCxt->nHostLLDRe[%d] = 0x%08x\r\n"),
pstFNDSharedCxt->nHostLLDRe[nDie]));
pstFNDSpec = pstFNDCxt->pstFNDSpec;
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_PREV_WRITE_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] saving the error context for write error\r\n")));
/* save DataRAM for bad block handling */
TRANSFER_FROM_NAND((UINT8 *) &pstFNDSharedCxt->nErrMainDataRAM[nDie][0],
&pstFOReg->nDataMB00[0],
pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE);
TRANSFER_FROM_NAND((UINT8 *) &pstFNDSharedCxt->nErrSpareDataRAM[nDie][0],
&pstFOReg->nDataSB00[0],
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct);
}
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_PREV_ERASE_ERROR)
{
/* do nothing for erase error */
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] saving the error context for erase error\r\n")));
}
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_LOG | FSR_DBZ_ERROR,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
}
/**
* @brief this function restores the contents of DataRAM & ctrl register
*
* @param[in] nDev : Physical Device Number (0 ~ 3)
* @param[in] nDie : die(chip) number (0 or 1) for DDP device
* @param[in] pstFNDCxt : pointer to FlexONDCxt
* @param[in] pstFOReg : pointer to FlexOneNANDReg
*
* @return FSR_LLD_SUCCESS
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n error for normal program
* @return FSR_LLD_PREV_WRITE_ERROR | {FSR_LLD_1STPLN_PREV_ERROR}
* @n error for cache program
* @return FSR_LLD_PREV_ERASE_ERROR | {FSR_LLD_1STPLN_CURR_ERROR}
* @n erase error for previous erase operation
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE INT32
_CheckErrorCxt( UINT32 nDev,
UINT32 nDie,
FlexONDCxt *pstFNDCxt,
volatile FlexOneNANDReg *pstFOReg)
{
FlexONDSpec *pstFNDSpec;
FlexONDShMem *pstFNDShMem = gpstFNDShMem[nDev];
volatile FlexONDSharedCxt *pstFNDSharedCxt;
INT32 nLLDRe;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:IN ] ++%s(nDev:%d, nDie:%d)\r\n"),
__FSR_FUNC__, nDev, nDie));
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
nLLDRe = pstFNDSharedCxt->nHostLLDRe[nDie];
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_PREV_WRITE_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" CtrlReg=0x%04x\r\n"),
pstFNDSharedCxt->nErrCtrlReg[nDie]));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT(" prev Op:%d @ nDev:%d, nPbn:%d, nPgOffset:%d, nFlag:0x%08x\r\n"),
pstFNDShMem->nPreOp[nDie], nDev, pstFNDShMem->nPreOpPbn[nDie],
pstFNDShMem->nPreOpPgOffset[nDie], pstFNDShMem->nPreOpFlag[nDie]));
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] restoring the error cxt for write error\r\n")));
pstFNDSpec = pstFNDCxt->pstFNDSpec;
TRANSFER_TO_NAND(&pstFOReg->nDataMB00[0],
(UINT8 *) &pstFNDSharedCxt->nErrMainDataRAM[nDie][0],
pstFNDSpec->nSctsPerPG * FSR_FND_SECTOR_SIZE);
TRANSFER_TO_NAND(&pstFOReg->nDataSB00[0],
(UINT8 *) &pstFNDSharedCxt->nErrSpareDataRAM[nDie][0],
pstFNDSpec->nSctsPerPG * pstFNDSpec->nSparePerSct);
}
if (FSR_RETURN_MAJOR(nLLDRe) == FSR_LLD_PREV_ERASE_ERROR)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF | FSR_DBZ_ERROR,
(TEXT("[FND:INF] restoring the error cxt for erase error\r\n")));
/* do nothing */
}
pstFNDSharedCxt->nHostLLDRe[nDie] = FSR_LLD_SUCCESS;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_LOG,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return nLLDRe;
}
#endif
/**
* @brief This function gets the unique ID from OTP Block
*
* @param[in] nDev : Physical Device Number (0 ~ 7)
* @param[in] pstFNDCxt : pointer to the structure FlexONDCxt
* @param[in] nFlag : bypass nFlag from GetDevSpec()
*
* @return FSR_LLD_SUCCESS
*
* @author NamOh Hwang
* @version 1.0.0
* @remark
*
*/
PRIVATE INT32
_GetUniqueID(UINT32 nDev,
FlexONDCxt *pstFNDCxt,
UINT32 nFlag)
{
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
volatile FlexONDSharedCxt *pstFNDSharedCxt = NULL;
#endif
FlexONDSpec *pstFNDSpec;
UINT32 nDie = 0;
UINT32 nPbn;
UINT32 nPgOffset;
UINT32 nByteRet;
UINT32 nIdx;
UINT32 nCnt;
UINT32 nSizeOfUID;
UINT32 nSparePerSct;
INT32 nLLDRe = FSR_LLD_SUCCESS;
INT32 nRet = 0;
BOOL32 bValidUID;
UINT8 *pUIDArea = NULL;
UINT8 *pSignature = NULL;
FSR_STACK_VAR;
FSR_STACK_END;
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF,
(TEXT("[FND:IN ] ++%s(nDev:%d, nDie:%d)\r\n"),
__FSR_FUNC__, nDev, nDie));
do
{
/* set OTP access mode */
nLLDRe = FSR_FND_IOCtl(nDev, /* nDev : Physical Device Number (0 ~ 7) */
FSR_LLD_IOCTL_OTP_ACCESS, /* nCode : IO Control Command */
(UINT8 *) &nDie, /* *pBufI : Input Buffer pointer */
sizeof(nDie), /* nLenI : Length of Input Buffer */
NULL, /* *pBufO : Output Buffer pointer */
0, /* nLenO : Length of Output Buffer */
&nByteRet); /* *pByteRet : The number of bytes (length) of
Output Buffer as the result of
function call */
if (FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS)
{
break;
}
FSR_ASSERT(pstFNDCxt != NULL);
FSR_ASSERT(pstFNDCxt->pstFNDSpec != NULL);
pstFNDSpec = pstFNDCxt->pstFNDSpec;
nSparePerSct = pstFNDSpec->nSparePerSct;
FSR_OAM_MEMSET(pstFNDCxt->pTempBuffer, 0x00,
pstFNDSpec->nSctsPerPG * (FSR_SECTOR_SIZE + nSparePerSct));
/* Unique ID is located at page 60 of OTP block */
nPgOffset = 60;
nPbn = 0;
pUIDArea = pstFNDCxt->pTempBuffer;
pSignature = pstFNDCxt->pTempBuffer + (pstFNDSpec->nSctsPerPG * FSR_SECTOR_SIZE);
nLLDRe = FSR_FND_Read(nDev, nPbn, nPgOffset,
pUIDArea, (FSRSpareBuf *) pSignature,
FSR_LLD_FLAG_DUMP_ON | FSR_LLD_FLAG_ECC_OFF |
FSR_LLD_FLAG_USE_SPAREBUF | nFlag);
if (FSR_RETURN_MAJOR(nLLDRe) != FSR_LLD_SUCCESS)
{
break;
}
/*
* ##UniqueID Verification sequence##
* STEP 1. check 16 bytes data in spare area.
* - the set must be checked minimum 1set out of 4sets
* - 1set has a value that '0x5555AAAA(4B)' is repeated four times
* STEP 2. check complement data in data area
* - the set must be checked minimum 1set out of 8sets
*/
/* STEP 1 : check signature */
/* | Spare0 (16B) | Spare1 (16B) | Spare2 (16B) | Spare3 (16B) |
* |--------------+--------------+--------------+--------------|
* | 0xAAAA5555 | All 0xFFFF |
*/
bValidUID = FALSE32;
for (nIdx = 0; nIdx < nSparePerSct; nIdx += 4)
{
if ((pSignature[nIdx] == 0x55) && (pSignature[nIdx + 2] == 0xAA))
{
bValidUID = TRUE32;
break;
}
}
if (bValidUID != TRUE32)
{
break;
}
/* STEP 2 : check complenent data */
/* | Unique ID (512B) | Reserved (512B) | Reserved (512B) | Reserved (512B) |
* |---------------------+-----------------+-----------------+-----------------|
* | ID(32B) & Cplmt(32B)| All 0xFFFF |
*/
bValidUID = FALSE32;
/* nSizeOfUID is 32 byte */
nSizeOfUID = (FSR_SECTOR_SIZE / FSR_FND_NUM_OF_UID) / 2;
for (nCnt = 0; nCnt < FSR_FND_NUM_OF_UID; nCnt++)
{
for (nIdx = 0; nIdx < nSizeOfUID; nIdx++)
{
pUIDArea[nSizeOfUID + nIdx] = (UINT8) ~pUIDArea[nSizeOfUID + nIdx];
}
nRet = FSR_OAM_MEMCMP(pUIDArea, pUIDArea + nSizeOfUID, nSizeOfUID);
if (nRet == 0)
{
bValidUID = TRUE32;
break;
}
/* skip 64 byte */
pUIDArea += (FSR_SECTOR_SIZE / FSR_FND_NUM_OF_UID);
}
if (bValidUID == FALSE32)
{
FSR_DBZ_RTLMOUT(FSR_DBZ_LLD_INF, (TEXT("[FND:ERR] Invalid UID\r\n")));
break;
}
/* Get Unique ID */
for (nIdx = 0; nIdx < FSR_LLD_UID_SIZE; nIdx++)
{
pstFNDCxt->nUID[nIdx] = pUIDArea[2 * nIdx];
}
} while (0);
/* exit the OTP block */
nLLDRe = FSR_FND_IOCtl(nDev, /* nDev : Physical Device Number (0 ~ 7) */
FSR_LLD_IOCTL_CORE_RESET, /* nCode : IO Control Command */
NULL, /* *pBufI : Input Buffer pointer */
0, /* nLenI : Length of Input Buffer */
NULL, /* *pBufO : Output Buffer pointer */
0, /* nLenO : Length of Output Buffer */
&nByteRet); /* *pByteRet : The number of bytes (length) of
Output Buffer as the result of
function call */
#if defined (FSR_LLD_HANDSHAKE_ERR_INF)
pstFNDSharedCxt = &gstFNDSharedCxt[nDev];
pstFNDSharedCxt->nPrevFSRMode[nDie] = nFlag & FSR_LLD_FLAG_READ_ONLY;
pstFNDSharedCxt->nHostLLDOp[nDie] = FSR_FND_PREOP_IOCTL;
pstFNDSharedCxt->nHostLLDPbn[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDSharedCxt->nHostLLDPgOffset[nDie] = FSR_FND_PREOP_ADDRESS_NONE;
pstFNDSharedCxt->nHostLLDFlag[nDie] = nFlag;
#endif
FSR_DBZ_DBGMOUT(FSR_DBZ_LLD_IF,
(TEXT("[FND:OUT] --%s()\r\n"), __FSR_FUNC__));
return (nLLDRe);
}
|
r3d4/samsung_kernel_nowplus
|
samsung/rfs_fsr/drivers/tfsr/LLD/FlexOND_MSM7k/FSR_LLD_FlexOND.c
|
C
|
gpl-2.0
| 272,209
|
#include "main_window_model_impl.h"
#include "main_window.h"
#include "tab_context.h"
#include "file_context.h"
#include "base/exception.h"
#include "gui_impl/commands/open_file_gui_command.h"
#include "gui_impl/signal_browser/signal_browser_model_4.h"
#include "gui_impl/signal_browser/signal_browser_view.h"
#include "gui_impl/event_table/event_table_widget.h"
#include <QSettings>
#include <QDebug>
namespace SigViewer_
{
int const MainWindowModelImpl::NUMBER_RECENT_FILES_ = 8;
//-----------------------------------------------------------------------------
MainWindowModelImpl::MainWindowModelImpl (QSharedPointer<ApplicationContext> application_context)
: application_context_ (application_context),
main_window_ (new MainWindow (application_context)),
tab_widget_ (0)
{
connect (main_window_, SIGNAL(recentFileActivated(QAction*)), SLOT(recentFileActivated(QAction*)));
connect (main_window_, SIGNAL(recentFileMenuAboutToShow()), SLOT(recentFileMenuAboutToShow()));
main_window_->show();
loadSettings();
}
//-----------------------------------------------------------------------------
MainWindowModelImpl::~MainWindowModelImpl ()
{
qDebug () << "deleting MainWindowModelImpl";
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::loadSettings()
{
QSettings settings("SigViewer");
settings.beginGroup("MainWindowModelImpl");
int size = settings.beginReadArray("recent_file");
for (int i = 0; i < size; i++)
{
settings.setArrayIndex(i);
recent_file_list_.append(settings.value("name").toString());
}
settings.endArray();
settings.endGroup();
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::saveSettings()
{
QSettings settings("SigViewer");
settings.beginGroup("MainWindowModelImpl");
settings.beginWriteArray("recent_file");
for (int i = 0; i < recent_file_list_.size(); i++)
{
settings.setArrayIndex(i);
settings.setValue("name", recent_file_list_.at(i));
}
settings.endArray();
settings.endGroup();
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::tabChanged (int tab_index)
{
if (tab_contexts_.find(tab_index) != tab_contexts_.end ())
{
application_context_->setCurrentTabContext (tab_contexts_[tab_index]);
tab_contexts_[tab_index]->gotActive ();
}
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::closeTab (int tab_index)
{
if (tab_index == 0)
{
if (!(application_context_->getCurrentFileContext().isNull()))
GuiActionFactory::getInstance()->getQAction("Close")->trigger();
return;
} else if (tab_index == 1)
return;
QWidget* widget = tab_widget_->widget (tab_index);
browser_models_.erase (tab_index);
tab_widget_->removeTab (tab_index);
delete widget;
int models_count = browser_models_.size();
if (models_count >= tab_index)
{
for (int index = tab_index + 1; index < models_count; index++)
browser_models_[index - 1] = browser_models_[index];
}
int event_views_count = event_views_.size();
if (event_views_count >= tab_index)
{
for (int index = tab_index + 1; index < event_views_count; index++)
if (event_views_.contains (index))
event_views_[index - 1] = event_views_[index];
}
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::recentFileMenuAboutToShow()
{
main_window_->setRecentFiles(recent_file_list_);
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::recentFileActivated(QAction* recent_file_action)
{
OpenFileGuiCommand::openFile (recent_file_action->text());
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::storeAndInitTabContext (QSharedPointer<TabContext> context, int tab_index)
{
tab_contexts_[tab_index] = context;
application_context_->setCurrentTabContext (context);
context->setSelectionState (TAB_STATE_NO_EVENT_SELECTED);
context->setEditState (TAB_STATE_NO_REDO_NO_UNDO);
}
//-------------------------------------------------------------------------
QSharedPointer<SignalVisualisationModel> MainWindowModelImpl::createSignalVisualisation (QString const& title, ChannelManager const& channel_manager)
{
int tab_index = createSignalVisualisationImpl (channel_manager, QSharedPointer<EventManager>(0));
tab_widget_->setTabText(tab_index, title);
tab_widget_->setCurrentIndex(tab_index);
return browser_models_[tab_index];
}
//-----------------------------------------------------------------------------
QSharedPointer<SignalVisualisationModel> MainWindowModelImpl::createSignalVisualisationOfFile (QSharedPointer<FileContext> file_ctx)
{
// waldesel:
// --begin
// to be replaced as soon as multi file support is implemented
if (!(application_context_->getCurrentFileContext().isNull()))
GuiActionFactory::getInstance()->getQAction("Close")->trigger();
// --end
if (!tab_widget_)
{
tab_widget_ = new QTabWidget (main_window_);
if (!connect (tab_widget_, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))))
throw (Exception ("MainWindowModelImpl::createSignalVisualisationOfFile failed: connect (tab_widget_, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)))"));
connect (tab_widget_, SIGNAL(tabCloseRequested(int)), SLOT(closeTab(int)));
tab_widget_->setTabsClosable (true);
}
recent_file_list_.removeAll (file_ctx->getFilePathAndName());
if (recent_file_list_.size() == NUMBER_RECENT_FILES_)
recent_file_list_.pop_back();
recent_file_list_.push_front (file_ctx->getFilePathAndName());
saveSettings();
// waldesel:
// --begin
// to be replaced as soon as new zooming is implemented
main_window_->setStatusBarSignalLength (file_ctx->getChannelManager().getDurationInSec());
// --end
main_window_->setStatusBarNrChannels (file_ctx->getChannelManager().getNumberChannels());
resetCurrentFileName (file_ctx->getFileName());
connect (file_ctx.data(), SIGNAL(fileNameChanged(QString const&)), SLOT(resetCurrentFileName(QString const&)));
int tab_index = createSignalVisualisationImpl (file_ctx->getChannelManager(), file_ctx->getEventManager());
QString tab_title ("Signal Data");
main_window_->setCentralWidget(tab_widget_);
tab_widget_->show();
tab_widget_->setTabText(tab_index, tab_title);
file_ctx->setMainVisualisationModel (browser_models_[tab_index]);
return browser_models_[tab_index];
}
//-----------------------------------------------------------------------------
void MainWindowModelImpl::closeCurrentFileTabs ()
{
// waldesel:
// --begin
// to be refactored as soon as multi file support is implemented
main_window_->setCentralWidget (0);
tab_widget_ = 0;
tab_contexts_.clear ();
// --end
main_window_->setStatusBarSignalLength(-1);
main_window_->setStatusBarNrChannels(-1);
resetCurrentFileName ("");
}
//-----------------------------------------------------------------------------
QSharedPointer<SignalVisualisationModel> MainWindowModelImpl::getCurrentSignalVisualisationModel ()
{
if (!tab_widget_)
return QSharedPointer<SignalVisualisationModel>(0);
return browser_models_[tab_widget_->currentIndex()];
}
//-------------------------------------------------------------------------
QSharedPointer<EventView> MainWindowModelImpl::getCurrentEventView ()
{
if (!tab_widget_)
return QSharedPointer<EventView>(0);
if (!event_views_.contains (tab_widget_->currentIndex()))
return QSharedPointer<EventView>(0);
return event_views_[tab_widget_->currentIndex()];
}
//-------------------------------------------------------------------------
void MainWindowModelImpl::resetCurrentFileName (QString const& file_name)
{
if (file_name.size() == 0)
main_window_->setWindowTitle (tr("SigViewer"));
else
main_window_->setWindowTitle (file_name + tr(" - SigViewer"));
}
//-------------------------------------------------------------------------
int MainWindowModelImpl::createSignalVisualisationImpl (ChannelManager const& channel_manager,
QSharedPointer<EventManager> event_manager)
{
QSharedPointer<TabContext> tab_context (new TabContext);
QSharedPointer<SignalBrowserModel> model (new SignalBrowserModel (event_manager,
channel_manager,
tab_context,
application_context_->getEventColorManager()));
SignalBrowserView* view = new SignalBrowserView (model, event_manager, tab_context, main_window_->rect(), tab_widget_);
int tab_index = tab_widget_->addTab (view, tr("Signal"));
model->setSignalBrowserView (view);
browser_models_[tab_index] = model;
event_views_[tab_index] = model;
if (!event_manager.isNull())
{
EventTableWidget* event_table_widget = new EventTableWidget (tab_context, event_manager, channel_manager);
int event_tab_index = tab_widget_->addTab (event_table_widget, tr("Events"));
browser_models_[event_tab_index] = QSharedPointer<SignalBrowserModel>(0);
event_views_[event_tab_index] = event_table_widget->getEventView();
tab_contexts_[event_tab_index] = tab_context;
model->connect (event_manager.data(), SIGNAL(eventCreated(QSharedPointer<SignalEvent const>)),
SLOT(addEventItem(QSharedPointer<SignalEvent const>)));
model->connect (event_manager.data(), SIGNAL(eventRemoved(EventID)),
SLOT(removeEventItem(EventID)));
model->connect (event_manager.data(), SIGNAL(eventChanged(EventID)),
SLOT(updateEvent(EventID)));
}
storeAndInitTabContext (tab_context, tab_index);
return tab_index;
}
} // namespace SigViewer_
|
4wheels/SigViewer-old
|
src/gui_impl/main_window_model_impl.cpp
|
C++
|
gpl-2.0
| 10,445
|
#! /usr/bin/perl -w
# file: increment.pl
use strict;
my $i = 10;
my $j = ++$i;
print "\$i = $i, \$j = $j\n";
$i = 10;
$j = $i++;
print "\$i = $i, \$j = $j\n";
|
vishwanathsingh/workspace
|
example/perlexamples/increment.pl
|
Perl
|
gpl-2.0
| 164
|
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, WordPress Language, and ABSPATH. You can find more information
* by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'Wordpress');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'Andydata123');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
|
Andy447/wordpress
|
wp-config.php
|
PHP
|
gpl-2.0
| 2,726
|
#
# Makefile for the linux kernel.
#
# Common support
obj-y := irq.o id.o io.o sram-fn.o memory.o prcm.o clock.o mux.o devices.o serial.o
obj-$(CONFIG_OMAP_MPU_TIMER) += timer-gp.o
# Power Management
obj-$(CONFIG_PM) += pm.o sleep.o
# Specific board support
obj-$(CONFIG_MACH_OMAP_GENERIC) += board-generic.o
obj-$(CONFIG_MACH_OMAP_H4) += board-h4.o
obj-$(CONFIG_MACH_ITOMAP2420) += board-itomap2420.o
obj-$(CONFIG_MACH_ITOMAP2430) += board-itomap2430.o
|
gerboland/linux-2.6.15-neuros-eabi
|
arch/arm/mach-omap2/Makefile
|
Makefile
|
gpl-2.0
| 464
|
<?php
namespace Drupal\ui_patterns\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\ui_patterns\UiPatternsManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class PatternLibraryController.
*
* @package Drupal\ui_patterns\Controller
*/
class PatternLibraryController extends ControllerBase {
/**
* Patterns manager service.
*
* @var \Drupal\ui_patterns\UiPatternsManager
*/
protected $patternsManager;
/**
* {@inheritdoc}
*/
public function __construct(UiPatternsManager $ui_patterns_manager) {
$this->patternsManager = $ui_patterns_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('plugin.manager.ui_patterns'));
}
/**
* Title callback.
*
* @return string
* Pattern label.
*/
public function title($name) {
$definition = $this->patternsManager->getDefinition($name);
return $definition['label'];
}
/**
* Render pattern library page.
*
* @return array
* Return render array.
*/
public function single($name) {
$definition = $this->patternsManager->getDefinition($name);
$definition['rendered']['#type'] = 'pattern_preview';
$definition['rendered']['#id'] = $name;
$definition['meta']['#theme'] = 'patterns_meta_information';
$definition['meta']['#pattern'] = $definition;
return [
'#theme' => 'patterns_single_page',
'#pattern' => $definition,
];
}
/**
* Render pattern library page.
*
* @return array
* Patterns overview page render array.
*/
public function overview() {
$definitions = $this->patternsManager->getDefinitions();
foreach ($definitions as $name => $definition) {
$definitions[$name]['rendered']['#type'] = 'pattern_preview';
$definitions[$name]['rendered']['#id'] = $name;
$definitions[$name]['meta']['#theme'] = 'patterns_meta_information';
$definitions[$name]['meta']['#pattern'] = $definition;
}
return [
'#theme' => 'patterns_overview_page',
'#patterns' => $definitions,
];
}
}
|
darrylri/vintagebmw
|
docroot/modules/contrib/ui_patterns/src/Controller/PatternLibraryController.php
|
PHP
|
gpl-2.0
| 2,161
|
#!/bin/bash
# @author Amos Kong <akong@redhat.com>
# @copyright: 2012 Red Hat, Inc.
#
# This script is prepared for RHEL/Fedora system, it's just an
# example, users can reference it to custom their own script.
if [[ $# != 2 ]];then
echo "usage: $0 <guest/host> <rebooted/none>"
exit
fi
guest=$1
reboot=$2
########################
echo "Setup env for performance testing, reboot isn't needed"
####
echo "Run test on a private LAN, as there are multpile nics, so set arp_filter to 1"
sysctl net.ipv4.conf.default.arp_filter=1
sysctl net.ipv4.conf.all.arp_filter=1
echo "Disable netfilter on bridges"
sysctl net.bridge.bridge-nf-call-ip6tables=0
sysctl net.bridge.bridge-nf-call-iptables=0
sysctl net.bridge.bridge-nf-call-arptables=0
echo "Set bridge forward delay to 0"
sysctl brctl setfd switch 0
####
echo "Stop the running serivices"
if [[ $guest = "host" ]];then
echo "Run tunning profile on host"
# RHEL6, requst 'tuned' package
tuned-adm profile enterprise-storage
# RHEL5
service tuned start
fi
service auditd stop
service avahi-daemon stop
service anacron stop
service qpidd stop
service smartd stop
service crond stop
service haldaemon stop
service opensmd stop
service openibd stop
service yum-updatesd stop
service collectd stop
service bluetooth stop
service cups stop
service cpuspeed stop
service hidd stop
service isdn stop
service kudzu stop
service lvm2-monitor stop
service mcstrans stop
service mdmonitor stop
service messagebus stop
service restorecond stop
service rhnsd stop
service rpcgssd stop
service setroubleshoot stop
service smartd stop
########################
if [[ $reboot = "rebooted" ]];then
echo "OS already rebooted"
echo "Environment setup finished"
exit
fi
########################
echo "Setup env for performance testing, reboot is needed"
####
echo "Setup runlevel to 3"
if [[ $guest = "guest" ]];then
echo sed -ie "s/id:.*:initdefault:/id:3:initdefault:/g" /etc/inittab
fi
####
echo "Off services when host starts up"
chkconfig auditd off
chkconfig autofs off
chkconfig avahi-daemon off
chkconfig crond off
chkconfig cups off
chkconfig ip6tables off
chkconfig sendmail off
chkconfig smartd off
chkconfig xfs off
chkconfig acpid off
chkconfig atd off
chkconfig haldaemon off
chkconfig mdmonitor off
chkconfig netfs off
chkconfig rhnsd off
chkconfig rpcgssd off
chkconfig rpcidmapd off
chkconfig abrtd off
chkconfig kdump off
chkconfig koan off
chkconfig libvirt-guests off
chkconfig ntpdate off
chkconfig portreserve off
chkconfig postfix off
chkconfig rhsmcertd off
chkconfig tuned off
########################
echo "Environment setup finished"
echo "OS should reboot"
|
nacc/autotest
|
client/virt/scripts/rh_perf_envsetup.sh
|
Shell
|
gpl-2.0
| 2,689
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Sat Aug 06 17:04:47 EDT 2005 -->
<TITLE>
Xalan-Java 2.7.0: Package org.apache.xpath.domapi
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../org/apache/xpath/domapi/package-summary.html" TARGET="classFrame">org.apache.xpath.domapi</A></FONT>
<TABLE BORDER="0" WIDTH="100%">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="XPathEvaluatorImpl.html" TARGET="classFrame">XPathEvaluatorImpl</A></FONT></TD>
</TR>
</TABLE>
<TABLE BORDER="0" WIDTH="100%">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Exceptions</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="XPathStylesheetDOM3Exception.html" TARGET="classFrame">XPathStylesheetDOM3Exception</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
MrStaticVoid/iriverter
|
lib/xalan-j_2_7_0/docs/apidocs/org/apache/xpath/domapi/package-frame.html
|
HTML
|
gpl-2.0
| 1,031
|
<?php
/*
* @version $Id: document_item.class.php 23445 2015-04-10 12:18:49Z yllen $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI 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.
GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Document_Item Class
*
* Relation between Documents and Items
**/
class Document_Item extends CommonDBRelation{
// From CommonDBRelation
static public $itemtype_1 = 'Document';
static public $items_id_1 = 'documents_id';
static public $take_entity_1 = true ;
static public $itemtype_2 = 'itemtype';
static public $items_id_2 = 'items_id';
static public $take_entity_2 = false ;
/**
* @since version 0.84
**/
function getForbiddenStandardMassiveAction() {
$forbidden = parent::getForbiddenStandardMassiveAction();
$forbidden[] = 'update';
return $forbidden;
}
function prepareInputForAdd($input) {
if ((empty($input['items_id']) || ($input['items_id'] == 0))
&& ($input['itemtype'] != 'Entity')) {
return false;
}
// Do not insert circular link for document
if (($input['itemtype'] == 'Document')
&& ($input['items_id'] == $input['documents_id'])) {
return false;
}
// Avoid duplicate entry
$restrict = "`documents_id` = '".$input['documents_id']."'
AND `itemtype` = '".$input['itemtype']."'
AND `items_id` = '".$input['items_id']."'";
if (countElementsInTable($this->getTable(),$restrict) > 0) {
return false;
}
return parent::prepareInputForAdd($input);
}
function post_addItem() {
if ($this->fields['itemtype'] == 'Ticket') {
$ticket = new Ticket();
$input = array('id' => $this->fields['items_id'],
'date_mod' => $_SESSION["glpi_currenttime"],
'_donotadddocs' => true);
if (!isset($this->input['_do_notif']) || $this->input['_do_notif']) {
$input['_forcenotif'] = true;
}
if (isset($this->input['_disablenotif']) && $this->input['_disablenotif']) {
$input['_disablenotif'] = true;
}
$ticket->update($input);
}
parent::post_addItem();
}
/**
* @since version 0.83
*
* @see CommonDBTM::post_purgeItem()
**/
function post_purgeItem() {
if ($this->fields['itemtype'] == 'Ticket') {
$ticket = new Ticket();
$input = array('id' => $this->fields['items_id'],
'date_mod' => $_SESSION["glpi_currenttime"],
'_donotadddocs' => true);
if (!isset($this->input['_do_notif']) || $this->input['_do_notif']) {
$input['_forcenotif'] = true;
}
//Clean ticket description if an image is in it
$doc = new Document();
$doc->getFromDB($this->fields['documents_id']);
if (!empty($doc->fields['tag'])) {
$ticket->getFromDB($this->fields['items_id']);
$input['content'] = $ticket->cleanTagOrImage($ticket->fields['content'],
array($doc->fields['tag']));
}
$ticket->update($input);
}
parent::post_purgeItem();
}
/**
* @param $item CommonDBTM object
**/
static function countForItem(CommonDBTM $item) {
$restrict = "`glpi_documents_items`.`items_id` = '".$item->getField('id')."'
AND `glpi_documents_items`.`itemtype` = '".$item->getType()."'";
if (Session::getLoginUserID()) {
$restrict .= getEntitiesRestrictRequest(" AND ", "glpi_documents_items", '', '', true);
} else {
// Anonymous access from FAQ
$restrict .= " AND `glpi_documents_items`.`entities_id` = '0' ";
}
$nb = countElementsInTable(array('glpi_documents_items'), $restrict);
// Document case : search in both
if ($item->getType() == 'Document') {
$restrict = "`glpi_documents_items`.`documents_id` = '".$item->getField('id')."'
AND `glpi_documents_items`.`itemtype` = '".$item->getType()."'";
if (Session::getLoginUserID()) {
$restrict .= getEntitiesRestrictRequest(" AND ", "glpi_documents_items", '', '', true);
} else {
// Anonymous access from FAQ
$restrict .= " AND `glpi_documents_items`.`entities_id` = '0' ";
}
$nb += countElementsInTable(array('glpi_documents_items'), $restrict);
}
return $nb ;
}
/**
* @param $item Document object
**/
static function countForDocument(Document $item) {
$restrict = "`glpi_documents_items`.`documents_id` = '".$item->getField('id')."'
AND `glpi_documents_items`.`itemtype` != '".$item->getType()."'";
return countElementsInTable(array('glpi_documents_items'), $restrict);
}
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
switch ($item->getType()) {
case 'Document' :
$ong = array();
if ($_SESSION['glpishow_count_on_tabs']) {
$ong[1] = self::createTabEntry(_n('Associated item', 'Associated items',
self::countForDocument($item)));
}
$ong[1] = _n('Associated item', 'Associated items', Session::getPluralNumber());
if ($_SESSION['glpishow_count_on_tabs']) {
$ong[2] = self::createTabEntry(Document::getTypeName(Session::getPluralNumber()),
self::countForItem($item));
}
$ong[2] = Document::getTypeName(Session::getPluralNumber());
return $ong;
default :
// Can exist for template
if (Document::canView()
|| ($item->getType() == 'Ticket')
|| ($item->getType() == 'Reminder')
|| ($item->getType() == 'KnowbaseItem')) {
if ($_SESSION['glpishow_count_on_tabs']) {
return self::createTabEntry(Document::getTypeName(Session::getPluralNumber()),
self::countForItem($item));
}
return Document::getTypeName(Session::getPluralNumber());
}
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
switch ($item->getType()) {
case 'Document' :
switch ($tabnum) {
case 1 :
self::showForDocument($item);
break;
case 2 :
self::showForItem($item, $withtemplate);
break;
}
return true;
default :
self::showForitem($item, $withtemplate);
}
}
/**
* Duplicate documents from an item template to its clone
*
* @since version 0.84
*
* @param $itemtype itemtype of the item
* @param $oldid ID of the item to clone
* @param $newid ID of the item cloned
* @param $newitemtype itemtype of the new item (= $itemtype if empty) (default '')
**/
static function cloneItem($itemtype, $oldid, $newid, $newitemtype='') {
global $DB;
if (empty($newitemtype)) {
$newitemtype = $itemtype;
}
$query = "SELECT `documents_id`
FROM `glpi_documents_items`
WHERE `items_id` = '$oldid'
AND `itemtype` = '$itemtype';";
foreach ($DB->request($query) as $data) {
$docitem = new self();
$docitem->add(array('documents_id' => $data["documents_id"],
'itemtype' => $newitemtype,
'items_id' => $newid));
}
}
/**
* Show items links to a document
*
* @since version 0.84
*
* @param $doc Document object
*
* @return nothing (HTML display)
**/
static function showForDocument(Document $doc) {
global $DB, $CFG_GLPI;
$instID = $doc->fields['id'];
if (!$doc->can($instID, READ)) {
return false;
}
$canedit = $doc->can($instID, UPDATE);
// for a document,
// don't show here others documents associated to this one,
// it's done for both directions in self::showAssociated
$query = "SELECT DISTINCT `itemtype`
FROM `glpi_documents_items`
WHERE `glpi_documents_items`.`documents_id` = '$instID'
AND `glpi_documents_items`.`itemtype` != 'Document'
ORDER BY `itemtype`";
$result = $DB->query($query);
$number = $DB->numrows($result);
$rand = mt_rand();
if ($canedit) {
echo "<div class='firstbloc'>";
echo "<form name='documentitem_form$rand' id='documentitem_form$rand' method='post'
action='".Toolbox::getItemTypeFormURL(__CLASS__)."'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_2'><th colspan='2'>".__('Add an item')."</th></tr>";
echo "<tr class='tab_bg_1'><td class='right'>";
Dropdown::showSelectItemFromItemtypes(array('itemtypes'
=> Document::getItemtypesThatCanHave(),
'entity_restrict'
=> ($doc->fields['is_recursive']
?getSonsOf('glpi_entities',
$doc->fields['entities_id'])
:$doc->fields['entities_id']),
'checkright'
=> true));
echo "</td><td class='center'>";
echo "<input type='submit' name='add' value=\""._sx('button', 'Add')."\" class='submit'>";
echo "<input type='hidden' name='documents_id' value='$instID'>";
echo "</td></tr>";
echo "</table>";
Html::closeForm();
echo "</div>";
}
echo "<div class='spaced'>";
if ($canedit && $number) {
Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
$massiveactionparams = array('container' => 'mass'.__CLASS__.$rand);
Html::showMassiveActions($massiveactionparams);
}
echo "<table class='tab_cadre_fixehov'>";
$header_begin = "<tr>";
$header_top = '';
$header_bottom = '';
$header_end = '';
if ($canedit && $number) {
$header_top .= "<th width='10'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
$header_top .= "</th>";
$header_bottom .= "<th width='10'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
$header_bottom .= "</th>";
}
$header_end .= "<th>".__('Type')."</th>";
$header_end .= "<th>".__('Name')."</th>";
$header_end .= "<th>".__('Entity')."</th>";
$header_end .= "<th>".__('Serial number')."</th>";
$header_end .= "<th>".__('Inventory number')."</th>";
$header_end .= "</tr>";
echo $header_begin.$header_top.$header_end;
for ($i=0 ; $i < $number ; $i++) {
$itemtype=$DB->result($result, $i, "itemtype");
if (!($item = getItemForItemtype($itemtype))) {
continue;
}
if ($item->canView()) {
if ($item instanceof CommonDevice) {
$column = "designation";
} else if ($item instanceof Item_Devices) {
$column = "itemtype";
} else {
$column = "name";
}
if ($itemtype == 'Ticket') {
$column = "id";
}
$itemtable = getTableForItemType($itemtype);
$query = "SELECT `$itemtable`.*,
`glpi_documents_items`.`id` AS IDD, ";
if ($itemtype == 'KnowbaseItem') {
$query .= "-1 AS entity
FROM `glpi_documents_items`, `$itemtable`
".KnowbaseItem::addVisibilityJoins()."
WHERE `$itemtable`.`id` = `glpi_documents_items`.`items_id`
AND ";
} else {
$query .= "`glpi_entities`.`id` AS entity
FROM `glpi_documents_items`, `$itemtable`";
if ($itemtype != 'Entity') {
$query .= " LEFT JOIN `glpi_entities`
ON (`glpi_entities`.`id` = `$itemtable`.`entities_id`)";
}
$query .= " WHERE `$itemtable`.`id` = `glpi_documents_items`.`items_id`
AND ";
}
$query .= "`glpi_documents_items`.`itemtype` = '$itemtype'
AND `glpi_documents_items`.`documents_id` = '$instID' ";
if ($itemtype =='KnowbaseItem') {
if (Session::getLoginUserID()) {
$where = "AND ".KnowbaseItem::addVisibilityRestrict();
} else {
// Anonymous access
if (Session::isMultiEntitiesMode()) {
$where = " AND (`glpi_entities_knowbaseitems`.`entities_id` = '0'
AND `glpi_entities_knowbaseitems`.`is_recursive` = '1')";
}
}
} else {
$query .= getEntitiesRestrictRequest(" AND ", $itemtable, '', '',
$item->maybeRecursive());
}
if ($item->maybeTemplate()) {
$query .= " AND `$itemtable`.`is_template` = '0'";
}
if ($itemtype == 'KnowbaseItem') {
$query .= " ORDER BY `$itemtable`.`$column`";
} else {
$query .= " ORDER BY `glpi_entities`.`completename`, `$itemtable`.`$column`";
}
if ($itemtype == 'SoftwareLicense') {
$soft = new Software();
}
if ($result_linked = $DB->query($query)) {
if ($DB->numrows($result_linked)) {
while ($data = $DB->fetch_assoc($result_linked)) {
if ($itemtype == 'Ticket') {
$data["name"] = sprintf(__('%1$s: %2$s'), __('Ticket'), $data["id"]);
}
if ($itemtype == 'SoftwareLicense') {
$soft->getFromDB($data['softwares_id']);
$data["name"] = sprintf(__('%1$s - %2$s'), $data["name"],
$soft->fields['name']);
}
if ($item instanceof CommonDevice) {
$linkname = $data["designation"];
} else if ($item instanceof Item_Devices) {
$linkname = $data["itemtype"];
} else {
$linkname = $data["name"];
}
if ($_SESSION["glpiis_ids_visible"]
|| empty($data["name"])) {
$linkname = sprintf(__('%1$s (%2$s)'), $linkname, $data["id"]);
}
if ($item instanceof Item_Devices) {
$tmpitem = new $item::$itemtype_2();
if ($tmpitem->getFromDB($data[$item::$items_id_2])) {
$linkname = $tmpitem->getLink();
}
}
$link = Toolbox::getItemTypeFormURL($itemtype);
$name = "<a href=\"".$link."?id=".$data["id"]."\">".$linkname."</a>";
echo "<tr class='tab_bg_1'>";
if ($canedit) {
echo "<td width='10'>";
Html::showMassiveActionCheckBox(__CLASS__, $data["IDD"]);
echo "</td>";
}
echo "<td class='center'>".$item->getTypeName(1)."</td>";
echo "<td ".
(isset($data['is_deleted']) && $data['is_deleted']?"class='tab_bg_2_2'":"").
">".$name."</td>";
echo "<td class='center'>".Dropdown::getDropdownName("glpi_entities",
$data['entity']);
echo "</td>";
echo "<td class='center'>".
(isset($data["serial"])? "".$data["serial"]."" :"-")."</td>";
echo "<td class='center'>".
(isset($data["otherserial"])? "".$data["otherserial"]."" :"-")."</td>";
echo "</tr>";
}
}
}
}
}
if ($number) {
echo $header_begin.$header_bottom.$header_end;
}
echo "</table>";
if ($canedit && $number) {
$massiveactionparams['ontop'] =false;
Html::showMassiveActions($massiveactionparams);
Html::closeForm();
}
echo "</div>";
}
/**
* Show documents associated to an item
*
* @since version 0.84
*
* @param $item CommonDBTM object for which associated documents must be displayed
* @param $withtemplate (default '')
**/
static function showForItem(CommonDBTM $item, $withtemplate='') {
global $DB, $CFG_GLPI;
$ID = $item->getField('id');
if ($item->isNewID($ID)) {
return false;
}
if (($item->getType() != 'Ticket')
&& ($item->getType() != 'KnowbaseItem')
&& ($item->getType() != 'Reminder')
&& !Document::canView()) {
return false;
}
if (!$item->can($item->fields['id'], READ)) {
return false;
}
$columns = array('name' => __('Name'),
'entity' => __('Entity'),
'filename' => __('File'),
'link' => __('Web link'),
'headings' => __('Heading'),
'mime' => __('MIME type'));
if ($CFG_GLPI['use_rich_text']) {
$columns['tag'] = __('Tag');
}
$columns['assocdate'] = __('Date');
if (empty($withtemplate)) {
$withtemplate = 0;
}
$linkparam = '';
if (get_class($item) == 'Ticket') {
$linkparam = "&tickets_id=".$item->fields['id'];
}
if (isset($_GET["order"]) && ($_GET["order"] == "ASC")) {
$order = "ASC";
} else {
$order = "DESC";
}
if ((isset($_GET["sort"]) && !empty($_GET["sort"]))
&& isset($columns[$_GET["sort"]])) {
$sort = "`".$_GET["sort"]."`";
} else {
$sort = "`assocdate`";
}
$canedit = $item->canAddItem('Document') && Document::canView();
$rand = mt_rand();
$is_recursive = $item->isRecursive();
$query = "SELECT `glpi_documents_items`.`id` AS assocID,
`glpi_documents_items`.`date_mod` AS assocdate,
`glpi_entities`.`id` AS entityID,
`glpi_entities`.`completename` AS entity,
`glpi_documentcategories`.`completename` AS headings,
`glpi_documents`.*
FROM `glpi_documents_items`
LEFT JOIN `glpi_documents`
ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)
LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)
LEFT JOIN `glpi_documentcategories`
ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)
WHERE `glpi_documents_items`.`items_id` = '$ID'
AND `glpi_documents_items`.`itemtype` = '".$item->getType()."' ";
if (Session::getLoginUserID()) {
$query .= getEntitiesRestrictRequest(" AND","glpi_documents",'','',true);
} else {
// Anonymous access from FAQ
$query .= " AND `glpi_documents`.`entities_id`= '0' ";
}
// Document : search links in both order using union
if ($item->getType() == 'Document') {
$query .= "UNION
SELECT `glpi_documents_items`.`id` AS assocID,
`glpi_documents_items`.`date_mod` AS assocdate,
`glpi_entities`.`id` AS entityID,
`glpi_entities`.`completename` AS entity,
`glpi_documentcategories`.`completename` AS headings,
`glpi_documents`.*
FROM `glpi_documents_items`
LEFT JOIN `glpi_documents`
ON (`glpi_documents_items`.`items_id`=`glpi_documents`.`id`)
LEFT JOIN `glpi_entities`
ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)
LEFT JOIN `glpi_documentcategories`
ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)
WHERE `glpi_documents_items`.`documents_id` = '$ID'
AND `glpi_documents_items`.`itemtype` = '".$item->getType()."' ";
if (Session::getLoginUserID()) {
$query .= getEntitiesRestrictRequest(" AND","glpi_documents",'','',true);
} else {
// Anonymous access from FAQ
$query .= " AND `glpi_documents`.`entities_id`='0' ";
}
}
$query .= " ORDER BY $sort $order";
$result = $DB->query($query);
$number = $DB->numrows($result);
$i = 0;
$documents = array();
$used = array();
if ($numrows = $DB->numrows($result)) {
while ($data = $DB->fetch_assoc($result)) {
$documents[$data['assocID']] = $data;
$used[$data['id']] = $data['id'];
}
}
if ($item->canAddItem('Document')
&& ($withtemplate < 2)) {
// Restrict entity for knowbase
$entities = "";
$entity = $_SESSION["glpiactive_entity"];
if ($item->isEntityAssign()) {
/// Case of personal items : entity = -1 : create on active entity (Reminder case))
if ($item->getEntityID() >=0 ) {
$entity = $item->getEntityID();
}
if ($item->isRecursive()) {
$entities = getSonsOf('glpi_entities',$entity);
} else {
$entities = $entity;
}
}
$limit = getEntitiesRestrictRequest(" AND ","glpi_documents",'',$entities,true);
$q = "SELECT COUNT(*)
FROM `glpi_documents`
WHERE `is_deleted` = '0'
$limit";
$result = $DB->query($q);
$nb = $DB->result($result,0,0);
if ($item->getType() == 'Document') {
$used[$ID] = $ID;
}
echo "<div class='firstbloc'>";
echo "<form name='documentitem_form$rand' id='documentitem_form$rand' method='post'
action='".Toolbox::getItemTypeFormURL('Document')."' enctype=\"multipart/form-data\">";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_2'><th colspan='5'>".__('Add a document')."</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td class='center'>";
_e('Heading');
echo "</td><td width='20%'>";
DocumentCategory::dropdown(array('entity' => $entities));
echo "</td>";
echo "<td class='right'>";
echo "<input type='hidden' name='entities_id' value='$entity'>";
echo "<input type='hidden' name='is_recursive' value='$is_recursive'>";
echo "<input type='hidden' name='itemtype' value='".$item->getType()."'>";
echo "<input type='hidden' name='items_id' value='$ID'>";
if ($item->getType() == 'Ticket') {
echo "<input type='hidden' name='tickets_id' value='$ID'>";
}
echo Html::file();
echo "</td><td class='left'>";
echo "(".Document::getMaxUploadSize().") ";
echo "</td>";
echo "<td class='center' width='20%'>";
echo "<input type='submit' name='add' value=\""._sx('button', 'Add a new file')."\"
class='submit'>";
echo "</td></tr>";
echo "</table>";
Html::closeForm();
if (Document::canView()
&& ($nb > count($used))) {
echo "<form name='document_form$rand' id='document_form$rand' method='post'
action='".Toolbox::getItemTypeFormURL(__CLASS__)."'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='4' class='center'>";
echo "<input type='hidden' name='itemtype' value='".$item->getType()."'>";
echo "<input type='hidden' name='items_id' value='$ID'>";
if ($item->getType() == 'Ticket') {
echo "<input type='hidden' name='tickets_id' value='$ID'>";
echo "<input type='hidden' name='documentcategories_id' value='".
$CFG_GLPI["documentcategories_id_forticket"]."'>";
}
Document::dropdown(array('entity' => $entities ,
'used' => $used));
echo "</td><td class='center' width='20%'>";
echo "<input type='submit' name='add' value=\"".
_sx('button', 'Associate an existing document')."\" class='submit'>";
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
}
echo "</div>";
}
echo "<div class='spaced'>";
if ($canedit
&& $number
&& ($withtemplate < 2)) {
Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
$massiveactionparams = array('num_displayed' => $number,
'container' => 'mass'.__CLASS__.$rand);
Html::showMassiveActions($massiveactionparams);
}
$sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" .
(($order == "DESC") ? "puce-down.png" : "puce-up.png") ."\" alt='' title=''>";
echo "<table class='tab_cadre_fixehov'>";
$header_begin = "<tr>";
$header_top = '';
$header_bottom = '';
$header_end = '';
if ($canedit
&& $number
&& ($withtemplate < 2)) {
$header_top .= "<th width='11'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
$header_top .= "</th>";
$header_bottom .= "<th width='11'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
$header_bottom .= "</th>";
}
foreach ($columns as $key => $val) {
$header_end .= "<th>".(($sort == "`$key`") ?$sort_img:"").
"<a href='javascript:reloadTab(\"sort=$key&order=".
(($order == "ASC") ?"DESC":"ASC")."&start=0\");'>$val</a></th>";
}
$header_end .= "</tr>";
echo $header_begin.$header_top.$header_end;
$used = array();
if ($number) {
// Don't use this for document associated to document
// To not loose navigation list for current document
if ($item->getType() != 'Document') {
Session::initNavigateListItems('Document',
//TRANS : %1$s is the itemtype name,
// %2$s is the name of the item (used for headings of a list)
sprintf(__('%1$s = %2$s'),
$item->getTypeName(1), $item->getName()));
}
$document = new Document();
foreach ($documents as $data) {
$docID = $data["id"];
$link = NOT_AVAILABLE;
$downloadlink = NOT_AVAILABLE;
if ($document->getFromDB($docID)) {
$link = $document->getLink();
$downloadlink = $document->getDownloadLink($linkparam);
}
if ($item->getType() != 'Document') {
Session::addToNavigateListItems('Document', $docID);
}
$used[$docID] = $docID;
$assocID = $data["assocID"];
echo "<tr class='tab_bg_1".($data["is_deleted"]?"_2":"")."'>";
if ($canedit
&& ($withtemplate < 2)) {
echo "<td width='10'>";
Html::showMassiveActionCheckBox(__CLASS__, $data["assocID"]);
echo "</td>";
}
echo "<td class='center'>$link</td>";
echo "<td class='center'>".$data['entity']."</td>";
echo "<td class='center'>$downloadlink</td>";
echo "<td class='center'>";
if (!empty($data["link"])) {
echo "<a target=_blank href='".formatOutputWebLink($data["link"])."'>".$data["link"];
echo "</a>";
} else {;
echo " ";
}
echo "</td>";
echo "<td class='center'>".Dropdown::getDropdownName("glpi_documentcategories",
$data["documentcategories_id"]);
echo "</td>";
echo "<td class='center'>".$data["mime"]."</td>";
if ($CFG_GLPI['use_rich_text']) {
echo "<td class='center'>";
echo !empty($data["tag"]) ? Document::getImageTag($data["tag"]) : '';
echo "</td>";
}
echo "<td class='center'>".Html::convDateTime($data["assocdate"])."</td>";
echo "</tr>";
$i++;
}
echo $header_begin.$header_bottom.$header_end;
}
echo "</table>";
if ($canedit && $number && ($withtemplate < 2)) {
$massiveactionparams['ontop'] = false;
Html::showMassiveActions($massiveactionparams);
Html::closeForm();
}
echo "</div>";
}
/**
* @since version 0.85
*
* @see CommonDBRelation::getRelationMassiveActionsPeerForSubForm()
**/
static function getRelationMassiveActionsPeerForSubForm(MassiveAction $ma) {
switch ($ma->getAction()) {
case 'add' :
case 'remove' :
return 1;
case 'add_item' :
case 'remove_item' :
return 2;
}
return 0;
}
/**
* @since version 0.85
*
* @see CommonDBRelation::getRelationMassiveActionsSpecificities()
**/
static function getRelationMassiveActionsSpecificities() {
global $CFG_GLPI;
$specificities = parent::getRelationMassiveActionsSpecificities();
$specificities['itemtypes'] = Document::getItemtypesThatCanHave();
// Define normalized action for add_item and remove_item
$specificities['normalized']['add'][] = 'add_item';
$specificities['normalized']['remove'][] = 'remove_item';
// Set the labels for add_item and remove_item
$specificities['button_labels']['add_item'] = $specificities['button_labels']['add'];
$specificities['button_labels']['remove_item'] = $specificities['button_labels']['remove'];
return $specificities;
}
}
?>
|
dtiguarulhos/suporteguarulhos
|
inc/document_item.class.php
|
PHP
|
gpl-2.0
| 32,868
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>fused_function_object</title>
<link rel="stylesheet" href="../../../../../../../doc/html/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.66.1">
<link rel="start" href="../../../index.html" title="Chapter 1. Fusion 2.0">
<link rel="up" href="../adapters.html" title=" Adapters">
<link rel="prev" href="fused_procedure.html" title="fused_procedure">
<link rel="next" href="unfused_generic.html" title="unfused_generic">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="fused_procedure.html"><img src="../../../../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../adapters.html"><img src="../../../../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="unfused_generic.html"><img src="../../../../../../../doc/html/images/next.png" alt="Next"></a>
</div>
<div class="section" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="fusion.functional.adapters.fused_function_object"></a><a href="fused_function_object.html" title="fused_function_object">fused_function_object</a></h4></div></div></div>
<a name="fusion.functional.adapters.fused_function_object.description"></a><h5>
<a name="id664533"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.description">Description</a>
</h5>
<p>
An unary <a href="../concepts/poly.html" title=" Polymorphic Function
Object">Polymorphic Function
Object</a> adapter template for a <a href="../concepts/poly.html" title=" Polymorphic Function
Object">Polymorphic
Function Object</a> target function. It takes a <a href="../../sequence/concepts/forward_sequence.html" title="Forward
Sequence">Forward
Sequence</a> that contains the arguments for the target function.
</p>
<p>
The type of the target function is allowed to be const qualified or a reference.
Const qualification is preserved and propagated appropriately (in other
words, only const versions of <tt class="literal">operator()</tt> can be used
for an target function object that is const or, if the target function
object is held by value, the adapter is const).
</p>
<p>
/functional/adapter/fused_function_object.hpp>
</p>
<a name="fusion.functional.adapters.fused_function_object.synopsis"></a><h5>
<a name="id664615"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.synopsis">Synopsis</a>
</h5>
<pre class="programlisting">
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Function</span><span class="special">></span>
<span class="keyword">class</span> <span class="identifier">fused_function_object</span><span class="special">;</span>
</pre>
<a name="fusion.functional.adapters.fused_function_object.template_parameters"></a><h5>
<a name="id664700"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.template_parameters">Template
parameters</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Parameter
</p>
</th>
<th>
<p>
Description
</p>
</th>
<th>
<p>
Default
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<tt class="computeroutput"><span class="identifier">Function</span></tt>
</p>
</td>
<td>
<p>
<a href="../concepts/poly.html" title=" Polymorphic Function
Object">Polymorphic Function
Object</a> type
</p>
</td>
<td>
<p>
</p>
</td>
</tr></tbody>
</table></div>
<a name="fusion.functional.adapters.fused_function_object.model_of"></a><h5>
<a name="id664816"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.model_of">Model
of</a>
</h5>
<div class="itemizedlist"><ul type="disc">
<li><a href="../concepts/poly.html" title=" Polymorphic Function
Object">Polymorphic Function
Object</a></li>
<li><a href="../concepts/def_callable.html" title=" Deferred
Callable Object">Deferred Callable
Object</a></li>
</ul></div>
<div class="variablelist">
<p class="title"><b>Notation</b></p>
<dl>
<dt><span class="term"><tt class="computeroutput"><span class="identifier">R</span></tt></span></dt>
<dd><p>
A possibly const qualified <a href="../concepts/poly.html" title=" Polymorphic Function
Object">Polymorphic
Function Object</a> type or reference type thereof
</p></dd>
<dt><span class="term"><tt class="computeroutput"><span class="identifier">r</span></tt></span></dt>
<dd><p>
An object convertible to <tt class="computeroutput"><span class="identifier">R</span></tt>
</p></dd>
<dt><span class="term"><tt class="computeroutput"><span class="identifier">s</span></tt></span></dt>
<dd><p>
A <a href="../../sequence.html" title="Sequence">Sequence</a> of arguments that
are accepted by <tt class="computeroutput"><span class="identifier">r</span></tt>
</p></dd>
<dt><span class="term"><tt class="computeroutput"><span class="identifier">f</span></tt></span></dt>
<dd><p>
An instance of <tt class="computeroutput"><span class="identifier">fused</span><span class="special"><</span><span class="identifier">R</span><span class="special">></span></tt>
</p></dd>
</dl>
</div>
<a name="fusion.functional.adapters.fused_function_object.expression_semantics"></a><h5>
<a name="id665037"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.expression_semantics">Expression
Semantics</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Expression
</p>
</th>
<th>
<p>
Semantics
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<tt class="computeroutput"><span class="identifier">fused_function_object</span><span class="special"><</span><span class="identifier">R</span><span class="special">>(</span><span class="identifier">r</span><span class="special">)</span></tt>
</p>
</td>
<td>
<p>
Creates a fused function as described above, initializes the target
function with <tt class="computeroutput"><span class="identifier">r</span></tt>.
</p>
</td>
</tr>
<tr>
<td>
<p>
<tt class="computeroutput"><span class="identifier">fused_function_object</span><span class="special"><</span><span class="identifier">R</span><span class="special">>()</span></tt>
</p>
</td>
<td>
<p>
Creates a fused function as described above, attempts to use <tt class="computeroutput"><span class="identifier">R</span></tt>'s default constructor.
</p>
</td>
</tr>
<tr>
<td>
<p>
<tt class="computeroutput"><span class="identifier">f</span><span class="special">(</span><span class="identifier">s</span><span class="special">)</span></tt>
</p>
</td>
<td>
<p>
Calls <tt class="computeroutput"><span class="identifier">r</span></tt> with the
elements in <tt class="computeroutput"><span class="identifier">s</span></tt> as
its arguments.
</p>
</td>
</tr>
</tbody>
</table></div>
<a name="fusion.functional.adapters.fused_function_object.example"></a><h5>
<a name="id665293"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.example">Example</a>
</h5>
<pre class="programlisting">
<span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span> <span class="identifier">SeqOfSeqs</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">Func</span><span class="special">></span>
<span class="keyword">typename</span> <a href="../../algorithm/transformation/metafunctions/transform.html" title="transform"><tt class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">transform</span></tt></a><span class="special"><</span> <span class="identifier">zip_view</span><span class="special"><</span><span class="identifier">SeqOfSeqs</span><span class="special">></span> <span class="keyword">const</span><span class="special">,</span>
<span class="identifier">fused_function_object</span><span class="special"><</span><span class="identifier">Func</span> <span class="keyword">const</span> <span class="special">&></span> <span class="special">>::</span><span class="identifier">type</span>
<span class="identifier">n_ary_transform</span><span class="special">(</span><span class="identifier">SeqOfSeqs</span> <span class="keyword">const</span> <span class="special">&</span> <span class="identifier">s</span><span class="special">,</span> <span class="identifier">Func</span> <span class="keyword">const</span> <span class="special">&</span> <span class="identifier">f</span><span class="special">)</span>
<span class="special">{</span>
<span class="keyword">return</span> <a href="../../algorithm/transformation/functions/transform.html" title="transform"><tt class="computeroutput"><span class="identifier">transform</span></tt></a><span class="special">(</span><span class="identifier">zip_view</span><span class="special"><</span><span class="identifier">SeqOfSeqs</span><span class="special">>(</span><span class="identifier">s</span><span class="special">),</span>
<span class="identifier">fused_function_object</span><span class="special"><</span><span class="identifier">Func</span> <span class="keyword">const</span> <span class="special">&>(</span><span class="identifier">f</span><span class="special">));</span>
<span class="special">}</span>
<span class="keyword">struct</span> <span class="identifier">sub</span>
<span class="special">{</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Sig</span><span class="special">></span>
<span class="keyword">struct</span> <span class="identifier">result</span><span class="special">;</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Self</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">T</span><span class="special">></span>
<span class="keyword">struct</span> <span class="identifier">result</span><span class="special"><</span> <span class="identifier">Self</span><span class="special">(</span><span class="identifier">T</span><span class="special">,</span><span class="identifier">T</span><span class="special">)</span> <span class="special">></span>
<span class="special">{</span> <span class="keyword">typedef</span> <span class="keyword">typename</span> <span class="identifier">remove_reference</span><span class="special"><</span><span class="identifier">T</span><span class="special">>::</span><span class="identifier">type</span> <span class="identifier">type</span><span class="special">;</span> <span class="special">};</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">T</span><span class="special">></span>
<span class="identifier">T</span> <span class="keyword">operator</span><span class="special">()(</span><span class="identifier">T</span> <span class="identifier">lhs</span><span class="special">,</span> <span class="identifier">T</span> <span class="identifier">rhs</span><span class="special">)</span> <span class="keyword">const</span>
<span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">lhs</span> <span class="special">-</span> <span class="identifier">rhs</span><span class="special">;</span>
<span class="special">}</span>
<span class="special">};</span>
<span class="keyword">void</span> <span class="identifier">try_it</span><span class="special">()</span>
<span class="special">{</span>
<a href="../../container/vector.html" title="vector"><tt class="computeroutput"><span class="identifier">vector</span></tt></a><span class="special"><</span><span class="keyword">int</span><span class="special">,</span><span class="keyword">float</span><span class="special">></span> <span class="identifier">a</span><span class="special">(</span><span class="number">2</span><span class="special">,</span><span class="number">2.0f</span><span class="special">);</span>
<a href="../../container/vector.html" title="vector"><tt class="computeroutput"><span class="identifier">vector</span></tt></a><span class="special"><</span><span class="keyword">int</span><span class="special">,</span><span class="keyword">float</span><span class="special">></span> <span class="identifier">b</span><span class="special">(</span><span class="number">1</span><span class="special">,</span><span class="number">1.5f</span><span class="special">);</span>
<a href="../../container/vector.html" title="vector"><tt class="computeroutput"><span class="identifier">vector</span></tt></a><span class="special"><</span><span class="keyword">int</span><span class="special">,</span><span class="keyword">float</span><span class="special">></span> <span class="identifier">c</span><span class="special">(</span><span class="number">1</span><span class="special">,</span><span class="number">0.5f</span><span class="special">);</span>
<span class="identifier">assert</span><span class="special">(</span><span class="identifier">c</span> <span class="special">==</span> <span class="identifier">n_ary_transform</span><span class="special">(</span><a href="../../container/generation/functions/vector_tie.html" title="vector_tie"><tt class="computeroutput"><span class="identifier">vector_tie</span></tt></a><span class="special">(</span><span class="identifier">a</span><span class="special">,</span><span class="identifier">b</span><span class="special">),</span> <span class="identifier">sub</span><span class="special">()));</span>
<span class="special">}</span>
</pre>
<a name="fusion.functional.adapters.fused_function_object.see_also"></a><h5>
<a name="id666351"></a>
<a href="fused_function_object.html#fusion.functional.adapters.fused_function_object.see_also">See
also</a>
</h5>
<div class="itemizedlist"><ul type="disc">
<li><a href="fused.html" title="fused"><tt class="computeroutput"><span class="identifier">fused</span></tt></a></li>
<li><a href="fused_procedure.html" title="fused_procedure"><tt class="computeroutput"><span class="identifier">fused_procedure</span></tt></a></li>
<li><a href="../invocation/functions/invoke_fobj.html" title="
invoke_function_object"><tt class="computeroutput"><span class="identifier">invoke_function_object</span></tt></a></li>
<li><a href="../../support/deduce.html" title="deduce"><tt class="computeroutput"><span class="identifier">deduce</span></tt></a></li>
</ul></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2007 Joel de Guzman, Dan Marsden, Tobias
Schwinger<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="fused_procedure.html"><img src="../../../../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../adapters.html"><img src="../../../../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="unfused_generic.html"><img src="../../../../../../../doc/html/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
scs/uclinux
|
lib/boost/boost_1_38_0/libs/fusion/doc/html/fusion/functional/adapters/fused_function_object.html
|
HTML
|
gpl-2.0
| 17,966
|
$(function()
{
$(".btn-primary").on('click',function() {
$(this).removeClass("btn-primary").addClass("btn-default");
});
});
|
ellinn7/openprofosmotr
|
web/js/toprint.js
|
JavaScript
|
gpl-2.0
| 146
|
<?php
if(!defined('VALID_CMS_ADMIN')) { die('ACCESS DENIED'); }
/******************************************************************************/
// //
// InstantCMS v1.9 //
// http://www.instantcms.ru/ //
// //
// written by InstantCMS Team, 2007-2011 //
// produced by InstantSoft, (www.instantsoft.ru) //
// //
// LICENSED BY GNU/GPL v2 //
// //
/******************************************************************************/
cpAddPathway('Ïðàéñëèñò', '?view=components&do=config&id='.$_REQUEST['id']);
echo '<h3>Ïðàéñëèñò</h3>';
if (isset($_REQUEST['opt'])) { $opt = $_REQUEST['opt']; } else { $opt = 'config'; }
$toolmenu = array();
$toolmenu[0]['icon'] = 'newfolder.gif';
$toolmenu[0]['title'] = 'Íîâàÿ êàòåãîðèÿ';
$toolmenu[0]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=add_cat';
$toolmenu[2]['icon'] = 'newstuff.gif';
$toolmenu[2]['title'] = 'Íîâûé òîâàð';
$toolmenu[2]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=add_item';
$toolmenu[1]['icon'] = 'folders.gif';
$toolmenu[1]['title'] = 'Êàòåãîðèè ïðàéñà';
$toolmenu[1]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats';
$toolmenu[3]['icon'] = 'liststuff.gif';
$toolmenu[3]['title'] = 'Âñå òîâàðû';
$toolmenu[3]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_items';
if($opt == 'list_items'){
$toolmenu[11]['icon'] = 'edit.gif';
$toolmenu[11]['title'] = 'Ðåäàêòèðîâàòü âûáðàííûå';
$toolmenu[11]['link'] = "javascript:checkSel('?view=components&do=config&id=".$_REQUEST['id']."&opt=edit_item&multiple=1');";
$toolmenu[12]['icon'] = 'show.gif';
$toolmenu[12]['title'] = 'Ïóáëèêîâàòü âûáðàííûå';
$toolmenu[12]['link'] = "javascript:checkSel('?view=components&do=config&id=".$_REQUEST['id']."&opt=show_item&multiple=1');";
$toolmenu[13]['icon'] = 'hide.gif';
$toolmenu[13]['title'] = 'Ñêðûòü âûáðàííûå';
$toolmenu[13]['link'] = "javascript:checkSel('?view=components&do=config&id=".$_REQUEST['id']."&opt=hide_item&multiple=1');";
$toolmenu[14]['icon'] = 'delete.gif';
$toolmenu[14]['title'] = 'Óäàëèòü âûáðàííûå';
$toolmenu[14]['link'] = "javascript:checkSel('?view=components&do=config&id=".$_REQUEST['id']."&opt=delete_item&multiple=1');";
}
cpToolMenu($toolmenu);
//LOAD CURRENT CONFIG
$cfg = $inCore->loadComponentConfig('price');
if($opt=='saveconfig'){
$cfg = array();
$cfg['email'] = $_REQUEST['email'];
$cfg['delivery'] = $_REQUEST['delivery'];
$inCore->saveComponentConfig('price', $cfg);
}
if (@$msg) { echo '<p class="success">'.$msg.'</p>'; }
if ($opt == 'show_item'){
if (!isset($_REQUEST['item'])){
if (isset($_REQUEST['id'])){ dbShow('cms_price_items', $id); }
echo '1'; exit;
} else {
dbShowList('cms_price_items', $_REQUEST['item']);
header('location:'.$_SERVER['HTTP_REFERER']);
}
}
if ($opt == 'hide_item'){
if (!isset($_REQUEST['item'])){
if (isset($_REQUEST['id'])){ dbHide('cms_price_items', $id); }
echo '1'; exit;
} else {
dbHideList('cms_price_items', $_REQUEST['item']);
header('location:'.$_SERVER['HTTP_REFERER']);
}
}
if ($opt == 'submit_item'){
$category_id = $_REQUEST['category_id'];
if (!empty($_REQUEST['title'])) { $title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES, 'cp1251'); } else { error("Óêàæèòå íàçâàíèå êàòåãîðèè!"); }
if (!empty($_REQUEST['price'])) {
$price = $_REQUEST['price'];
}
$published = $_REQUEST['published'];
$canmany = $_REQUEST['canmany'];
$price = str_replace(',', '.', $price);
$sql = "INSERT INTO cms_price_items (category_id, title, price, published, canmany)
VALUES ($category_id, '$title', '$price', $published, $canmany)";
dbQuery($sql) ;
header('location:?view=components&do=config&opt=list_items&id='.$_REQUEST['id']);
}
if ($opt == 'update_item'){
if(isset($_REQUEST['item_id'])) {
$id = $_REQUEST['item_id'];
$category_id = $_REQUEST['category_id'];
$title = $_REQUEST['title'];
$price = $_REQUEST['price'];
$published = $_REQUEST['published'];
$canmany = $_REQUEST['canmany'];
$price = str_replace(',', '.', $price);
$sql = "UPDATE cms_price_items
SET category_id = $category_id,
title='$title',
price='$price',
published=$published,
canmany=$canmany
WHERE id = $id
LIMIT 1";
dbQuery($sql) ;
}
if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist'])==0){
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_items');
} else {
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_item');
}
}
if($opt == 'delete_item'){
if (!isset($_REQUEST['item'])){
if (isset($_REQUEST['item_id'])){ dbDelete('cms_price_items', $_REQUEST['item_id']); }
} else {
dbDeleteList('cms_price_items', $_REQUEST['item']);
}
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_items');
}
if ($opt == 'config') {
?>
<form action="index.php?view=components&do=config&id=<?php echo $_REQUEST['id'];?>" method="post" name="optform" target="_self" id="form1">
<table width="600" border="0" cellpadding="10" cellspacing="0" class="proptable">
<tr>
<td width="218"><b>E-mail ïðîäàâöà : </b></td>
<td width="338"><input name="email" type="text" id="title2" size="30" value="<?php echo @$cfg['email'];?>"/></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="10" cellspacing="0" class="proptable">
<tr>
<td><p><b>Èíôîðìàöèÿ î äîñòàâêå: </b></p>
<?php
$inCore->insertEditor('delivery', $cfg['delivery'], '260', '100%');
?></td>
</tr>
</table>
<p>
<input name="opt" type="hidden" id="do" value="saveconfig" />
<input name="save" type="submit" id="save" value="Ñîõðàíèòü" />
<input name="back" type="button" id="back" value="Îòìåíà" onclick="window.location.href='index.php?view=components&do=config&id=<?php echo $_REQUEST['id']; ?>';"/>
</p>
</form>
<?php
}
if ($opt == 'show_cat'){
if(isset($_REQUEST['item_id'])) {
$id = $_REQUEST['item_id'];
$sql = "UPDATE cms_price_cats SET published = 1 WHERE id = $id";
dbQuery($sql) ;
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
}
}
if ($opt == 'hide_cat'){
if(isset($_REQUEST['item_id'])) {
$id = $_REQUEST['item_id'];
$sql = "UPDATE cms_price_cats SET published = 0 WHERE id = $id";
dbQuery($sql) ;
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
}
}
if ($opt == 'submit_cat'){
if (!empty($_REQUEST['title'])) { $title = $_REQUEST['title']; } else { error("Óêàæèòå íàçâàíèå êàòåãîðèè!"); }
$description = $_REQUEST['description'];
$published = $_REQUEST['published'];
$sql = "INSERT INTO cms_price_cats (title, description, published)
VALUES ('$title', '$description', '$published')";
dbQuery($sql) ;
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
}
if($opt == 'delete_cat'){
if(isset($_REQUEST['item_id'])) {
$id = $_REQUEST['item_id'];
//DELETE ITEMS
$sql = "DELETE FROM cms_price_items WHERE category_id = $id";
dbQuery($sql) ;
//DELETE CATEGORY
$sql = "DELETE FROM cms_price_cats WHERE id = $id LIMIT 1";
dbQuery($sql) ;
}
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
}
if ($opt == 'update_cat'){
if(isset($_REQUEST['item_id'])) {
$id = $_REQUEST['item_id'];
if (!empty($_REQUEST['title'])) { $title = $_REQUEST['title']; } else { error("Óêàæèòå íàçâàíèå êàòåãîðèè!"); }
$description = $_REQUEST['description'];
$published = $_REQUEST['published'];
$sql = "UPDATE cms_price_cats
SET title='$title',
description='$description',
published=$published
WHERE id = $id
LIMIT 1";
dbQuery($sql) ;
header('location:?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
}
}
if ($opt == 'list_cats'){
cpAddPathway('Êàòåãîðèè ïðàéñà', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
echo '<h3>Êàòåãîðèè ïðàéñà</h3>';
//TABLE COLUMNS
$fields = array();
$fields[0]['title'] = 'id'; $fields[0]['field'] = 'id'; $fields[0]['width'] = '30';
$fields[1]['title'] = 'Íàçâàíèå'; $fields[1]['field'] = 'title'; $fields[1]['width'] = '';
$fields[1]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_cat&item_id=%id%';
$fields[2]['title'] = 'Ïîêàç'; $fields[2]['field'] = 'published'; $fields[2]['width'] = '100';
$fields[2]['do'] = 'opt'; $fields[2]['do_suffix'] = '_cat';
//ACTIONS
$actions = array();
$actions[0]['title'] = 'Ðåäàêòèðîâàòü';
$actions[0]['icon'] = 'edit.gif';
$actions[0]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_cat&item_id=%id%';
$actions[1]['title'] = 'Óäàëèòü';
$actions[1]['icon'] = 'delete.gif';
$actions[1]['confirm'] = 'Óäàëèòü êàòåãîðèþ èç ïðàéñëèñòà?';
$actions[1]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=delete_cat&item_id=%id%';
//Print table
cpListTable('cms_price_cats', $fields, $actions);
}
if ($opt == 'list_items'){
cpAddPathway('Òîâàðû', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_items');
echo '<h3>Òîâàðû</h3>';
//TABLE COLUMNS
$fields = array();
$fields[0]['title'] = 'id'; $fields[0]['field'] = 'id'; $fields[0]['width'] = '30';
$fields[1]['title'] = 'Íàçâàíèå'; $fields[1]['field'] = 'title'; $fields[1]['width'] = '';
$fields[1]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_item&item_id=%id%';
$fields[1]['filter'] = 15;
$fields[2]['title'] = 'Ïîêàç'; $fields[2]['field'] = 'published'; $fields[2]['width'] = '100';
$fields[2]['do'] = 'opt'; $fields[2]['do_suffix'] = '_item';
$fields[3]['title'] = 'Öåíà'; $fields[3]['field'] = 'price'; $fields[3]['width'] = '90';
$fields[3]['filter'] = 6;
$fields[4]['title'] = 'Êàòåãîðèÿ'; $fields[4]['field'] = 'category_id';$fields[4]['width'] = '300';
$fields[4]['prc'] = 'cpPriceCatById'; $fields[4]['filter'] = 1; $fields[4]['filterlist'] = cpGetList('cms_price_cats');
//ACTIONS
$actions = array();
$actions[0]['title'] = 'Ðåäàêòèðîâàòü';
$actions[0]['icon'] = 'edit.gif';
$actions[0]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_item&item_id=%id%';
$actions[1]['title'] = 'Óäàëèòü';
$actions[1]['icon'] = 'delete.gif';
$actions[1]['confirm'] = 'Óäàëèòü ïîçèöèþ èç ïðàéñà?';
$actions[1]['link'] = '?view=components&do=config&id='.$_REQUEST['id'].'&opt=delete_item&item_id=%id%';
//Print table
cpListTable('cms_price_items', $fields, $actions);
}
if ($opt == 'add_item' || $opt == 'edit_item'){
if ($opt=='add_item'){
echo '<h3>Äîáàâèòü òîâàð</h3>';
cpAddPathway('Äîáàâèòü òîâàð', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=add_item');
} else {
if(isset($_REQUEST['multiple'])){
if (isset($_REQUEST['item'])){
$_SESSION['editlist'] = $_REQUEST['item'];
} else {
echo '<p class="error">Íåò âûáðàííûõ îáúåêòîâ!</p>';
return;
}
}
$ostatok = '';
if (isset($_SESSION['editlist'])){
$id = array_shift($_SESSION['editlist']);
if (sizeof($_SESSION['editlist'])==0) { unset($_SESSION['editlist']); } else
{ $ostatok = '(Íà î÷åðåäè: '.sizeof($_SESSION['editlist']).')'; }
} else { $id = $_REQUEST['item_id']; }
$sql = "SELECT * FROM cms_price_items WHERE id = $id LIMIT 1";
$result = dbQuery($sql) ;
if (mysql_num_rows($result)){
$mod = mysql_fetch_assoc($result);
}
echo '<h3>'.$mod['title'].' '.$ostatok.'</h3>';
cpAddPathway('Òîâàðû', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_items');
cpAddPathway($mod['title'], '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_item&item_id='.$id);
}
?>
<form action="index.php?view=components&do=config&id=<?php echo $_REQUEST['id'];?>" method="post" enctype="multipart/form-data" name="addform" id="addform">
<table width="650" border="0" cellspacing="5" class="proptable">
<tr>
<td width="177">Íàçâàíèå òîâàðà: </td>
<td width="311"><textarea name="title" id="title" rows="1" style="height:16px;width:320px;"><?php echo @$mod['title'];?></textarea></td>
</tr>
<tr>
<td>Öåíà (<font color="#999999">ðóá.êîï</font>): </td>
<td><input name="price" type="text" size="30" style="height:16px;width:120px;" value="<?php echo @$mod['price'];?>"/></td>
</tr>
<tr>
<td>Êàòåãîðèÿ:</td>
<td>
<select name="category_id" id="category_id">
<?php
if (isset($mod['category_id'])) {
echo $inCore->getListItems('cms_price_cats', $mod['category_id']);
} else {
if (isset($_REQUEST['addto'])){
echo $inCore->getListItems('cms_price_cats', $_REQUEST['addto']);
} else {
echo $inCore->getListItems('cms_price_cats');
}
}
?>
</select>
</td>
</tr>
<tr>
<td>Âûáîð êîëè÷åñòâà: </td>
<td><select name="canmany" id="canmany">
<option value="1" <?php if(@$mod['canmany']) { echo 'selected'; } ?>>Ðàçðåøèòü</option>
<option value="0" <?php if(@!$mod['canmany']) { echo 'selected'; } ?>>Çàïðåòèòü</option>
</select>
</td>
</tr>
<tr>
<td>Ïóáëèêîâàòü òîâàð?</td>
<td><input name="published" type="radio" value="1" checked="checked" <?php if (@$mod['published']) { echo 'checked="checked"'; } ?> />
Äà
<label>
<input name="published" type="radio" value="0" <?php if (@!$mod['published']) { echo 'checked="checked"'; } ?> />
Íåò</label></td>
</tr>
</table>
<p>
<label>
<input name="add_mod" type="submit" id="add_mod" <?php if ($opt=='add_item') { echo 'value="Äîáàâèòü òîâàð"'; } else { echo 'value="Ñîõðàíèòü èçìåíåíèÿ"'; } ?> />
</label>
<label>
<input name="back2" type="button" id="back2" value="Îòìåíà" onclick="window.location.href='index.php?view=components&do=config&id=<?php echo $_REQUEST['id']; ?>';"/>
</label>
<input name="opt" type="hidden" id="do" <?php if ($opt=='add_item') { echo 'value="submit_item"'; } else { echo 'value="update_item"'; } ?> />
<?php
if ($opt=='edit_item'){
echo '<input name="item_id" type="hidden" value="'.$mod['id'].'" />';
}
?>
</p>
</form>
<?php
}
if ($opt == 'add_cat' || $opt == 'edit_cat'){
if ($opt=='add_cat'){
echo '<h3>Äîáàâèòü êàòåãîðèþ</h3>';
cpAddPathway('Äîáàâèòü êàòåãîðèþ', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=add_cat');
} else {
if(isset($_REQUEST['item_id'])){
$id = $_REQUEST['item_id'];
$sql = "SELECT * FROM cms_price_cats WHERE id = $id LIMIT 1";
$result = dbQuery($sql) ;
if (mysql_num_rows($result)){
$mod = mysql_fetch_assoc($result);
}
}
echo '<h3>Êàòåãîðèÿ: '.$mod['title'].'</h3>';
cpAddPathway('Êàòåãîðèè ïðàéñà', '?view=components&do=config&id='.$_REQUEST['id'].'&opt=list_cats');
cpAddPathway($mod['title'], '?view=components&do=config&id='.$_REQUEST['id'].'&opt=edit_cat&item_id='.$_REQUEST['item_id']);
}
?>
<form id="addform" name="addform" method="post" action="index.php?view=components&do=config&id=<?php echo $_REQUEST['id'];?>">
<table width="600" border="0" cellspacing="5" class="proptable">
<tr>
<td width="200">Íàçâàíèå êàòåãîðèè: </td>
<td width="213"><input name="title" type="text" id="title" size="30" value="<?php echo htmlspecialchars($mod['title']);?>"/></td>
<td width="173"> </td>
</tr>
<tr>
<td>Ïóáëèêîâàòü êàòåãîðèþ?</td>
<td><input name="published" type="radio" value="1" <?php if (@$mod['published']) { echo 'checked="checked"'; } ?> />
Äà
<label>
<input name="published" type="radio" value="0" <?php if (@!$mod['published']) { echo 'checked="checked"'; } ?> />
Íåò</label></td>
<td> </td>
</tr>
</table>
<table width="100%" border="0">
<tr>
<?php
if(!isset($mod['user']) || @$mod['user']==1){
echo '<td width="52%" valign="top">';
echo 'Îïèñàíèå êàòåãîðèè:<br/>';
$inCore->insertEditor('description', $mod['description'], '260', '605');
echo '</td>';
}
?>
</tr>
</table>
<p>
<label>
<input name="add_mod" type="submit" id="add_mod" <?php if ($do=='add_cat') { echo 'value="Ñîçäàòü êàòåãîðèþ"'; } else { echo 'value="Ñîõðàíèòü èçìåíåíèÿ"'; } ?> />
</label>
<label>
<input name="back3" type="button" id="back3" value="Îòìåíà" onclick="window.location.href='index.php?view=components&do=config&id=<?php echo $_REQUEST['id']; ?>';"/>
</label>
<input name="opt" type="hidden" id="do" <?php if ($opt=='add_cat') { echo 'value="submit_cat"'; } else { echo 'value="update_cat"'; } ?> />
<?php
if ($opt=='edit_cat'){
echo '<input name="item_id" type="hidden" value="'.$mod['id'].'" />';
}
?>
</p>
</form>
<?php
}
?>
|
pashen/icms
|
admin/components/price/backend.php
|
PHP
|
gpl-2.0
| 18,403
|
class AddPasswordToUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.string :password
end
change_table :admins do |t|
t.string :password
end
end
end
|
ptravers/sportl_rails
|
db/migrate/20150306222526_add_password_to_users.rb
|
Ruby
|
gpl-2.0
| 208
|
<?php
wp_enqueue_script('wpmf-gallery');
$class_default = array();
$class_default[] = "gallery gallery_default";
$class_default[] = "galleryid-{$id}";
$class_default[] = "gallery-columns-{$columns}";
$class_default[] = "gallery-size-{$size_class}";
$class_default[] = "gallery-link-{$link}";
$output = "<div id='$selector' class='" . implode(' ', $class_default) . "'>";
$i = 0;
$pos = 1;
foreach ($attachments as $id => $attachment) {
$link_target = get_post_meta( $attachment->ID, '_gallery_link_target', true );
if ($customlink) {
$image_output = $this->wpmf_gallery_get_attachment_link($id, $size, false, false, false, $targetsize, $customlink, $link_target);
} else if (!empty($link) && 'file' === $link) {
$image_output = $this->wpmf_gallery_get_attachment_link($id, $size, false, false, false, $targetsize, $customlink, $link_target);
} else if (!empty($link) && 'none' === $link) {
if(get_post_meta($id, _WPMF_GALLERY_PREFIX . 'custom_image_link', true) != ''){
$image_output = $this->wpmf_gallery_get_attachment_link($id, $size, false, false, false, $targetsize, $customlink, $link_target);
}else{
$image_output = wp_get_attachment_image($id, $size, false);
}
} else {
$image_output = $this->wpmf_gallery_get_attachment_link($id, $size, true, false, false, 'large', false, $link_target);
}
$image_meta = wp_get_attachment_metadata($id);
$orientation = '';
if (isset($image_meta['height'], $image_meta['width']))
$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
$width_item = 100/$columns.'%';
$output .= "<figure class='wpmf-gallery-item gallery-item' style='width:$width_item'>";
$output .= "
<div class='gallery-icon {$orientation}'>
$image_output
</div>";
$caption_text = trim($attachment->post_excerpt);
if (!empty($caption_text)) {
$output .= "<figcaption class='wp-caption-text gallery-caption'>" . wptexturize($caption_text) . "</figcaption>";
}
$output .= "</figure>";
$pos++;
}
$output .= "</div>";
?>
|
amunadesigns/amunadesigns
|
wp-content/plugins/wp-media-folder/themes-gallery/gallery-default.php
|
PHP
|
gpl-2.0
| 2,135
|
/* $Id$ */
/*
* lock.c aus dem Taylor-UUCP 1.04. (C)opyright Ian Taylor
*
* Minimal modifiziert...
*/
/* lock.c
Lock and unlock a file name.
Copyright (C) 1991, 1992 Ian Lance Taylor
This file is part of the Taylor UUCP package.
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.
The author of the program may be contacted at ian@airs.com or
c/o Infinity Development Systems, P.O. Box 520, Waltham, MA 02254.
*/
#include "config.h"
#include "zconnect.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#ifdef NEED_MODE_H
#include <sys/mode.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "utility.h"
#include "policy.h"
#ifndef O_RDONLY
#define O_RDONLY 0
#define O_WRONLY 1
#define O_RDWR 2
#endif
#ifndef O_NOCTTY
#define O_NOCTTY 0
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#define TRUE 1
#define FALSE 0
#define IPUBLIC_FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#ifndef S_IRWXU
#define S_IRWXU 0700
#endif
#ifndef S_IRUSR
#define S_IRUSR 0400
#endif
#ifndef S_IWUSR
#define S_IWUSR 0200
#endif
#ifndef S_IXUSR
#define S_IXUSR 0100
#endif
#ifndef S_IRWXG
#define S_IRWXG 0070
#endif
#ifndef S_IRGRP
#define S_IRGRP 0040
#endif
#ifndef S_IWGRP
#define S_IWGRP 0020
#endif
#ifndef S_IXGRP
#define S_IXGRP 0010
#endif
#ifndef S_IRWXO
#define S_IRWXO 0007
#endif
#ifndef S_IROTH
#define S_IROTH 0004
#endif
#ifndef S_IWOTH
#define S_IWOTH 0002
#endif
#ifndef S_IXOTH
#define S_IXOTH 0001
#endif
/* Lock something. If the fspooldir argument is TRUE, the argument is
a file name relative to the spool directory; otherwise the argument
is a simple file name which should be created in the system lock
directory (under HDB this is /etc/locks). */
int fsdo_lock (const char *zlock);
int fsdo_lock (const char *zlock)
{
char *zfree;
const char *zpath, *zslash;
size_t cslash;
pid_t ime;
char *ztempfile;
char abtempfile[sizeof "TMP1234567890"];
int o;
#if HAVE_V2_LOCKFILES
int i;
#else
char ab[12];
#endif
int cwrote;
const char *zerr;
int fret;
zfree = dalloc(strlen(zlock) + sizeof LOCKDIR + 2);
sprintf(zfree, LOCKDIR"/%s", zlock);
zpath = zfree;
ime = getpid ();
/* We do the actual lock by creating a file and then linking it to
the final file name we want. This avoids race conditions due to
one process checking the file before we have finished writing it,
and also works even if we are somehow running as root.
First, create the file in the right directory (we must create the
file in the same directory since otherwise we might attempt a
cross-device link). */
zslash = strrchr (zpath, '/');
if (zslash == NULL)
cslash = 0;
else
cslash = zslash - zpath + 1;
sprintf (abtempfile, "TMP%010lx", (unsigned long) ime);
ztempfile = dalloc (cslash + sizeof abtempfile);
memcpy (ztempfile, zpath, cslash);
memcpy (ztempfile + cslash, abtempfile, sizeof abtempfile);
o = creat (ztempfile, IPUBLIC_FILE_MODE);
if (o < 0)
{
if (errno == ENOENT)
return FALSE;
if (o < 0)
{
fprintf (deblogfile, "creat (%s): %s\n", ztempfile, strerror (errno));
dfree (zfree);
dfree (ztempfile);
return FALSE;
}
}
#if HAVE_V2_LOCKFILES
i = ime;
cwrote = write (o, &i, sizeof i);
#else
sprintf (ab, "%10d\n", (int) ime);
cwrote = write (o, ab, strlen (ab));
#endif
zerr = NULL;
if (cwrote < 0)
zerr = "write";
if (close (o) < 0)
zerr = "close";
if (zerr != NULL)
{
fprintf (deblogfile, "%s (%s): %s\n", zerr, ztempfile, strerror (errno));
(void) remove (ztempfile);
dfree (zfree);
dfree (ztempfile);
return FALSE;
}
/* Now try to link the file we just created to the lock file that we
want. If it fails, try reading the existing file to make sure
the process that created it still exists. We do this in a loop
to make it easy to retry if the old locking process no longer
exists. */
fret = TRUE;
o = -1;
zerr = NULL;
while (link (ztempfile, zpath) != 0)
{
int cgot;
int ipid;
int freadonly;
fret = FALSE;
if (errno != EEXIST)
{
fprintf (deblogfile, "link (%s, %s): %s\n", ztempfile, zpath,
strerror (errno));
break;
}
freadonly = FALSE;
o = open (zpath, O_RDWR | O_NOCTTY, 0);
if (o < 0)
{
if (errno == EACCES)
{
freadonly = TRUE;
o = open (zpath, O_RDONLY, 0);
}
if (o < 0)
{
if (errno == ENOENT)
{
/* The file was presumably removed between the link
and the open. Try the link again. */
fret = TRUE;
continue;
}
zerr = "open";
break;
}
}
/* The race starts here. See below for a discussion. */
#if HAVE_V2_LOCKFILES
cgot = read (o, &i, sizeof i);
#else
cgot = read (o, ab, sizeof ab - 1);
#endif
if (cgot < 0)
{
zerr = "read";
break;
}
#if HAVE_V2_LOCKFILES
ipid = i;
#else
ab[cgot] = '\0';
ipid = strtol (ab, (char **) NULL, 10);
#endif
/* On NFS, the link might have actually succeeded even though we
got a failure return. This can happen if the original
acknowledgement was lost or delayed and the operation was
retried. In this case the pid will be our own. This
introduces a rather improbable race condition: if a stale
lock was left with our process ID in it, and another process
just did the kill, below, but has not yet changed the lock
file to hold its own process ID, we could start up and make
it all the way to here and think we have the lock. I'm not
going to worry about this possibility. */
if (ipid == ime)
{
fret = TRUE;
break;
}
/* If the process still exists, we will get EPERM rather than
ESRCH. We then return FALSE to indicate that we cannot make
the lock. */
if (kill (ipid, 0) == 0 || errno == EPERM)
break;
fprintf (deblogfile, "Found stale lock %s held by process %d\n",
zpath, ipid);
/* This is a stale lock, created by a process that no longer
exists.
Now we could remove the file (and, if the file mode disallows
writing, that's what we have to do), but we try to avoid
doing so since it causes a race condition. If we remove the
file, and are interrupted any time after we do the read until
we do the remove, another process could get in, open the
file, find that it was a stale lock, remove the file and
create a new one. When we regained control we would remove
the file the other process just created.
These files are being generated partially for the benefit of
cu, and it would be nice to avoid the race however cu avoids
it, so that the programs remain compatible. Unfortunately,
nobody seems to know how cu avoids the race, or even if it
tries to avoid it at all.
There are a few ways to avoid the race. We could use kernel
locking primitives, but they may not be available. We could
link to a special file name, but if that file were left lying
around then no stale lock could ever be broken (Henry Spencer
would think this was a good thing).
Instead I've implemented the following procedure: seek to the
start of the file, write our pid into it, sleep for five
seconds, and then make sure our pid is still there. Anybody
who checks the file while we're asleep will find our pid
there and fail the lock. The only race will come from
another process which has done the read by the time we do our
write. That process will then have five seconds to do its
own write. When we wake up, we'll notice that our pid is no
longer in the file, and retry the lock from the beginning.
This relies on the atomicity of write(2). If it possible for
the writes of two processes to be interleaved, the two
processes could livelock. POSIX unfortunately leaves this
case explicitly undefined; however, given that the write is
of less than a disk block, it's difficult to imagine an
interleave occurring.
Note that this is still a race. If it takes the second
process more than five seconds to do the kill, the lseek, and
the write, both processes will think they have the lock.
Perhaps the length of time to sleep should be configurable.
Even better, perhaps I should add a configuration option to
use a permanent lock file, which eliminates any race and
forces the installer to be aware of the existence of the
permanent lock file.
We stat the file after the sleep, to make sure some other
program hasn't deleted it for us. */
if (freadonly)
{
(void) close (o);
o = -1;
(void) remove (zpath);
continue;
}
if (lseek (o, (off_t) 0, SEEK_SET) != 0)
{
zerr = "lseek";
break;
}
#if HAVE_V2_LOCKFILES
i = ime;
cwrote = write (o, &i, sizeof i);
#else
sprintf (ab, "%10d\n", (int) ime);
cwrote = write (o, ab, strlen (ab));
#endif
if (cwrote < 0)
{
zerr = "write";
break;
}
(void) sleep (5);
if (lseek (o, (off_t) 0, SEEK_SET) != 0)
{
zerr = "lseek";
break;
}
#if HAVE_V2_LOCKFILES
cgot = read (o, &i, sizeof i);
#else
cgot = read (o, ab, sizeof ab - 1);
#endif
if (cgot < 0)
{
zerr = "read";
break;
}
#if HAVE_V2_LOCKFILES
ipid = i;
#else
ab[cgot] = '\0';
ipid = strtol (ab, (char **) NULL, 10);
#endif
if (ipid == ime)
{
struct stat sfile, sdescriptor;
/* It looks like we have the lock. Do the final stat
check. */
if (stat (zpath, &sfile) < 0)
{
if (errno != ENOENT)
{
zerr = "stat";
break;
}
/* Loop around and try again. */
}
else
{
if (fstat (o, &sdescriptor) < 0)
{
zerr = "fstat";
break;
}
if (sfile.st_ino == sdescriptor.st_ino
&& sfile.st_dev == sdescriptor.st_dev)
{
/* Close the file before assuming we've succeeded to
pick up any trailing errors. */
if (close (o) < 0)
{
zerr = "close";
break;
}
o = -1;
/* We have the lock. */
fret = TRUE;
break;
}
}
}
/* Loop around and try the lock again. We keep doing this until
the lock file holds a pid that exists. */
(void) close (o);
o = -1;
fret = TRUE;
}
if (zerr != NULL)
{
fprintf (deblogfile, "%s (%s): %s\n", zerr, zpath, strerror (errno));
}
if (o >= 0)
(void) close (o);
dfree (zfree);
/* It would be nice if we could leave the temporary file around for
future calls, but considering that we create lock files in
various different directories it's probably more trouble than
it's worth. */
if (remove (ztempfile) != 0)
fprintf (deblogfile, "remove (%s): %s\n", ztempfile, strerror (errno));
dfree (ztempfile);
return fret;
}
/* Unlock something. The fspooldir argument is as in fsdo_lock. */
int fsdo_unlock (const char *zlock);
int fsdo_unlock (const char *zlock)
{
char *zfree;
const char *zpath;
zfree = dalloc(strlen(zlock) + sizeof LOCKDIR + 2);
sprintf(zfree, LOCKDIR"/%s", zlock);
zpath = zfree;
if (remove (zpath) == 0
|| errno == ENOENT)
{
dfree (zfree);
return TRUE;
}
else
{
fprintf (deblogfile, "remove (%s): %s\n", zpath, strerror (errno));
dfree (zfree);
return FALSE;
}
}
|
dinoex/unix-connect
|
online/lock.c
|
C
|
gpl-2.0
| 12,021
|
/* Partial symbol tables.
Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "symtab.h"
#include "psympriv.h"
#include "objfiles.h"
#include "gdb_assert.h"
#include "block.h"
#include "filenames.h"
#include "source.h"
#include "addrmap.h"
#include "gdbtypes.h"
#include "bcache.h"
#include "ui-out.h"
#include "command.h"
#include "readline/readline.h"
#include "gdb_regex.h"
#include "dictionary.h"
#include "language.h"
#include "cp-support.h"
#ifndef DEV_TTY
#define DEV_TTY "/dev/tty"
#endif
struct psymbol_bcache
{
struct bcache *bcache;
};
/* A fast way to get from a psymtab to its symtab (after the first time). */
#define PSYMTAB_TO_SYMTAB(pst) \
((pst) -> symtab != NULL ? (pst) -> symtab : psymtab_to_symtab (pst))
static struct partial_symbol *match_partial_symbol (struct partial_symtab *,
int,
const char *, domain_enum,
symbol_compare_ftype *,
symbol_compare_ftype *);
static struct partial_symbol *lookup_partial_symbol (struct partial_symtab *,
const char *, int,
domain_enum);
static char *psymtab_to_fullname (struct partial_symtab *ps);
static struct partial_symbol *find_pc_sect_psymbol (struct partial_symtab *,
CORE_ADDR,
struct obj_section *);
static struct partial_symbol *fixup_psymbol_section (struct partial_symbol
*psym,
struct objfile *objfile);
static struct symtab *psymtab_to_symtab (struct partial_symtab *pst);
/* Ensure that the partial symbols for OBJFILE have been loaded. This
function always returns its argument, as a convenience. */
struct objfile *
require_partial_symbols (struct objfile *objfile, int verbose)
{
if ((objfile->flags & OBJF_PSYMTABS_READ) == 0)
{
objfile->flags |= OBJF_PSYMTABS_READ;
if (objfile->sf->sym_read_psymbols)
{
if (verbose)
{
printf_unfiltered (_("Reading symbols from %s..."),
objfile->name);
gdb_flush (gdb_stdout);
}
(*objfile->sf->sym_read_psymbols) (objfile);
if (verbose)
{
if (!objfile_has_symbols (objfile))
{
wrap_here ("");
printf_unfiltered (_("(no debugging symbols found)..."));
wrap_here ("");
}
printf_unfiltered (_("done.\n"));
}
}
}
return objfile;
}
/* Traverse all psymtabs in one objfile, requiring that the psymtabs
be read in. */
#define ALL_OBJFILE_PSYMTABS_REQUIRED(objfile, p) \
for ((p) = require_partial_symbols (objfile, 1)->psymtabs; \
(p) != NULL; \
(p) = (p)->next)
/* We want to make sure this file always requires psymtabs. */
#undef ALL_OBJFILE_PSYMTABS
/* Traverse all psymtabs in all objfiles. */
#define ALL_PSYMTABS(objfile, p) \
ALL_OBJFILES (objfile) \
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, p)
/* Lookup the partial symbol table of a source file named NAME.
*If* there is no '/' in the name, a match after a '/'
in the psymtab filename will also work. */
static struct partial_symtab *
lookup_partial_symtab (struct objfile *objfile, const char *name,
const char *full_path, const char *real_path)
{
struct partial_symtab *pst;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, pst)
{
if (FILENAME_CMP (name, pst->filename) == 0)
{
return (pst);
}
/* If the user gave us an absolute path, try to find the file in
this symtab and use its absolute path. */
if (full_path != NULL)
{
psymtab_to_fullname (pst);
if (pst->fullname != NULL
&& FILENAME_CMP (full_path, pst->fullname) == 0)
{
return pst;
}
}
if (real_path != NULL)
{
char *rp = NULL;
psymtab_to_fullname (pst);
if (pst->fullname != NULL)
{
rp = gdb_realpath (pst->fullname);
make_cleanup (xfree, rp);
}
if (rp != NULL && FILENAME_CMP (real_path, rp) == 0)
{
return pst;
}
}
}
/* Now, search for a matching tail (only if name doesn't have any dirs). */
if (lbasename (name) == name)
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, pst)
{
if (FILENAME_CMP (lbasename (pst->filename), name) == 0)
return (pst);
}
return (NULL);
}
static int
lookup_symtab_via_partial_symtab (struct objfile *objfile, const char *name,
const char *full_path, const char *real_path,
struct symtab **result)
{
struct partial_symtab *ps;
ps = lookup_partial_symtab (objfile, name, full_path, real_path);
if (!ps)
return 0;
if (ps->readin)
error (_("Internal: readin %s pst for `%s' found when no symtab found."),
ps->filename, name);
*result = PSYMTAB_TO_SYMTAB (ps);
return 1;
}
/* Find which partial symtab contains PC and SECTION starting at psymtab PST.
We may find a different psymtab than PST. See FIND_PC_SECT_PSYMTAB. */
static struct partial_symtab *
find_pc_sect_psymtab_closer (CORE_ADDR pc, struct obj_section *section,
struct partial_symtab *pst,
struct minimal_symbol *msymbol)
{
struct objfile *objfile = pst->objfile;
struct partial_symtab *tpst;
struct partial_symtab *best_pst = pst;
CORE_ADDR best_addr = pst->textlow;
/* An objfile that has its functions reordered might have
many partial symbol tables containing the PC, but
we want the partial symbol table that contains the
function containing the PC. */
if (!(objfile->flags & OBJF_REORDERED) &&
section == 0) /* Can't validate section this way. */
return pst;
if (msymbol == NULL)
return (pst);
/* The code range of partial symtabs sometimes overlap, so, in
the loop below, we need to check all partial symtabs and
find the one that fits better for the given PC address. We
select the partial symtab that contains a symbol whose
address is closest to the PC address. By closest we mean
that find_pc_sect_symbol returns the symbol with address
that is closest and still less than the given PC. */
for (tpst = pst; tpst != NULL; tpst = tpst->next)
{
if (pc >= tpst->textlow && pc < tpst->texthigh)
{
struct partial_symbol *p;
CORE_ADDR this_addr;
/* NOTE: This assumes that every psymbol has a
corresponding msymbol, which is not necessarily
true; the debug info might be much richer than the
object's symbol table. */
p = find_pc_sect_psymbol (tpst, pc, section);
if (p != NULL
&& SYMBOL_VALUE_ADDRESS (p)
== SYMBOL_VALUE_ADDRESS (msymbol))
return tpst;
/* Also accept the textlow value of a psymtab as a
"symbol", to provide some support for partial
symbol tables with line information but no debug
symbols (e.g. those produced by an assembler). */
if (p != NULL)
this_addr = SYMBOL_VALUE_ADDRESS (p);
else
this_addr = tpst->textlow;
/* Check whether it is closer than our current
BEST_ADDR. Since this symbol address is
necessarily lower or equal to PC, the symbol closer
to PC is the symbol which address is the highest.
This way we return the psymtab which contains such
best match symbol. This can help in cases where the
symbol information/debuginfo is not complete, like
for instance on IRIX6 with gcc, where no debug info
is emitted for statics. (See also the nodebug.exp
testcase.) */
if (this_addr > best_addr)
{
best_addr = this_addr;
best_pst = tpst;
}
}
}
return best_pst;
}
/* Find which partial symtab contains PC and SECTION. Return 0 if
none. We return the psymtab that contains a symbol whose address
exactly matches PC, or, if we cannot find an exact match, the
psymtab that contains a symbol whose address is closest to PC. */
static struct partial_symtab *
find_pc_sect_psymtab (struct objfile *objfile, CORE_ADDR pc,
struct obj_section *section,
struct minimal_symbol *msymbol)
{
struct partial_symtab *pst;
/* Try just the PSYMTABS_ADDRMAP mapping first as it has better granularity
than the later used TEXTLOW/TEXTHIGH one. */
if (objfile->psymtabs_addrmap != NULL)
{
pst = addrmap_find (objfile->psymtabs_addrmap, pc);
if (pst != NULL)
{
/* FIXME: addrmaps currently do not handle overlayed sections,
so fall back to the non-addrmap case if we're debugging
overlays and the addrmap returned the wrong section. */
if (overlay_debugging && msymbol && section)
{
struct partial_symbol *p;
/* NOTE: This assumes that every psymbol has a
corresponding msymbol, which is not necessarily
true; the debug info might be much richer than the
object's symbol table. */
p = find_pc_sect_psymbol (pst, pc, section);
if (!p
|| SYMBOL_VALUE_ADDRESS (p)
!= SYMBOL_VALUE_ADDRESS (msymbol))
goto next;
}
/* We do not try to call FIND_PC_SECT_PSYMTAB_CLOSER as
PSYMTABS_ADDRMAP we used has already the best 1-byte
granularity and FIND_PC_SECT_PSYMTAB_CLOSER may mislead us into
a worse chosen section due to the TEXTLOW/TEXTHIGH ranges
overlap. */
return pst;
}
}
next:
/* Existing PSYMTABS_ADDRMAP mapping is present even for PARTIAL_SYMTABs
which still have no corresponding full SYMTABs read. But it is not
present for non-DWARF2 debug infos not supporting PSYMTABS_ADDRMAP in GDB
so far. */
/* Check even OBJFILE with non-zero PSYMTABS_ADDRMAP as only several of
its CUs may be missing in PSYMTABS_ADDRMAP as they may be varying
debug info type in single OBJFILE. */
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, pst)
if (pc >= pst->textlow && pc < pst->texthigh)
{
struct partial_symtab *best_pst;
best_pst = find_pc_sect_psymtab_closer (pc, section, pst, msymbol);
if (best_pst != NULL)
return best_pst;
}
return NULL;
}
static struct symtab *
find_pc_sect_symtab_from_partial (struct objfile *objfile,
struct minimal_symbol *msymbol,
CORE_ADDR pc, struct obj_section *section,
int warn_if_readin)
{
struct partial_symtab *ps = find_pc_sect_psymtab (objfile, pc, section,
msymbol);
if (ps)
{
if (warn_if_readin && ps->readin)
/* Might want to error() here (in case symtab is corrupt and
will cause a core dump), but maybe we can successfully
continue, so let's not. */
warning (_("\
(Internal error: pc %s in read in psymtab, but not in symtab.)\n"),
paddress (get_objfile_arch (ps->objfile), pc));
return PSYMTAB_TO_SYMTAB (ps);
}
return NULL;
}
/* Find which partial symbol within a psymtab matches PC and SECTION.
Return 0 if none. */
static struct partial_symbol *
find_pc_sect_psymbol (struct partial_symtab *psymtab, CORE_ADDR pc,
struct obj_section *section)
{
struct partial_symbol *best = NULL, *p, **pp;
CORE_ADDR best_pc;
gdb_assert (psymtab != NULL);
/* Cope with programs that start at address 0. */
best_pc = (psymtab->textlow != 0) ? psymtab->textlow - 1 : 0;
/* Search the global symbols as well as the static symbols, so that
find_pc_partial_function doesn't use a minimal symbol and thus
cache a bad endaddr. */
for (pp = psymtab->objfile->global_psymbols.list + psymtab->globals_offset;
(pp - (psymtab->objfile->global_psymbols.list + psymtab->globals_offset)
< psymtab->n_global_syms);
pp++)
{
p = *pp;
if (SYMBOL_DOMAIN (p) == VAR_DOMAIN
&& SYMBOL_CLASS (p) == LOC_BLOCK
&& pc >= SYMBOL_VALUE_ADDRESS (p)
&& (SYMBOL_VALUE_ADDRESS (p) > best_pc
|| (psymtab->textlow == 0
&& best_pc == 0 && SYMBOL_VALUE_ADDRESS (p) == 0)))
{
if (section) /* Match on a specific section. */
{
fixup_psymbol_section (p, psymtab->objfile);
if (!matching_obj_sections (SYMBOL_OBJ_SECTION (p), section))
continue;
}
best_pc = SYMBOL_VALUE_ADDRESS (p);
best = p;
}
}
for (pp = psymtab->objfile->static_psymbols.list + psymtab->statics_offset;
(pp - (psymtab->objfile->static_psymbols.list + psymtab->statics_offset)
< psymtab->n_static_syms);
pp++)
{
p = *pp;
if (SYMBOL_DOMAIN (p) == VAR_DOMAIN
&& SYMBOL_CLASS (p) == LOC_BLOCK
&& pc >= SYMBOL_VALUE_ADDRESS (p)
&& (SYMBOL_VALUE_ADDRESS (p) > best_pc
|| (psymtab->textlow == 0
&& best_pc == 0 && SYMBOL_VALUE_ADDRESS (p) == 0)))
{
if (section) /* Match on a specific section. */
{
fixup_psymbol_section (p, psymtab->objfile);
if (!matching_obj_sections (SYMBOL_OBJ_SECTION (p), section))
continue;
}
best_pc = SYMBOL_VALUE_ADDRESS (p);
best = p;
}
}
return best;
}
static struct partial_symbol *
fixup_psymbol_section (struct partial_symbol *psym, struct objfile *objfile)
{
CORE_ADDR addr;
if (!psym)
return NULL;
if (SYMBOL_OBJ_SECTION (psym))
return psym;
gdb_assert (objfile);
switch (SYMBOL_CLASS (psym))
{
case LOC_STATIC:
case LOC_LABEL:
case LOC_BLOCK:
addr = SYMBOL_VALUE_ADDRESS (psym);
break;
default:
/* Nothing else will be listed in the minsyms -- no use looking
it up. */
return psym;
}
fixup_section (&psym->ginfo, addr, objfile);
return psym;
}
static struct symtab *
lookup_symbol_aux_psymtabs (struct objfile *objfile,
int block_index, const char *name,
const domain_enum domain)
{
struct partial_symtab *ps;
const int psymtab_index = (block_index == GLOBAL_BLOCK ? 1 : 0);
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
if (!ps->readin && lookup_partial_symbol (ps, name, psymtab_index, domain))
{
struct symbol *sym = NULL;
struct symtab *stab = PSYMTAB_TO_SYMTAB (ps);
/* Some caution must be observed with overloaded functions
and methods, since the psymtab will not contain any overload
information (but NAME might contain it). */
if (stab->primary)
{
struct blockvector *bv = BLOCKVECTOR (stab);
struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
sym = lookup_block_symbol (block, name, domain);
}
if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
return stab;
/* Keep looking through other psymtabs. */
}
}
return NULL;
}
/* Look in PST for a symbol in DOMAIN whose name matches NAME. Search
the global block of PST if GLOBAL, and otherwise the static block.
MATCH is the comparison operation that returns true iff MATCH (s,
NAME), where s is a SYMBOL_SEARCH_NAME. If ORDERED_COMPARE is
non-null, the symbols in the block are assumed to be ordered
according to it (allowing binary search). It must be compatible
with MATCH. Returns the symbol, if found, and otherwise NULL. */
static struct partial_symbol *
match_partial_symbol (struct partial_symtab *pst, int global,
const char *name, domain_enum domain,
symbol_compare_ftype *match,
symbol_compare_ftype *ordered_compare)
{
struct partial_symbol **start, **psym;
struct partial_symbol **top, **real_top, **bottom, **center;
int length = (global ? pst->n_global_syms : pst->n_static_syms);
int do_linear_search = 1;
if (length == 0)
return NULL;
start = (global ?
pst->objfile->global_psymbols.list + pst->globals_offset :
pst->objfile->static_psymbols.list + pst->statics_offset);
if (global && ordered_compare) /* Can use a binary search. */
{
do_linear_search = 0;
/* Binary search. This search is guaranteed to end with center
pointing at the earliest partial symbol whose name might be
correct. At that point *all* partial symbols with an
appropriate name will be checked against the correct
domain. */
bottom = start;
top = start + length - 1;
real_top = top;
while (top > bottom)
{
center = bottom + (top - bottom) / 2;
gdb_assert (center < top);
if (!do_linear_search
&& (SYMBOL_LANGUAGE (*center) == language_java))
do_linear_search = 1;
if (ordered_compare (SYMBOL_SEARCH_NAME (*center), name) >= 0)
top = center;
else
bottom = center + 1;
}
gdb_assert (top == bottom);
while (top <= real_top
&& match (SYMBOL_SEARCH_NAME (*top), name) == 0)
{
if (symbol_matches_domain (SYMBOL_LANGUAGE (*top),
SYMBOL_DOMAIN (*top), domain))
return *top;
top++;
}
}
/* Can't use a binary search or else we found during the binary search that
we should also do a linear search. */
if (do_linear_search)
{
for (psym = start; psym < start + length; psym++)
{
if (symbol_matches_domain (SYMBOL_LANGUAGE (*psym),
SYMBOL_DOMAIN (*psym), domain)
&& match (SYMBOL_SEARCH_NAME (*psym), name) == 0)
return *psym;
}
}
return NULL;
}
static void
pre_expand_symtabs_matching_psymtabs (struct objfile *objfile,
enum block_enum block_kind,
const char *name,
domain_enum domain)
{
/* Nothing. */
}
/* Returns the name used to search psymtabs. Unlike symtabs, psymtabs do
not contain any method/function instance information (since this would
force reading type information while reading psymtabs). Therefore,
if NAME contains overload information, it must be stripped before searching
psymtabs.
The caller is responsible for freeing the return result. */
static char *
psymtab_search_name (const char *name)
{
switch (current_language->la_language)
{
case language_cplus:
case language_java:
{
if (strchr (name, '('))
{
char *ret = cp_remove_params (name);
if (ret)
return ret;
}
}
break;
default:
break;
}
return xstrdup (name);
}
/* Look, in partial_symtab PST, for symbol whose natural name is NAME.
Check the global symbols if GLOBAL, the static symbols if not. */
static struct partial_symbol *
lookup_partial_symbol (struct partial_symtab *pst, const char *name,
int global, domain_enum domain)
{
struct partial_symbol **start, **psym;
struct partial_symbol **top, **real_top, **bottom, **center;
int length = (global ? pst->n_global_syms : pst->n_static_syms);
int do_linear_search = 1;
char *search_name;
struct cleanup *cleanup;
if (length == 0)
{
return (NULL);
}
search_name = psymtab_search_name (name);
cleanup = make_cleanup (xfree, search_name);
start = (global ?
pst->objfile->global_psymbols.list + pst->globals_offset :
pst->objfile->static_psymbols.list + pst->statics_offset);
if (global) /* This means we can use a binary search. */
{
do_linear_search = 0;
/* Binary search. This search is guaranteed to end with center
pointing at the earliest partial symbol whose name might be
correct. At that point *all* partial symbols with an
appropriate name will be checked against the correct
domain. */
bottom = start;
top = start + length - 1;
real_top = top;
while (top > bottom)
{
center = bottom + (top - bottom) / 2;
if (!(center < top))
internal_error (__FILE__, __LINE__,
_("failed internal consistency check"));
if (!do_linear_search
&& SYMBOL_LANGUAGE (*center) == language_java)
{
do_linear_search = 1;
}
if (strcmp_iw_ordered (SYMBOL_SEARCH_NAME (*center),
search_name) >= 0)
{
top = center;
}
else
{
bottom = center + 1;
}
}
if (!(top == bottom))
internal_error (__FILE__, __LINE__,
_("failed internal consistency check"));
/* For `case_sensitivity == case_sensitive_off' strcmp_iw_ordered will
search more exactly than what matches SYMBOL_MATCHES_SEARCH_NAME. */
while (top >= start && SYMBOL_MATCHES_SEARCH_NAME (*top, search_name))
top--;
/* Fixup to have a symbol which matches SYMBOL_MATCHES_SEARCH_NAME. */
top++;
while (top <= real_top && SYMBOL_MATCHES_SEARCH_NAME (*top, search_name))
{
if (symbol_matches_domain (SYMBOL_LANGUAGE (*top),
SYMBOL_DOMAIN (*top), domain))
{
do_cleanups (cleanup);
return (*top);
}
top++;
}
}
/* Can't use a binary search or else we found during the binary search that
we should also do a linear search. */
if (do_linear_search)
{
for (psym = start; psym < start + length; psym++)
{
if (symbol_matches_domain (SYMBOL_LANGUAGE (*psym),
SYMBOL_DOMAIN (*psym), domain)
&& SYMBOL_MATCHES_SEARCH_NAME (*psym, search_name))
{
do_cleanups (cleanup);
return (*psym);
}
}
}
do_cleanups (cleanup);
return (NULL);
}
/* Get the symbol table that corresponds to a partial_symtab.
This is fast after the first time you do it. In fact, there
is an even faster macro PSYMTAB_TO_SYMTAB that does the fast
case inline. */
static struct symtab *
psymtab_to_symtab (struct partial_symtab *pst)
{
/* If it's been looked up before, return it. */
if (pst->symtab)
return pst->symtab;
/* If it has not yet been read in, read it. */
if (!pst->readin)
{
struct cleanup *back_to = increment_reading_symtab ();
(*pst->read_symtab) (pst);
do_cleanups (back_to);
}
return pst->symtab;
}
static void
relocate_psymtabs (struct objfile *objfile,
struct section_offsets *new_offsets,
struct section_offsets *delta)
{
struct partial_symbol **psym;
struct partial_symtab *p;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, p)
{
p->textlow += ANOFFSET (delta, SECT_OFF_TEXT (objfile));
p->texthigh += ANOFFSET (delta, SECT_OFF_TEXT (objfile));
}
for (psym = objfile->global_psymbols.list;
psym < objfile->global_psymbols.next;
psym++)
{
fixup_psymbol_section (*psym, objfile);
if (SYMBOL_SECTION (*psym) >= 0)
SYMBOL_VALUE_ADDRESS (*psym) += ANOFFSET (delta,
SYMBOL_SECTION (*psym));
}
for (psym = objfile->static_psymbols.list;
psym < objfile->static_psymbols.next;
psym++)
{
fixup_psymbol_section (*psym, objfile);
if (SYMBOL_SECTION (*psym) >= 0)
SYMBOL_VALUE_ADDRESS (*psym) += ANOFFSET (delta,
SYMBOL_SECTION (*psym));
}
}
static struct symtab *
find_last_source_symtab_from_partial (struct objfile *ofp)
{
struct partial_symtab *ps;
struct partial_symtab *cs_pst = 0;
ALL_OBJFILE_PSYMTABS_REQUIRED (ofp, ps)
{
const char *name = ps->filename;
int len = strlen (name);
if (!(len > 2 && (strcmp (&name[len - 2], ".h") == 0
|| strcmp (name, "<<C++-namespaces>>") == 0)))
cs_pst = ps;
}
if (cs_pst)
{
if (cs_pst->readin)
{
internal_error (__FILE__, __LINE__,
_("select_source_symtab: "
"readin pst found and no symtabs."));
}
else
return PSYMTAB_TO_SYMTAB (cs_pst);
}
return NULL;
}
static void
forget_cached_source_info_partial (struct objfile *objfile)
{
struct partial_symtab *pst;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, pst)
{
if (pst->fullname != NULL)
{
xfree (pst->fullname);
pst->fullname = NULL;
}
}
}
static void
print_partial_symbols (struct gdbarch *gdbarch,
struct partial_symbol **p, int count, char *what,
struct ui_file *outfile)
{
fprintf_filtered (outfile, " %s partial symbols:\n", what);
while (count-- > 0)
{
fprintf_filtered (outfile, " `%s'", SYMBOL_LINKAGE_NAME (*p));
if (SYMBOL_DEMANGLED_NAME (*p) != NULL)
{
fprintf_filtered (outfile, " `%s'", SYMBOL_DEMANGLED_NAME (*p));
}
fputs_filtered (", ", outfile);
switch (SYMBOL_DOMAIN (*p))
{
case UNDEF_DOMAIN:
fputs_filtered ("undefined domain, ", outfile);
break;
case VAR_DOMAIN:
/* This is the usual thing -- don't print it. */
break;
case STRUCT_DOMAIN:
fputs_filtered ("struct domain, ", outfile);
break;
case LABEL_DOMAIN:
fputs_filtered ("label domain, ", outfile);
break;
default:
fputs_filtered ("<invalid domain>, ", outfile);
break;
}
switch (SYMBOL_CLASS (*p))
{
case LOC_UNDEF:
fputs_filtered ("undefined", outfile);
break;
case LOC_CONST:
fputs_filtered ("constant int", outfile);
break;
case LOC_STATIC:
fputs_filtered ("static", outfile);
break;
case LOC_REGISTER:
fputs_filtered ("register", outfile);
break;
case LOC_ARG:
fputs_filtered ("pass by value", outfile);
break;
case LOC_REF_ARG:
fputs_filtered ("pass by reference", outfile);
break;
case LOC_REGPARM_ADDR:
fputs_filtered ("register address parameter", outfile);
break;
case LOC_LOCAL:
fputs_filtered ("stack parameter", outfile);
break;
case LOC_TYPEDEF:
fputs_filtered ("type", outfile);
break;
case LOC_LABEL:
fputs_filtered ("label", outfile);
break;
case LOC_BLOCK:
fputs_filtered ("function", outfile);
break;
case LOC_CONST_BYTES:
fputs_filtered ("constant bytes", outfile);
break;
case LOC_UNRESOLVED:
fputs_filtered ("unresolved", outfile);
break;
case LOC_OPTIMIZED_OUT:
fputs_filtered ("optimized out", outfile);
break;
case LOC_COMPUTED:
fputs_filtered ("computed at runtime", outfile);
break;
default:
fputs_filtered ("<invalid location>", outfile);
break;
}
fputs_filtered (", ", outfile);
fputs_filtered (paddress (gdbarch, SYMBOL_VALUE_ADDRESS (*p)), outfile);
fprintf_filtered (outfile, "\n");
p++;
}
}
static void
dump_psymtab (struct objfile *objfile, struct partial_symtab *psymtab,
struct ui_file *outfile)
{
struct gdbarch *gdbarch = get_objfile_arch (objfile);
int i;
fprintf_filtered (outfile, "\nPartial symtab for source file %s ",
psymtab->filename);
fprintf_filtered (outfile, "(object ");
gdb_print_host_address (psymtab, outfile);
fprintf_filtered (outfile, ")\n\n");
fprintf_unfiltered (outfile, " Read from object file %s (",
objfile->name);
gdb_print_host_address (objfile, outfile);
fprintf_unfiltered (outfile, ")\n");
if (psymtab->readin)
{
fprintf_filtered (outfile,
" Full symtab was read (at ");
gdb_print_host_address (psymtab->symtab, outfile);
fprintf_filtered (outfile, " by function at ");
gdb_print_host_address (psymtab->read_symtab, outfile);
fprintf_filtered (outfile, ")\n");
}
fprintf_filtered (outfile, " Relocate symbols by ");
for (i = 0; i < psymtab->objfile->num_sections; ++i)
{
if (i != 0)
fprintf_filtered (outfile, ", ");
wrap_here (" ");
fputs_filtered (paddress (gdbarch,
ANOFFSET (psymtab->section_offsets, i)),
outfile);
}
fprintf_filtered (outfile, "\n");
fprintf_filtered (outfile, " Symbols cover text addresses ");
fputs_filtered (paddress (gdbarch, psymtab->textlow), outfile);
fprintf_filtered (outfile, "-");
fputs_filtered (paddress (gdbarch, psymtab->texthigh), outfile);
fprintf_filtered (outfile, "\n");
fprintf_filtered (outfile, " Depends on %d other partial symtabs.\n",
psymtab->number_of_dependencies);
for (i = 0; i < psymtab->number_of_dependencies; i++)
{
fprintf_filtered (outfile, " %d ", i);
gdb_print_host_address (psymtab->dependencies[i], outfile);
fprintf_filtered (outfile, " %s\n",
psymtab->dependencies[i]->filename);
}
if (psymtab->n_global_syms > 0)
{
print_partial_symbols (gdbarch,
objfile->global_psymbols.list
+ psymtab->globals_offset,
psymtab->n_global_syms, "Global", outfile);
}
if (psymtab->n_static_syms > 0)
{
print_partial_symbols (gdbarch,
objfile->static_psymbols.list
+ psymtab->statics_offset,
psymtab->n_static_syms, "Static", outfile);
}
fprintf_filtered (outfile, "\n");
}
static void
print_psymtab_stats_for_objfile (struct objfile *objfile)
{
int i;
struct partial_symtab *ps;
i = 0;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
if (ps->readin == 0)
i++;
}
printf_filtered (_(" Number of psym tables (not yet expanded): %d\n"), i);
}
static void
dump_psymtabs_for_objfile (struct objfile *objfile)
{
struct partial_symtab *psymtab;
if (objfile->psymtabs)
{
printf_filtered ("Psymtabs:\n");
for (psymtab = objfile->psymtabs;
psymtab != NULL;
psymtab = psymtab->next)
{
printf_filtered ("%s at ",
psymtab->filename);
gdb_print_host_address (psymtab, gdb_stdout);
printf_filtered (", ");
if (psymtab->objfile != objfile)
{
printf_filtered ("NOT ON CHAIN! ");
}
wrap_here (" ");
}
printf_filtered ("\n\n");
}
}
/* Look through the partial symtabs for all symbols which begin
by matching FUNC_NAME. Make sure we read that symbol table in. */
static void
read_symtabs_for_function (struct objfile *objfile, const char *func_name)
{
struct partial_symtab *ps;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
if (ps->readin)
continue;
if ((lookup_partial_symbol (ps, func_name, 1, VAR_DOMAIN)
!= NULL)
|| (lookup_partial_symbol (ps, func_name, 0, VAR_DOMAIN)
!= NULL))
psymtab_to_symtab (ps);
}
}
static void
expand_partial_symbol_tables (struct objfile *objfile)
{
struct partial_symtab *psymtab;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, psymtab)
{
psymtab_to_symtab (psymtab);
}
}
static void
read_psymtabs_with_filename (struct objfile *objfile, const char *filename)
{
struct partial_symtab *p;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, p)
{
if (filename_cmp (filename, p->filename) == 0)
PSYMTAB_TO_SYMTAB (p);
}
}
static void
map_symbol_filenames_psymtab (struct objfile *objfile,
symbol_filename_ftype *fun, void *data)
{
struct partial_symtab *ps;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
const char *fullname;
if (ps->readin)
continue;
fullname = psymtab_to_fullname (ps);
(*fun) (ps->filename, fullname, data);
}
}
int find_and_open_source (const char *filename,
const char *dirname,
char **fullname);
/* Finds the fullname that a partial_symtab represents.
If this functions finds the fullname, it will save it in ps->fullname
and it will also return the value.
If this function fails to find the file that this partial_symtab represents,
NULL will be returned and ps->fullname will be set to NULL. */
static char *
psymtab_to_fullname (struct partial_symtab *ps)
{
int r;
if (!ps)
return NULL;
/* Don't check ps->fullname here, the file could have been
deleted/moved/..., look for it again. */
r = find_and_open_source (ps->filename, ps->dirname, &ps->fullname);
if (r >= 0)
{
close (r);
return ps->fullname;
}
return NULL;
}
static const char *
find_symbol_file_from_partial (struct objfile *objfile, const char *name)
{
struct partial_symtab *pst;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, pst)
{
if (lookup_partial_symbol (pst, name, 1, VAR_DOMAIN))
return pst->filename;
}
return NULL;
}
/* For all symbols, s, in BLOCK that are in NAMESPACE and match NAME
according to the function MATCH, call CALLBACK(BLOCK, s, DATA).
BLOCK is assumed to come from OBJFILE. Returns 1 iff CALLBACK
ever returns non-zero, and otherwise returns 0. */
static int
map_block (const char *name, domain_enum namespace, struct objfile *objfile,
struct block *block,
int (*callback) (struct block *, struct symbol *, void *),
void *data, symbol_compare_ftype *match)
{
struct dict_iterator iter;
struct symbol *sym;
for (sym = dict_iter_match_first (BLOCK_DICT (block), name, match, &iter);
sym != NULL; sym = dict_iter_match_next (name, match, &iter))
{
if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
SYMBOL_DOMAIN (sym), namespace))
{
if (callback (block, sym, data))
return 1;
}
}
return 0;
}
/* Psymtab version of map_matching_symbols. See its definition in
the definition of quick_symbol_functions in symfile.h. */
static void
map_matching_symbols_psymtab (const char *name, domain_enum namespace,
struct objfile *objfile, int global,
int (*callback) (struct block *,
struct symbol *, void *),
void *data,
symbol_compare_ftype *match,
symbol_compare_ftype *ordered_compare)
{
const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
struct partial_symtab *ps;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
QUIT;
if (ps->readin
|| match_partial_symbol (ps, global, name, namespace, match,
ordered_compare))
{
struct symtab *s = PSYMTAB_TO_SYMTAB (ps);
struct block *block;
if (s == NULL || !s->primary)
continue;
block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), block_kind);
if (map_block (name, namespace, objfile, block,
callback, data, match))
return;
if (callback (block, NULL, data))
return;
}
}
}
static void
expand_symtabs_matching_via_partial (struct objfile *objfile,
int (*file_matcher) (const char *,
void *),
int (*name_matcher) (const char *,
void *),
enum search_domain kind,
void *data)
{
struct partial_symtab *ps;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, ps)
{
struct partial_symbol **psym;
struct partial_symbol **bound, **gbound, **sbound;
int keep_going = 1;
if (ps->readin)
continue;
if (file_matcher && ! (*file_matcher) (ps->filename, data))
continue;
gbound = objfile->global_psymbols.list
+ ps->globals_offset + ps->n_global_syms;
sbound = objfile->static_psymbols.list
+ ps->statics_offset + ps->n_static_syms;
bound = gbound;
/* Go through all of the symbols stored in a partial
symtab in one loop. */
psym = objfile->global_psymbols.list + ps->globals_offset;
while (keep_going)
{
if (psym >= bound)
{
if (bound == gbound && ps->n_static_syms != 0)
{
psym = objfile->static_psymbols.list + ps->statics_offset;
bound = sbound;
}
else
keep_going = 0;
continue;
}
else
{
QUIT;
if ((kind == ALL_DOMAIN
|| (kind == VARIABLES_DOMAIN
&& SYMBOL_CLASS (*psym) != LOC_TYPEDEF
&& SYMBOL_CLASS (*psym) != LOC_BLOCK)
|| (kind == FUNCTIONS_DOMAIN
&& SYMBOL_CLASS (*psym) == LOC_BLOCK)
|| (kind == TYPES_DOMAIN
&& SYMBOL_CLASS (*psym) == LOC_TYPEDEF))
&& (*name_matcher) (SYMBOL_NATURAL_NAME (*psym), data))
{
PSYMTAB_TO_SYMTAB (ps);
keep_going = 0;
}
}
psym++;
}
}
}
static int
objfile_has_psyms (struct objfile *objfile)
{
return objfile->psymtabs != NULL;
}
const struct quick_symbol_functions psym_functions =
{
objfile_has_psyms,
find_last_source_symtab_from_partial,
forget_cached_source_info_partial,
lookup_symtab_via_partial_symtab,
lookup_symbol_aux_psymtabs,
pre_expand_symtabs_matching_psymtabs,
print_psymtab_stats_for_objfile,
dump_psymtabs_for_objfile,
relocate_psymtabs,
read_symtabs_for_function,
expand_partial_symbol_tables,
read_psymtabs_with_filename,
find_symbol_file_from_partial,
map_matching_symbols_psymtab,
expand_symtabs_matching_via_partial,
find_pc_sect_symtab_from_partial,
map_symbol_filenames_psymtab
};
/* This compares two partial symbols by names, using strcmp_iw_ordered
for the comparison. */
static int
compare_psymbols (const void *s1p, const void *s2p)
{
struct partial_symbol *const *s1 = s1p;
struct partial_symbol *const *s2 = s2p;
return strcmp_iw_ordered (SYMBOL_SEARCH_NAME (*s1),
SYMBOL_SEARCH_NAME (*s2));
}
void
sort_pst_symbols (struct partial_symtab *pst)
{
/* Sort the global list; don't sort the static list. */
qsort (pst->objfile->global_psymbols.list + pst->globals_offset,
pst->n_global_syms, sizeof (struct partial_symbol *),
compare_psymbols);
}
/* Allocate and partially fill a partial symtab. It will be
completely filled at the end of the symbol list.
FILENAME is the name of the symbol-file we are reading from. */
struct partial_symtab *
start_psymtab_common (struct objfile *objfile,
struct section_offsets *section_offsets,
const char *filename,
CORE_ADDR textlow, struct partial_symbol **global_syms,
struct partial_symbol **static_syms)
{
struct partial_symtab *psymtab;
psymtab = allocate_psymtab (filename, objfile);
psymtab->section_offsets = section_offsets;
psymtab->textlow = textlow;
psymtab->texthigh = psymtab->textlow; /* default */
psymtab->globals_offset = global_syms - objfile->global_psymbols.list;
psymtab->statics_offset = static_syms - objfile->static_psymbols.list;
return (psymtab);
}
/* Calculate a hash code for the given partial symbol. The hash is
calculated using the symbol's value, language, domain, class
and name. These are the values which are set by
add_psymbol_to_bcache. */
static unsigned long
psymbol_hash (const void *addr, int length)
{
unsigned long h = 0;
struct partial_symbol *psymbol = (struct partial_symbol *) addr;
unsigned int lang = psymbol->ginfo.language;
unsigned int domain = PSYMBOL_DOMAIN (psymbol);
unsigned int class = PSYMBOL_CLASS (psymbol);
h = hash_continue (&psymbol->ginfo.value, sizeof (psymbol->ginfo.value), h);
h = hash_continue (&lang, sizeof (unsigned int), h);
h = hash_continue (&domain, sizeof (unsigned int), h);
h = hash_continue (&class, sizeof (unsigned int), h);
h = hash_continue (psymbol->ginfo.name, strlen (psymbol->ginfo.name), h);
return h;
}
/* Returns true if the symbol at addr1 equals the symbol at addr2.
For the comparison this function uses a symbols value,
language, domain, class and name. */
static int
psymbol_compare (const void *addr1, const void *addr2, int length)
{
struct partial_symbol *sym1 = (struct partial_symbol *) addr1;
struct partial_symbol *sym2 = (struct partial_symbol *) addr2;
return (memcmp (&sym1->ginfo.value, &sym1->ginfo.value,
sizeof (sym1->ginfo.value)) == 0
&& sym1->ginfo.language == sym2->ginfo.language
&& PSYMBOL_DOMAIN (sym1) == PSYMBOL_DOMAIN (sym2)
&& PSYMBOL_CLASS (sym1) == PSYMBOL_CLASS (sym2)
&& sym1->ginfo.name == sym2->ginfo.name);
}
/* Initialize a partial symbol bcache. */
struct psymbol_bcache *
psymbol_bcache_init (void)
{
struct psymbol_bcache *bcache = XCALLOC (1, struct psymbol_bcache);
bcache->bcache = bcache_xmalloc (psymbol_hash, psymbol_compare);
return bcache;
}
/* Free a partial symbol bcache. */
void
psymbol_bcache_free (struct psymbol_bcache *bcache)
{
if (bcache == NULL)
return;
bcache_xfree (bcache->bcache);
xfree (bcache);
}
/* Return the internal bcache of the psymbol_bcache BCACHE. */
struct bcache *
psymbol_bcache_get_bcache (struct psymbol_bcache *bcache)
{
return bcache->bcache;
}
/* Find a copy of the SYM in BCACHE. If BCACHE has never seen this
symbol before, add a copy to BCACHE. In either case, return a pointer
to BCACHE's copy of the symbol. If optional ADDED is not NULL, return
1 in case of new entry or 0 if returning an old entry. */
static const struct partial_symbol *
psymbol_bcache_full (struct partial_symbol *sym,
struct psymbol_bcache *bcache,
int *added)
{
return bcache_full (sym,
sizeof (struct partial_symbol),
bcache->bcache,
added);
}
/* Helper function, initialises partial symbol structure and stashes
it into objfile's bcache. Note that our caching mechanism will
use all fields of struct partial_symbol to determine hash value of the
structure. In other words, having two symbols with the same name but
different domain (or address) is possible and correct. */
static const struct partial_symbol *
add_psymbol_to_bcache (const char *name, int namelength, int copy_name,
domain_enum domain,
enum address_class class,
long val, /* Value as a long */
CORE_ADDR coreaddr, /* Value as a CORE_ADDR */
enum language language, struct objfile *objfile,
int *added)
{
struct partial_symbol psymbol;
/* We must ensure that the entire 'value' field has been zeroed
before assigning to it, because an assignment may not write the
entire field. */
memset (&psymbol.ginfo.value, 0, sizeof (psymbol.ginfo.value));
/* val and coreaddr are mutually exclusive, one of them *will* be zero. */
if (val != 0)
{
SYMBOL_VALUE (&psymbol) = val;
}
else
{
SYMBOL_VALUE_ADDRESS (&psymbol) = coreaddr;
}
SYMBOL_SECTION (&psymbol) = 0;
SYMBOL_OBJ_SECTION (&psymbol) = NULL;
SYMBOL_SET_LANGUAGE (&psymbol, language);
PSYMBOL_DOMAIN (&psymbol) = domain;
PSYMBOL_CLASS (&psymbol) = class;
SYMBOL_SET_NAMES (&psymbol, name, namelength, copy_name, objfile);
/* Stash the partial symbol away in the cache. */
return psymbol_bcache_full (&psymbol,
objfile->psymbol_cache,
added);
}
/* Increase the space allocated for LISTP, which is probably
global_psymbols or static_psymbols. This space will eventually
be freed in free_objfile(). */
static void
extend_psymbol_list (struct psymbol_allocation_list *listp,
struct objfile *objfile)
{
int new_size;
if (listp->size == 0)
{
new_size = 255;
listp->list = (struct partial_symbol **)
xmalloc (new_size * sizeof (struct partial_symbol *));
}
else
{
new_size = listp->size * 2;
listp->list = (struct partial_symbol **)
xrealloc ((char *) listp->list,
new_size * sizeof (struct partial_symbol *));
}
/* Next assumes we only went one over. Should be good if
program works correctly. */
listp->next = listp->list + listp->size;
listp->size = new_size;
}
/* Helper function, adds partial symbol to the given partial symbol
list. */
static void
append_psymbol_to_list (struct psymbol_allocation_list *list,
const struct partial_symbol *psym,
struct objfile *objfile)
{
if (list->next >= list->list + list->size)
extend_psymbol_list (list, objfile);
*list->next++ = (struct partial_symbol *) psym;
OBJSTAT (objfile, n_psyms++);
}
/* Add a symbol with a long value to a psymtab.
Since one arg is a struct, we pass in a ptr and deref it (sigh).
Return the partial symbol that has been added. */
/* NOTE: carlton/2003-09-11: The reason why we return the partial
symbol is so that callers can get access to the symbol's demangled
name, which they don't have any cheap way to determine otherwise.
(Currenly, dwarf2read.c is the only file who uses that information,
though it's possible that other readers might in the future.)
Elena wasn't thrilled about that, and I don't blame her, but we
couldn't come up with a better way to get that information. If
it's needed in other situations, we could consider breaking up
SYMBOL_SET_NAMES to provide access to the demangled name lookup
cache. */
const struct partial_symbol *
add_psymbol_to_list (const char *name, int namelength, int copy_name,
domain_enum domain,
enum address_class class,
struct psymbol_allocation_list *list,
long val, /* Value as a long */
CORE_ADDR coreaddr, /* Value as a CORE_ADDR */
enum language language, struct objfile *objfile)
{
const struct partial_symbol *psym;
int added;
/* Stash the partial symbol away in the cache. */
psym = add_psymbol_to_bcache (name, namelength, copy_name, domain, class,
val, coreaddr, language, objfile, &added);
/* Do not duplicate global partial symbols. */
if (list == &objfile->global_psymbols
&& !added)
return psym;
/* Save pointer to partial symbol in psymtab, growing symtab if needed. */
append_psymbol_to_list (list, psym, objfile);
return psym;
}
/* Initialize storage for partial symbols. */
void
init_psymbol_list (struct objfile *objfile, int total_symbols)
{
/* Free any previously allocated psymbol lists. */
if (objfile->global_psymbols.list)
{
xfree (objfile->global_psymbols.list);
}
if (objfile->static_psymbols.list)
{
xfree (objfile->static_psymbols.list);
}
/* Current best guess is that approximately a twentieth
of the total symbols (in a debugging file) are global or static
oriented symbols. */
objfile->global_psymbols.size = total_symbols / 10;
objfile->static_psymbols.size = total_symbols / 10;
if (objfile->global_psymbols.size > 0)
{
objfile->global_psymbols.next =
objfile->global_psymbols.list = (struct partial_symbol **)
xmalloc ((objfile->global_psymbols.size
* sizeof (struct partial_symbol *)));
}
if (objfile->static_psymbols.size > 0)
{
objfile->static_psymbols.next =
objfile->static_psymbols.list = (struct partial_symbol **)
xmalloc ((objfile->static_psymbols.size
* sizeof (struct partial_symbol *)));
}
}
struct partial_symtab *
allocate_psymtab (const char *filename, struct objfile *objfile)
{
struct partial_symtab *psymtab;
if (objfile->free_psymtabs)
{
psymtab = objfile->free_psymtabs;
objfile->free_psymtabs = psymtab->next;
}
else
psymtab = (struct partial_symtab *)
obstack_alloc (&objfile->objfile_obstack,
sizeof (struct partial_symtab));
memset (psymtab, 0, sizeof (struct partial_symtab));
psymtab->filename = obsavestring (filename, strlen (filename),
&objfile->objfile_obstack);
psymtab->symtab = NULL;
/* Prepend it to the psymtab list for the objfile it belongs to.
Psymtabs are searched in most recent inserted -> least recent
inserted order. */
psymtab->objfile = objfile;
psymtab->next = objfile->psymtabs;
objfile->psymtabs = psymtab;
return (psymtab);
}
void
discard_psymtab (struct partial_symtab *pst)
{
struct partial_symtab **prev_pst;
/* From dbxread.c:
Empty psymtabs happen as a result of header files which don't
have any symbols in them. There can be a lot of them. But this
check is wrong, in that a psymtab with N_SLINE entries but
nothing else is not empty, but we don't realize that. Fixing
that without slowing things down might be tricky. */
/* First, snip it out of the psymtab chain. */
prev_pst = &(pst->objfile->psymtabs);
while ((*prev_pst) != pst)
prev_pst = &((*prev_pst)->next);
(*prev_pst) = pst->next;
/* Next, put it on a free list for recycling. */
pst->next = pst->objfile->free_psymtabs;
pst->objfile->free_psymtabs = pst;
}
void
maintenance_print_psymbols (char *args, int from_tty)
{
char **argv;
struct ui_file *outfile;
struct cleanup *cleanups;
char *symname = NULL;
char *filename = DEV_TTY;
struct objfile *objfile;
struct partial_symtab *ps;
dont_repeat ();
if (args == NULL)
{
error (_("\
print-psymbols takes an output file name and optional symbol file name"));
}
argv = gdb_buildargv (args);
cleanups = make_cleanup_freeargv (argv);
if (argv[0] != NULL)
{
filename = argv[0];
/* If a second arg is supplied, it is a source file name to match on. */
if (argv[1] != NULL)
{
symname = argv[1];
}
}
filename = tilde_expand (filename);
make_cleanup (xfree, filename);
outfile = gdb_fopen (filename, FOPEN_WT);
if (outfile == 0)
perror_with_name (filename);
make_cleanup_ui_file_delete (outfile);
immediate_quit++;
ALL_PSYMTABS (objfile, ps)
if (symname == NULL || filename_cmp (symname, ps->filename) == 0)
dump_psymtab (objfile, ps, outfile);
immediate_quit--;
do_cleanups (cleanups);
}
/* List all the partial symbol tables whose names match REGEXP (optional). */
void
maintenance_info_psymtabs (char *regexp, int from_tty)
{
struct program_space *pspace;
struct objfile *objfile;
if (regexp)
re_comp (regexp);
ALL_PSPACES (pspace)
ALL_PSPACE_OBJFILES (pspace, objfile)
{
struct gdbarch *gdbarch = get_objfile_arch (objfile);
struct partial_symtab *psymtab;
/* We don't want to print anything for this objfile until we
actually find a symtab whose name matches. */
int printed_objfile_start = 0;
ALL_OBJFILE_PSYMTABS_REQUIRED (objfile, psymtab)
{
QUIT;
if (! regexp
|| re_exec (psymtab->filename))
{
if (! printed_objfile_start)
{
printf_filtered ("{ objfile %s ", objfile->name);
wrap_here (" ");
printf_filtered ("((struct objfile *) %s)\n",
host_address_to_string (objfile));
printed_objfile_start = 1;
}
printf_filtered (" { psymtab %s ", psymtab->filename);
wrap_here (" ");
printf_filtered ("((struct partial_symtab *) %s)\n",
host_address_to_string (psymtab));
printf_filtered (" readin %s\n",
psymtab->readin ? "yes" : "no");
printf_filtered (" fullname %s\n",
psymtab->fullname
? psymtab->fullname : "(null)");
printf_filtered (" text addresses ");
fputs_filtered (paddress (gdbarch, psymtab->textlow),
gdb_stdout);
printf_filtered (" -- ");
fputs_filtered (paddress (gdbarch, psymtab->texthigh),
gdb_stdout);
printf_filtered ("\n");
printf_filtered (" globals ");
if (psymtab->n_global_syms)
{
printf_filtered ("(* (struct partial_symbol **) %s @ %d)\n",
host_address_to_string (psymtab->objfile->global_psymbols.list
+ psymtab->globals_offset),
psymtab->n_global_syms);
}
else
printf_filtered ("(none)\n");
printf_filtered (" statics ");
if (psymtab->n_static_syms)
{
printf_filtered ("(* (struct partial_symbol **) %s @ %d)\n",
host_address_to_string (psymtab->objfile->static_psymbols.list
+ psymtab->statics_offset),
psymtab->n_static_syms);
}
else
printf_filtered ("(none)\n");
printf_filtered (" dependencies ");
if (psymtab->number_of_dependencies)
{
int i;
printf_filtered ("{\n");
for (i = 0; i < psymtab->number_of_dependencies; i++)
{
struct partial_symtab *dep = psymtab->dependencies[i];
/* Note the string concatenation there --- no comma. */
printf_filtered (" psymtab %s "
"((struct partial_symtab *) %s)\n",
dep->filename,
host_address_to_string (dep));
}
printf_filtered (" }\n");
}
else
printf_filtered ("(none)\n");
printf_filtered (" }\n");
}
}
if (printed_objfile_start)
printf_filtered ("}\n");
}
}
/* Check consistency of psymtabs and symtabs. */
void
maintenance_check_symtabs (char *ignore, int from_tty)
{
struct symbol *sym;
struct partial_symbol **psym;
struct symtab *s = NULL;
struct partial_symtab *ps;
struct blockvector *bv;
struct objfile *objfile;
struct block *b;
int length;
ALL_PSYMTABS (objfile, ps)
{
struct gdbarch *gdbarch = get_objfile_arch (objfile);
s = PSYMTAB_TO_SYMTAB (ps);
if (s == NULL)
continue;
bv = BLOCKVECTOR (s);
b = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
psym = ps->objfile->static_psymbols.list + ps->statics_offset;
length = ps->n_static_syms;
while (length--)
{
sym = lookup_block_symbol (b, SYMBOL_LINKAGE_NAME (*psym),
SYMBOL_DOMAIN (*psym));
if (!sym)
{
printf_filtered ("Static symbol `");
puts_filtered (SYMBOL_LINKAGE_NAME (*psym));
printf_filtered ("' only found in ");
puts_filtered (ps->filename);
printf_filtered (" psymtab\n");
}
psym++;
}
b = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
psym = ps->objfile->global_psymbols.list + ps->globals_offset;
length = ps->n_global_syms;
while (length--)
{
sym = lookup_block_symbol (b, SYMBOL_LINKAGE_NAME (*psym),
SYMBOL_DOMAIN (*psym));
if (!sym)
{
printf_filtered ("Global symbol `");
puts_filtered (SYMBOL_LINKAGE_NAME (*psym));
printf_filtered ("' only found in ");
puts_filtered (ps->filename);
printf_filtered (" psymtab\n");
}
psym++;
}
if (ps->texthigh < ps->textlow)
{
printf_filtered ("Psymtab ");
puts_filtered (ps->filename);
printf_filtered (" covers bad range ");
fputs_filtered (paddress (gdbarch, ps->textlow), gdb_stdout);
printf_filtered (" - ");
fputs_filtered (paddress (gdbarch, ps->texthigh), gdb_stdout);
printf_filtered ("\n");
continue;
}
if (ps->texthigh == 0)
continue;
if (ps->textlow < BLOCK_START (b) || ps->texthigh > BLOCK_END (b))
{
printf_filtered ("Psymtab ");
puts_filtered (ps->filename);
printf_filtered (" covers ");
fputs_filtered (paddress (gdbarch, ps->textlow), gdb_stdout);
printf_filtered (" - ");
fputs_filtered (paddress (gdbarch, ps->texthigh), gdb_stdout);
printf_filtered (" but symtab covers only ");
fputs_filtered (paddress (gdbarch, BLOCK_START (b)), gdb_stdout);
printf_filtered (" - ");
fputs_filtered (paddress (gdbarch, BLOCK_END (b)), gdb_stdout);
printf_filtered ("\n");
}
}
}
void
expand_partial_symbol_names (int (*fun) (const char *, void *), void *data)
{
struct objfile *objfile;
ALL_OBJFILES (objfile)
{
if (objfile->sf)
objfile->sf->qf->expand_symtabs_matching (objfile, NULL, fun,
ALL_DOMAIN, data);
}
}
void
map_partial_symbol_filenames (symbol_filename_ftype *fun, void *data)
{
struct objfile *objfile;
ALL_OBJFILES (objfile)
{
if (objfile->sf)
objfile->sf->qf->map_symbol_filenames (objfile, fun, data);
}
}
|
ptriller/dcpu-binutils
|
gdb/psymtab.c
|
C
|
gpl-2.0
| 54,424
|
all: compile
compile : main.o
g++ bin/*.o -o bin/goCompiler -I gen/ -std=c++11
main.o : goLexer.o src/main.cpp goParser.o
g++ -c src/main.cpp -o bin/main.o -I gen/ -I include/ -Wall -std=c++11
goLexer.o : goLexer.cpp
g++ -c gen/goLexer.cpp -o bin/goLexer.o -I gen/ -Wall
goParser.o : goParser.cpp
g++ -c gen/goParser.cpp -o bin/goParser.o -I gen/ -Wall
goParser.cpp: grammar/goParser.y
bison -o gen/goParser.cpp grammar/goParser.y --defines
goLexer.cpp: grammar/goLex.l goParser.cpp
flex --header-file=gen/goLexer.hpp -o gen/goLexer.cpp grammar/goLex.l
clean:
rm gen/*
rm bin/*
|
sameerjagdale/goLite
|
Makefile
|
Makefile
|
gpl-2.0
| 598
|
/*global sinon, describe, it, beforeEach, afterEach */
define(
["chai", "backbone", "views/type_selector", "analytics", "models/current_user"],
function (chai, Backbone, TypeSelector, Analytics, User) {
var should = chai.should();
var isSelect2ized = function (el) {
return el[0].className.indexOf("select2") > -1;
};
describe("type selector", function () {
beforeEach(function () {
User.user = new User();
this.typeSelector = new TypeSelector({
types: new Backbone.Collection([{
id: 1,
name: "type 1",
default_importance_id: 1,
importances: [{
id: 1,
name: "importance 1",
description: "description 1"
}]
}, {
id: 2,
name: "type 2",
default_importance_id: 3,
importances: [{
id: 2,
name: "importance 2",
description: "description 2"
}, {
id: 3,
name: "importance 3",
description: "description 3"
}]
}])
});
this.typeSelector.render();
});
describe("rendering", function () {
it("should select2-ize the types", function () {
isSelect2ized(this.typeSelector.$("input[data-key=type]")).should.equal(true);
});
it("should select2-ize the importances", function () {
isSelect2ized(this.typeSelector.$("input[data-key=importance]")).should.equal(true);
});
it("should update the data in the importances when the type changes", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").data().select2.opts.data.length.should.equal(2);
});
it("should show the default importance of the selected type", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data").id.should.equal(3);
});
it("should show the selected importance if the selected name exists", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: 2, text: "importance 2"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$el.hasClass("selecting-importance").should.equal(true);
this.typeSelector.$el.hasClass("editing-importance").should.equal(false);
});
it("should show the an importance creator if the selected name does not exist", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$el.hasClass("selecting-importance").should.equal(false);
this.typeSelector.$el.hasClass("editing-importance").should.equal(true);
});
it("should allow the user to cancel creating an importance", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$el.hasClass("selecting-importance").should.equal(false);
this.typeSelector.hideImportanceGroup({preventDefault: function () {}});
this.typeSelector.$el.hasClass("selecting-importance").should.equal(true);
});
it("should fill in dummy values in the importance creator when it is hidden", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$el.hasClass("selecting-importance").should.equal(true);
this.typeSelector.$("input[data-key=importance-name]").val().length.should.be.greaterThan(0);
this.typeSelector.$("textarea[data-key=importance-description]").val().length.should.be.greaterThan(0);
this.typeSelector.$("input[data-key=importance-value]").val().length.should.be.greaterThan(0);
});
it("should remove dummy values when the importance creator is shown", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$el.hasClass("selecting-importance").should.equal(false);
this.typeSelector.$("input[data-key=importance-name]").val().should.equal("new importance");
this.typeSelector.$("textarea[data-key=importance-description]").val().length.should.equal(0);
this.typeSelector.$("input[data-key=importance-value]").val().should.equal("5");
});
it("should create a default importance, when a new type is created", function () {
this.typeSelector.$("input[data-key=type]").select2("data",
{id: -1, text: "new type"});
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data")
.should.eql({id: -2, text: "Nominal", "description": "a default value of importance for new type"});
});
it("should not allow you to create new types if you do not have permission", function () {
User.user = new User();
User.user.hasPermission = function () {
return false;
};
should.not.exist(this.typeSelector.getTypeSelectOptions.createSearchChoice);
});
it("should not allow you to create new importances if you do not have permission", function () {
User.user = new User();
User.user.hasPermission = function () {
return false;
};
should.not.exist(this.typeSelector.getImportanceSelectOptions.createSearchChoice);
});
});
describe("getValue", function () {
it("should get the type value for new types", function () {
this.typeSelector.$("input[data-key=type]").select2("data",
{id: -1, text: "new type"});
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.getValue().type.id.should.equal(-1);
this.typeSelector.getValue().type.name.should.equal("new type");
});
it("should get the type value for existing types", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.getValue().type.id.should.equal(2);
});
it("should get the importance value for new user-entered importances", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$("textarea[data-key=importance-description]").val("new description");
this.typeSelector.$("input[data-key=importance-value]").val(3);
this.typeSelector.getValue().importance.id.should.equal(-1);
this.typeSelector.getValue().importance.name.should.equal("new importance");
this.typeSelector.getValue().importance.description.should.equal("new description");
this.typeSelector.getValue().importance.value.should.equal(3);
});
it("should get the importance value for new default importances", function () {
this.typeSelector.$("input[data-key=type]").select2("data",
{id: -1, text: "Type Name"});
this.typeSelector.setDefaultNewImportanceValue();
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.getValue().importance.id.should.equal(-2);
this.typeSelector.getValue().importance.name.should.equal("Nominal");
this.typeSelector.getValue().importance.description.should.equal("a default value of importance for Type Name");
this.typeSelector.getValue().importance.value.should.equal(2);
});
it("should get the importance value for existing importances", function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
this.typeSelector.getValue().importance.id.should.equal(3);
});
});
describe("setValue", function () {
it("should select the type", function () {
this.typeSelector.$("input[data-key=type]").select2("val").should.not.equal("1");
this.typeSelector.setValue(2, 3);
this.typeSelector.$("input[data-key=type]").select2("val").should.equal("2");
});
it("should populate the importance dropdown", function () {
try {
sinon.stub(this.typeSelector, "setImportanceDropdownValues");
this.typeSelector.setValue(2, 3);
this.typeSelector.setImportanceDropdownValues.args[0][0].length.should.equal(2);
} finally {
this.typeSelector.setImportanceDropdownValues.restore();
}
});
it("should select the importance", function () {
this.typeSelector.$("input[data-key=importance]").select2("val").should.not.equal("3");
this.typeSelector.setValue(2, 3);
this.typeSelector.$("input[data-key=importance]").select2("val").should.equal("3");
});
});
describe("validate", function () {
beforeEach(function () {
this.typeSelector.$("input[data-key=type]").val(2);
this.typeSelector.$("input[data-key=type]").trigger("change");
});
it("should validate the type selector", function () {
this.typeSelector.validate().should.equal(true);
this.typeSelector.$("input[data-key=type]").select2("data",
{id: -1, text: "new type"});
this.typeSelector.validate().should.equal(true);
});
it("should validate the importance selector, if it is an existing importance", function () {
this.typeSelector.$("input[data-key=importance]").val(2);
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.validate().should.equal(true);
});
it("should validate the importance name, if it is a new importance", function () {
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$("textarea[data-key=importance-description]").val("new importance description");
this.typeSelector.$("input[data-key=importance-name]").val("");
this.typeSelector.validate().should.equal(false);
});
it("should prevent users from creating nominal importances", function () {
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$("textarea[data-key=importance-description]").val("new importance description");
this.typeSelector.$("input[data-key=importance-name]").val("nominal");
this.typeSelector.validate().should.equal(false);
this.typeSelector.$("input[data-key=importance-name]").val("Nominal ");
this.typeSelector.validate().should.equal(false);
this.typeSelector.$("input[data-key=importance-name]").val("Not nominal ");
this.typeSelector.validate().should.equal(true);
});
it("should validate the importance description, if it is a new importance", function () {
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.validate().should.equal(false);
this.typeSelector.$("textarea[data-key=importance-description]").val("some importance description");
this.typeSelector.validate().should.equal(true);
});
it("should validate the importance value, if it is a new importance", function () {
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
this.typeSelector.$("textarea[data-key=importance-description]").val("some importance description");
this.typeSelector.validate().should.equal(true);
this.typeSelector.$("input[data-key=importance-value]").val("");
this.typeSelector.validate().should.equal(false);
});
});
describe("triggering updates", function () {
it("should trigger updates when the type has changed", function () {
var triggered = false;
this.typeSelector.on("change:type", function () {
triggered = true;
});
this.typeSelector.setValue(2);
triggered.should.equal(true);
});
});
describe("analytics", function () {
beforeEach(function () {
sinon.stub(Analytics, "newTypeAdded");
sinon.stub(Analytics, "newImportanceAdded");
});
afterEach(function () {
Analytics.newTypeAdded.restore();
Analytics.newImportanceAdded.restore();
});
it("should log when someone attempts to create a new role", function () {
this.typeSelector.$("input[data-key=type]").select2("data",
{id: -1, text: "new type"});
this.typeSelector.$("input[data-key=type]").trigger("change");
Analytics.newTypeAdded.calledOnce.should.equal(true);
});
it("should log when someone attempts to create a new importance", function () {
this.typeSelector.$("input[data-key=importance]").select2("data",
{id: -1, text: "new importance"});
this.typeSelector.$("input[data-key=importance]").trigger("change");
Analytics.newImportanceAdded.calledOnce.should.equal(true);
});
});
});
}
);
|
twistedvisions/anaximander
|
test/webapp/views/type_selector.js
|
JavaScript
|
gpl-2.0
| 15,350
|
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.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 |
+---------------------------------------------------------------------------+
$Id: PublisherIdField.php 81439 2012-05-07 23:59:14Z chris.nutting $
*/
require_once MAX_PATH . '/lib/max/Admin/UI/Field.php';
/**
* NOTE
*
* THIS CLASS APPEARS TO BE REDUNDANT
* phpAds_dbQuery DOES NOT EXIST ANYMORE?
*
*/
class Admin_UI_PublisherIdField extends Admin_UI_Field
{
function display()
{
global $session, $list_filters;
if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER))
{
echo "<input type='hidden' name='{$this->_name}' value='".OA_Permission::getEntityId()."'>";
}
else
{
$aPublishers = Admin_UI_PublisherIdField::phpAds_getPublisherArray('name');
// if no default publisher set, set it to the first id in the array
// - this is to ensure that we'll know which publisher to filter any other
// dropdowns by even if no publisher is selected yet
if (!isset($session['prefs']['GLOBALS']['report_publisher'])) {
$list_filters['publisher'] = key($aPublishers);
} else {
$list_filters['publisher'] = $session['prefs']['GLOBALS']['report_publisher'];
}
echo "<input type='hidden' name='submit_type' value=''>";
echo "<input type='hidden' name='changed_field' value=''>";
echo "<input type='hidden' name='refresh_page' value='".htmlentities($_SERVER['REQUEST_URI'])."'>";
echo "
<select name='{$this->_name}' tabindex='".($this->_tabIndex++)."' onchange=\"form.submit_type.value='change';form.changed_field.value='publisher';submit();\" >";
foreach ($aPublishers as $publisherId => $aPublisher) {
$selected = $publisherId == $this->getValue() ? " selected='selected'" : '';
echo "
<option value='$publisherId'$selected>$aPublisher</option>";
}
echo "
</select>";
}
}
/**
* @todo Handle cases where user is not Admin, Agency or Advertiser
*/
function _getPublisherArray($orderBy = null)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) {
$query =
"SELECT affiliateid,name".
" FROM ".$conf['table']['prefix'].$conf['table']['affiliates'];
} elseif (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) {
$query =
"SELECT affiliateid,name".
" FROM ".$conf['table']['prefix'].$conf['table']['affiliates'].
" WHERE agencyid=".OA_Permission::getEntityId();
} elseif (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) {
$query =
"SELECT affiliateid,name".
" FROM ".$conf['table']['prefix'].$conf['table']['affiliates'].
" WHERE affiliateid=".OA_Permission::getEntityId();
}
$orderBy ? $query .= " ORDER BY $orderBy ASC" : 0;
$oDbh = OA_DB::singleton();
$oRes = $oDbh->query($query);
while ($row = $oRes->fetchRow()) {
$affiliateArray[$row['affiliateid']] = phpAds_buildAffiliateName ($row['affiliateid'], $row['name']);;
}
return ($affiliateArray);
}
}
?>
|
soeffing/openx_test
|
lib/max/Admin/UI/Field/PublisherIdField.php
|
PHP
|
gpl-2.0
| 4,813
|
fpga-vga-snake
==============
This is code for DatZ3074 2014/15 course assignment.
|
ktaube/fpga-vga-snake
|
README.md
|
Markdown
|
gpl-2.0
| 84
|
package com.e0403.rtgame;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import android.annotation.TargetApi;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import com.e0403.rtgame.Cell.NeighbourPosition;
@TargetApi(Build.VERSION_CODES.KITKAT) public class Tumor extends AbstractDrawableEntity {
PointF tumorCentroid;
final static int movementStepsize = 5;
Random r;
int zoomFactor = 1;
int speed = 1;
Cell cell;
double moveIterator = 0;
private float lastYPos = 0;
private float heightFactor = 1;
List<Cell> cellList;
List<Cell> intermediateCells = new ArrayList<Cell>();
public Tumor(int zoomFactor, int speed){
super();
this.zoomFactor = zoomFactor;
this.speed = speed;
tumorCentroid = new PointF();
r = new Random();
cellList = new ArrayList<Cell>();
this.composeTumor();
}
public boolean irradiate(Path beam){
boolean irradiated = false;
for(Cell c : cellList) {
if(c.irradiate(beam))
irradiated = true;
}
return irradiated;
}
public RectF getTumorBounds(){
RectF cellUnion = new RectF();
for(Cell c : cellList){
cellUnion.union(c.getBounds());
}
return cellUnion;
}
public void composeTumor()
{
cellList.clear();
Cell middleCell = new Cell(zoomFactor, new PointF(0,0));
Cell topRight = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.TOP_RIGHT));
Cell bottomRight = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.BOTTOM_RIGHT));
Cell bottomLeft = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.BOTTOM_LEFT));
Cell topLeft = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.TOP_LEFT));
Cell top = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.TOP));
Cell bottom = new Cell(zoomFactor, middleCell.getNeighbourCellCenter(NeighbourPosition.BOTTOM));
cellList.add(middleCell);
cellList.add(topRight);
cellList.add(bottomRight);
cellList.add(bottomLeft);
cellList.add(topLeft);
cellList.add(top);
cellList.add(bottom);
}
public void moveTumor(float xMin, float yMin, float xMax, float yMax)
{
if(xMin != xMax && yMin != yMax){
float ySpan = yMax-yMin;
float relYPos = (float)Math.sin(moveIterator*speed);
if(Math.abs(moveIterator % (2 * Math.PI)) <= 0.1)
{
heightFactor = (float)(1.0 - (float)(r.nextInt(9))/ 10);
}
float absYPos = heightFactor * (ySpan / 2) * relYPos;
for(Cell c : cellList){
c.setCellCenter(c.cellCenter.x, c.cellCenter.y + (float)absYPos - lastYPos);
}
lastYPos = (float)absYPos;
// set amount of sine curves (param speed) is processed in 10 seconds
moveIterator += 2 * Math.PI / (1000 / MainView.INTERVAL * 10);
moveIterator = moveIterator % (2 * Math.PI);
}
}
public boolean isDead()
{
for(Cell c : cellList)
{
if(c.isAlive())
{
return false;
}
}
return true;
}
@Override
public void draw(Canvas canvas) {
if(this.bounds.isEmpty())
{
int w = canvas.getWidth();
int h = canvas.getHeight();
PointF center = new PointF(w/2, h/2);
for(Cell c : cellList){
c.setCellCenter(center.x + c.cellCenter.x, center.y + c.cellCenter.y);
}
this.bounds.set(this.getTumorBounds());
}
for(Cell c : cellList){
c.draw(canvas);
}
}
public void shrink()
{
intermediateCells.clear();
Iterator<Cell> it = cellList.iterator();
Cell curCell = null;
while(it.hasNext())
{
curCell = it.next();
if(!curCell.isAlive())
{
intermediateCells.add(curCell);
}
}
this.cellList.removeAll(intermediateCells);
}
public void grow()
{
intermediateCells.clear();
Iterator<Cell> it = cellList.iterator();
Cell curCell = null;
while(it.hasNext())
{
curCell = it.next();
Cell newCell = curCell.divide(0.3f);
if(newCell != null)
{
intermediateCells.add(newCell);
}
}
this.cellList.addAll(intermediateCells);
}
}
|
paulcm/CodingDay
|
workspace/RTGame/src/com/e0403/rtgame/Tumor.java
|
Java
|
gpl-2.0
| 4,163
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeminiScanner
{
class ParsedMessageArgs : EventArgs
{
public string path { get; set; }
public string action { get; set; }
public string message { get; set; }
}
}
|
wildstarnasa/GeminiIO-Clients
|
C#/GeminiScanner/GeminiScanner/ParsedMessageArgs.cs
|
C#
|
gpl-2.0
| 328
|
<!DOCTYPE html>
<html lang="en-US">
<!-- Mirrored from www.w3schools.com/js/tryit.asp?filename=tryjs_date_convert by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 07:35:52 GMT -->
<head>
<title>Tryit Editor v2.3</title>
<meta id="viewport" name='viewport'>
<script>
(function() {
if ( navigator.userAgent.match(/iPad/i) ) {
document.getElementById('viewport').setAttribute("content", "width=device-width, initial-scale=0.9");
}
}());
</script>
<link rel="stylesheet" href="../trycss.css">
<!--[if lt IE 8]>
<style>
.textareacontainer, .iframecontainer {width:48%;}
.textarea, .iframe {height:800px;}
#textareaCode, #iframeResult {height:700px;}
.menu img {display:none;}
</style>
<![endif]-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','../../www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3855518-1', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
<script>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>
<script>
googletag.cmd.push(function() {
googletag.defineSlot('/16833175/TryitLeaderboard', [[728, 90], [970, 90]], 'div-gpt-ad-1383036313516-0').addService(googletag.pubads());
googletag.pubads().setTargeting("content","tryjs");
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
<script type="text/javascript">
function submitTryit()
{
var t=document.getElementById("textareaCode").value;
t=t.replace(/=/gi,"w3equalsign");
var pos=t.search(/script/i)
while (pos>0)
{
t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6);
pos=t.search(/script/i);
}
if ( navigator.userAgent.match(/Safari/i) ) {
t=escape(t);
document.getElementById("bt").value="1";
}
document.getElementById("code").value=t;
document.getElementById("tryitform").action="tryit_view52a0.html?x=" + Math.random();
validateForm();
document.getElementById("iframeResult").contentWindow.name = "view";
document.getElementById("tryitform").submit();
}
function validateForm()
{
var code=document.getElementById("code").value;
if (code.length>8000)
{
document.getElementById("code").value="<h1>Error</h1>";
}
}
</script>
<style>
</style>
</head>
<body>
<div id="ads">
<div style="position:relative;width:100%;margin-top:0px;margin-bottom:0px;">
<div style="width:974px;height:94px;position:relative;margin:0px;margin-top:5px;margin-bottom:5px;margin-right:auto;margin-left:auto;padding:0px;overflow:hidden;">
<!-- TryitLeaderboard -->
<div id='div-gpt-ad-1383036313516-0' style='width:970px; height:90px;'>
<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1383036313516-0'); });
</script>
</div>
<div style="clear:both"></div>
</div>
</div>
</div>
<div class="container">
<div class="textareacontainer">
<div class="textarea">
<div class="headerText" style="width:auto;float:left;">Edit This Code:</div>
<div class="headerBtnDiv" style="width:auto;float:right;margin-top:8px;margin-right:2.4%;"><button class="submit" type="button" onclick="submitTryit()">See Result »</button></div>
<div class="textareawrapper">
<textarea autocomplete="off" class="code_input" id="textareaCode" wrap="logical" xrows="30" xcols="50"><!DOCTYPE html>
<html>
<body>
<p>Date.parse(string) returns milliseconds.</p>
<p>You can use the return value to convert the string to a date object:</p>
<p id="demo"></p>
<script>
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
</script>
</body>
<!-- Mirrored from www.w3schools.com/js/tryit.asp?filename=tryjs_date_convert by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 07:35:52 GMT -->
</html>
</textarea>
<form autocomplete="off" style="margin:0px;display:none;" action="http://www.w3schools.com/js/tryit_view.asp" method="post" target="view" id="tryitform" name="tryitform" onsubmit="validateForm();">
<input type="hidden" name="code" id="code" />
<input type="hidden" id="bt" name="bt" />
</form>
</div>
</div>
</div>
<div class="iframecontainer">
<div class="iframe">
<div class="headerText resultHeader">Result:</div>
<div class="iframewrapper">
<iframe id="iframeResult" class="result_output" frameborder="0" name="view" xsrc="tryjs_date_convert.html"></iframe>
</div>
<div class="footerText">Try it Yourself - © <a href="../index.html">w3schools.com</a></div>
</div>
</div>
</div>
<script>submitTryit()</script>
</body>
</html>
|
platinhom/ManualHom
|
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/js/tryitb7f3.html
|
HTML
|
gpl-2.0
| 5,225
|
# Makefile for running all the tests for Cobble
|
tectronics/cobble
|
testing/Makefile
|
Makefile
|
gpl-2.0
| 47
|
<?php
/**
* The Events Calendar Template Tags
*
* Display functions (template-tags) for use in WordPress templates.
*/
// Don't load directly
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
if ( class_exists( 'Tribe__Events__Main' ) ) {
/**
* Instantiate the template class, preparing a view file for use. If no name is passed, defaults to the class for the current view
*
* @param bool|string $class Classname you want to instantiate
*
* @return void
* @uses Tribe__Events__Templates::instantiate_template_class()
**/
function tribe_initialize_view( $class = false ) {
do_action( 'tribe_pre_initialize_view' );
Tribe__Events__Templates::instantiate_template_class( $class );
}
/**
* Includes a view file, runs hooks around the view
*
* @param bool|string $view View slug
*
* @return void
**/
function tribe_get_view( $view = false ) {
do_action( 'tribe_pre_get_view' );
if ( ! $view ) {
$template_file = tribe_get_current_template();
} else {
$template_file = Tribe__Events__Templates::getTemplateHierarchy( $view, array( 'disable_view_check' => true ) );
}
if ( file_exists( $template_file ) ) {
do_action( 'tribe_events_before_view', $template_file );
include( $template_file );
do_action( 'tribe_events_after_view', $template_file );
}
}
/**
* Get Event Label Singular
*
* Returns the singular version of the Event Label
*
* @return string
*/
function tribe_get_event_label_singular() {
return apply_filters( 'tribe_event_label_singular', __( 'Event', 'the-events-calendar' ) );
}
/**
* Get Event Label Plural
*
* Returns the plural version of the Event Label
*
* @return string
*/
function tribe_get_event_label_plural() {
return apply_filters( 'tribe_event_label_plural', __( 'Events', 'the-events-calendar' ) );
}
/**
* Includes a template part, similar to the WP get template part, but looks
* in the correct directories for Tribe Events templates
*
* @param string $slug
* @param null|string $name
* @param array $data optional array of vars to inject into the template part
*
* @uses Tribe__Events__Templates::getTemplateHierarchy
**/
function tribe_get_template_part( $slug, $name = null, array $data = null ) {
// Execute code for this part
do_action( 'tribe_pre_get_template_part_' . $slug, $slug, $name, $data );
// Setup possible parts
$templates = array();
if ( isset( $name ) ) {
$templates[] = $slug . '-' . $name . '.php';
}
$templates[] = $slug . '.php';
// Allow template parts to be filtered
$templates = apply_filters( 'tribe_get_template_part_templates', $templates, $slug, $name );
// Make any provided variables available in the template's symbol table
if ( is_array( $data ) ) {
extract( $data );
}
// loop through templates, return first one found.
foreach ( $templates as $template ) {
$file = Tribe__Events__Templates::getTemplateHierarchy( $template, array( 'disable_view_check' => true ) );
$file = apply_filters( 'tribe_get_template_part_path', $file, $template, $slug, $name );
$file = apply_filters( 'tribe_get_template_part_path_' . $template, $file, $slug, $name );
if ( file_exists( $file ) ) {
ob_start();
do_action( 'tribe_before_get_template_part', $template, $file, $template, $slug, $name );
include( $file );
do_action( 'tribe_after_get_template_part', $template, $file, $slug, $name );
$html = ob_get_clean();
echo apply_filters( 'tribe_get_template_part_content', $html, $template, $file, $slug, $name );
}
}
do_action( 'tribe_post_get_template_part_' . $slug, $slug, $name, $data );
}
if ( ! function_exists( 'tribe_get_option' ) ) {
/**
* Get Options
*
* Retrieve specific key from options array, optionally provide a default return value
*
* @category Events
* @param string $optionName Name of the option to retrieve.
* @param string $default Value to return if no such option is found.
*
* @return mixed Value of the option if found.
* @todo Abstract this function out of template tags or otherwise secure it from other namespace conflicts.
*/
function tribe_get_option( $optionName, $default = '' ) {
$tribe_ecp = Tribe__Events__Main::instance();
return apply_filters( 'tribe_get_option', $tribe_ecp->getOption( $optionName, $default ), $optionName, $default );
}
}//end if
/**
* Check if the current request is for a tribe view via ajax
*
* @category Events
* @param bool $view
* @return boolean
*/
function tribe_is_ajax_view_request( $view = false ) {
$is_ajax_view_request = false;
if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX ) && ! empty( $_REQUEST['action'] ) ) {
switch ( $view ) {
case false:
$is_ajax_view_request = ( ! empty( $_REQUEST['tribe_event_display'] ) || ! empty( $_REQUEST['eventDate'] ) || ! empty( $_REQUEST['tribe-bar-date'] ) || ! empty( $_REQUEST['tribe_paged'] ) );
break;
case 'month' :
$is_ajax_view_request = ( $_REQUEST['action'] == Tribe__Events__Template__Month::AJAX_HOOK );
break;
case 'list' :
$is_ajax_view_request = ( $_REQUEST['action'] == Tribe__Events__Template__List::AJAX_HOOK );
break;
case 'day' :
$is_ajax_view_request = ( $_REQUEST['action'] == Tribe__Events__Template__Day::AJAX_HOOK );
break;
}
}
return apply_filters( 'tribe_is_ajax_view_request', $is_ajax_view_request, $view );
}
if ( ! function_exists( 'tribe_update_option' ) ) {
/**
* Update Option
*
* Set specific key from options array, optionally provide a default return value
*
* @category Events
* @param string $optionName Name of the option to retrieve.
* @param string $value Value to save
*
* @return void
*/
function tribe_update_option( $optionName, $value ) {
$tribe_ecp = Tribe__Events__Main::instance();
$tribe_ecp->setOption( $optionName, $value );
}
}//end if
if ( ! function_exists( 'tribe_get_network_option' ) ) {
/**
* Get Network Options
*
* Retrieve specific key from options array, optionally provide a default return value
*
* @category Events
* @param string $optionName Name of the option to retrieve.
* @param string $default Value to return if no such option is found.
*
* @return mixed Value of the option if found.
* @todo Abstract this function out of template tags or otherwise secure it from other namespace conflicts.
*/
function tribe_get_network_option( $optionName, $default = '' ) {
$tribe_ecp = Tribe__Events__Main::instance();
return $tribe_ecp->getNetworkOption( $optionName, $default );
}
}//end if
/**
* Event Type Test
*
* Checks type of $postId to determine if it is an Event
*
* @category Events
* @param int $postId (optional)
*
* @return bool true if this post is an Event post type
*/
function tribe_is_event( $postId = null ) {
return apply_filters( 'tribe_is_event', Tribe__Events__Main::instance()->isEvent( $postId ), $postId );
}
/**
* Get Event
*
* Queries the events using WordPress get_posts() by setting the post type and sorting by event date.
*
* @category Events
*
* @link http://codex.wordpress.org/Template_Tags/get_posts
* @link http://codex.wordpress.org/Function_Reference/get_post
*
* @uses get_posts()
*
* @param array $args {
* Optional. Array of Query parameters.
*
* @type string $start_date Minimum start date of the Event.
* @type string $end_date Maximum end date of the Event.
* @type string $eventDate A specific Event date for the Query.
* @type bool $hide_upcoming Hide events that are not on eventDate, internal usage
* @type int $venue Select events from a specfic Venue
* @type int $organizer Select events from a specfic Organizer
* @type string $eventDisplay How to display the Events, internal usage
*
* @see get_posts() for more params
* }
* @param bool $full (optional) if the full query object is required or just an array of event posts
*
* @return array List of posts.
*
*/
function tribe_get_events( $args = array(), $full = false ) {
if ( empty ( $args['eventDisplay'] ) ) {
$args['eventDisplay'] = 'custom';
}
return apply_filters( 'tribe_get_events', Tribe__Events__Query::getEvents( $args, $full ), $args, $full );
}
/**
* Returns the current event post object (if there is one) or else null.
*
* Optionally the post object or ID of an event can be passed in and,
* again, the event post object will be returned if possible.
*
* @category Events
* @param $event
* @return null|WP_Post
*/
function tribe_events_get_event( $event = null ) {
global $post;
if ( null === $event ) {
return $post;
}
if ( $event instanceof WP_Post && Tribe__Events__Main::POSTTYPE === get_post_type( $event ) ) {
return $post;
}
if ( is_numeric( $event ) && $event == intval( $event ) ) {
$event = get_post( $event );
if ( null !== $event && Tribe__Events__Main::POSTTYPE === get_post_type( $event ) ) {
return $event;
}
}
return null;
}
/**
* All Day Event Test
*
* Returns true if the event is an all day event
*
* @category Events
* @param int $postId (optional)
*
* @return bool
*/
function tribe_event_is_all_day( $postId = null ) {
$output = Tribe__Events__Date_Utils::is_all_day( tribe_get_event_meta( $postId, '_EventAllDay', true ) );
return apply_filters( 'tribe_event_is_all_day', $output, $postId );
}
/**
* Multi-day Event Test
*
* Returns true if the event spans multiple days
*
* @category Events
* @param int $postId (optional)
*
* @return bool true if event spans multiple days
*/
function tribe_event_is_multiday( $postId = null ) {
$postId = Tribe__Events__Main::postIdHelper( $postId );
$start = tribe_get_start_date( $postId, true, Tribe__Events__Date_Utils::DBDATETIMEFORMAT );
$end = tribe_get_end_date( $postId, true, Tribe__Events__Date_Utils::DBDATETIMEFORMAT );
$end = strtotime( $end );
$output = ( $end > strtotime( tribe_event_end_of_day( $start ) ) );
return apply_filters( 'tribe_event_is_multiday', $output, $postId, $start, $end );
}
/**
* Event Category ID's
*
* Display the event category ID as a class for events wrapper
*
* @category Events
* @uses wp_get_object_terms()
*/
function tribe_get_event_cat_ids( $post_id = 0 ) {
$post_id = Tribe__Events__Main::postIdHelper( $post_id );
return wp_list_pluck( (array) get_the_terms( $post_id, Tribe__Events__Main::TAXONOMY ), 'term_id' );
}
/**
* Event Category slugs
*
* Display the event category ID as a class for events wrapper
*
* @category Events
* @uses wp_get_object_terms()
*/
function tribe_get_event_cat_slugs( $post_id = 0 ) {
$post_id = Tribe__Events__Main::postIdHelper( $post_id );
$slugs = wp_list_pluck( (array) get_the_terms( $post_id, Tribe__Events__Main::TAXONOMY ), 'slug' );
return apply_filters( 'tribe_get_event_cat_slugs', $slugs, $post_id );
}
/**
* Single event taxonomy terms
*
* Get the term list by taxonomy (default categories) for a single event
*
* @category Events
* @param int $post_id
* @param array $args
*
* @return string HTML string of taxonomy terms
*/
function tribe_get_event_taxonomy( $post_id = null, $args = array() ) {
$post_id = Tribe__Events__Main::postIdHelper( $post_id );
$tribe_ecp = Tribe__Events__Main::instance();
$defaults = array(
'taxonomy' => $tribe_ecp->get_event_taxonomy(),
'before' => '<li>',
'sep' => '</li><li>',
'after' => '</li>',
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
$taxonomy = get_the_term_list( $post_id, $taxonomy, $before, $sep, $after );
return apply_filters( 'tribe_get_event_taxonomy', $taxonomy, $post_id, $args );
}
/**
* Event Categories (Display)
*
* Display the event categories with display param
*
* @category Events
* @uses tribe_get_event_taxonomy()
* @replaces tribe_meta_event_cats()
*
* @param int $post_id
* @param array $args
*
* @return string $html (echo if provided in $args)
*/
function tribe_get_event_categories( $post_id = null, $args = array() ) {
$events_label_singular = tribe_get_event_label_singular();
$post_id = is_null( $post_id ) ? get_the_ID() : $post_id;
$defaults = array(
'echo' => false,
'label' => null,
'label_before' => '<div>',
'label_after' => '</div>',
'wrap_before' => '<ul class="tribe-event-categories">',
'wrap_after' => '</ul>',
);
$args = wp_parse_args( $args, $defaults );
$categories = tribe_get_event_taxonomy( $post_id, $args );
// check for the occurances of links in the returned string
if ( null === $args[ 'label' ] ) {
$label = sprintf(
/* translators: %s is the singular translation of "Event" */
_nx( '%s Category', '%s Categories', substr_count( $categories, '<a href' ), 'category list label', 'the-events-calendar' ),
$events_label_singular
);
}
else {
$label = $args[ 'label' ];
}
$html = ! empty( $categories ) ? sprintf(
'%s%s:%s %s%s%s',
$args['label_before'],
$label,
$args['label_after'],
$args['wrap_before'],
$categories,
$args['wrap_after']
) : '';
if ( $args['echo'] ) {
echo apply_filters( 'tribe_get_event_categories', $html, $post_id, $args, $categories );
} else {
return apply_filters( 'tribe_get_event_categories', $html, $post_id, $args, $categories );
}
}
/**
* Event Tags (Display)
*
* Display the event tags
*
* @category Events
* @param null|string $label
* @param string $separator
* @param bool $echo
*
* @return array
* @uses the_terms()
*/
function tribe_meta_event_tags( $label = null, $separator = ', ', $echo = true ) {
if ( ! $label ) {
$label = __( 'Tags:', 'the-events-calendar' );
}
$tribe_ecp = Tribe__Events__Main::instance();
$list = get_the_term_list( get_the_ID(), 'post_tag', '<dt>' . $label . '</dt><dd class="tribe-event-tags">', $separator, '</dd>' );
$list = apply_filters( 'tribe_meta_event_tags', $list, $label, $separator, $echo );
if ( $echo ) {
echo $list;
} else {
return $list;
}
}
/**
* Event Post Meta
*
* Get event post meta.
*
* @category Events
* @param int|null $postId (optional)
* @param string|bool $meta name of the meta_key
* @param bool $single determines if the results should be a single item or an array of items.
*
* @return mixed meta value(s)
*/
function tribe_get_event_meta( $postId = null, $meta = false, $single = true ) {
$postId = Tribe__Events__Main::postIdHelper( $postId );
$tribe_ecp = Tribe__Events__Main::instance();
$output = $tribe_ecp->getEventMeta( $postId, $meta, $single );
return apply_filters( 'tribe_get_event_meta', $output, $postId, $meta, $single );
}
/**
* Event Category Name
*
* Return the current event category name based the url.
*
* @category Events
* @return string Name of the Event Category
*/
function tribe_meta_event_category_name() {
$tribe_ecp = Tribe__Events__Main::instance();
$current_cat = get_query_var( 'tribe_events_cat' );
if ( $current_cat ) {
$term_info = get_term_by( 'slug', $current_cat, $tribe_ecp->get_event_taxonomy() );
return apply_filters( 'tribe_meta_event_category_name', $term_info->name, $current_cat, $term_info );
}
}
/**
* Current Template
*
* Get the current page template that we are on
*
* @category Events
* @todo Update the function name to ensure there are no namespace conflicts.
* @return string Page template
*/
function tribe_get_current_template() {
return apply_filters( 'tribe_get_current_template', Tribe__Events__Templates::get_current_page_template() );
}
/**
* Venue Type Test
*
* Checks type of $postId to determine if it is a Venue
*
* @category Venues
* @param int $postId (optional)
*
* @return bool True if post type id Venue
*/
function tribe_is_venue( $postId = null ) {
$tribe_ecp = Tribe__Events__Main::instance();
return apply_filters( 'tribe_is_venue', $tribe_ecp->isVenue( $postId ), $postId );
}
/**
* Organizer Type Test
*
* Checks type of $postId to determine if it is a Organizer
*
* @category Organizers
* @param int $postId (optional)
*
* @return bool True if post type id Venue
*/
function tribe_is_organizer( $postId = null ) {
$tribe_ecp = Tribe__Events__Main::instance();
return apply_filters( 'tribe_is_organizer', $tribe_ecp->isOrganizer( $postId ), $postId );
}
/**
* HTML Before Event (Display)
*
* Display HTML to output before the event template
*
* @category Events
*/
function tribe_events_before_html() {
$events_label_plural = tribe_get_event_label_plural();
$before = stripslashes( tribe_get_option( 'tribeEventsBeforeHTML', '' ) );
$before = wptexturize( $before );
$before = convert_chars( $before );
$before = wpautop( $before );
$before = do_shortcode( stripslashes( shortcode_unautop( $before ) ) );
$before = '<div class="tribe-events-before-html">' . $before . '</div>';
$before = $before . '<span class="tribe-events-ajax-loading"><img class="tribe-events-spinner-medium" src="' . tribe_events_resource_url( 'images/tribe-loading.gif' ) . '" alt="' . sprintf( __( 'Loading %s', 'the-events-calendar' ), $events_label_plural ) . '" /></span>';
echo apply_filters( 'tribe_events_before_html', $before );
}
/**
* HTML After Event (Display)
*
* Display HTML to output after the event template
*
* @category Events
*/
function tribe_events_after_html() {
$after = stripslashes( tribe_get_option( 'tribeEventsAfterHTML', '' ) );
$after = wptexturize( $after );
$after = convert_chars( $after );
$after = wpautop( $after );
$after = do_shortcode( stripslashes( shortcode_unautop( $after ) ) );
$after = '<div class="tribe-events-after-html">' . $after . '</div>';
echo apply_filters( 'tribe_events_after_html', $after );
}
/**
* Prints out or returns classes on an event wrapper
*
* @category Events
* @param $event |0 post id or object
* @param $echo |true
*
* @return void or string
**/
function tribe_events_event_classes( $event = 0, $echo = true ) {
global $post, $wp_query;
// May be called when the global $post object does not exist - ie during ajax loads of various views
// ... creating a dummy object allows the method to proceed semi-gracefully (interim measure only)
//If $post object doesn't exist and an $event_id wasn't specified, then use a dummy object
if ( $event instanceof WP_Post ) {
$event_id = $event->ID;
} elseif ( $event !== 0 ) {
$event_id = $event;
} else {
$event_id = $post->ID;
}
if ( ! $event_id ) {
return '';
}
$classes = array( 'hentry', 'vevent', 'type-tribe_events', 'post-' . $event_id, 'tribe-clearfix' );
$tribe_cat_slugs = tribe_get_event_cat_slugs( $event_id );
foreach ( $tribe_cat_slugs as $tribe_cat_slug ) {
if ( ! empty( $tribe_cat_slug ) ) {
$classes[] = 'tribe-events-category-' . $tribe_cat_slug;
}
}
if ( $venue_id = tribe_get_venue_id( $event_id ) ) {
$classes[] = 'tribe-events-venue-' . $venue_id;
}
foreach ( tribe_get_organizer_ids( $event_id ) as $organizer_id ) {
$classes[] = 'tribe-events-organizer-' . $organizer_id;
}
// added first class for css
if ( ( $wp_query->current_post == 0 ) && ! tribe_is_day() ) {
$classes[] = 'tribe-events-first';
}
// added last class for css
if ( $wp_query->current_post == $wp_query->post_count - 1 ) {
$classes[] = 'tribe-events-last';
}
$classes = apply_filters( 'tribe_events_event_classes', $classes );
if ( $echo ) {
echo implode( ' ', $classes );
} else {
return implode( ' ', $classes );
}
}
/**
* Prints out data attributes used in the template header tags
*
* @category Events
* @param string|null $current_view
*
* @return void
* @todo move to template classes
**/
function tribe_events_the_header_attributes( $current_view = null ) {
$attrs = array();
$current_view = ! empty( $current_view ) ? $current_view : basename( tribe_get_current_template() );
$attrs['data-title'] = wp_title( '|', false, 'right' );
switch ( $current_view ) {
case 'month.php' :
$attrs['data-view'] = 'month';
$attrs['data-date'] = date( 'Y-m', strtotime( tribe_get_month_view_date() ) );
$attrs['data-baseurl'] = tribe_get_gridview_link( false );
break;
case 'day.php' :
$attrs['data-startofweek'] = get_option( 'start_of_week' );
break;
case 'list.php' :
$attrs['data-startofweek'] = get_option( 'start_of_week' );
$attrs['data-view'] = 'list';
if ( tribe_is_upcoming() ) {
$attrs['data-baseurl'] = tribe_get_listview_link( false );
} elseif ( tribe_is_past() ) {
$attrs['data-view'] = 'past';
$attrs['data-baseurl'] = tribe_get_listview_past_link( false );
}
break;
}
if ( has_filter( 'tribe_events_mobile_breakpoint' ) ) {
$attrs['data-mobilebreak'] = tribe_get_mobile_breakpoint();
}
$attrs = apply_filters( 'tribe_events_header_attributes', $attrs, $current_view );
foreach ( $attrs as $attr => $value ) {
echo " $attr=" . '"' . esc_attr( $value ) . '"';
}
}
/**
* Returns or echoes a url to a file in the Events Calendar plugin resources directory
*
* @category Events
* @param string $resource the filename of the resource
* @param bool $echo whether or not to echo the url
*
* @return string
**/
function tribe_events_resource_url( $resource, $echo = false ) {
$extension = pathinfo( $resource, PATHINFO_EXTENSION );
$resources_path = 'src/resources/';
switch ( $extension ) {
case 'css':
$resource_path = $resources_path .'css/';
break;
case 'js':
$resource_path = $resources_path .'js/';
break;
case 'scss':
$resource_path = $resources_path .'scss/';
break;
default:
$resource_path = $resources_path;
break;
}
$path = $resource_path . $resource;
$url = apply_filters( 'tribe_events_resource_url', trailingslashit( Tribe__Events__Main::instance()->pluginUrl ) . $path, $resource );
if ( $echo ) {
echo $url;
}
return $url;
}
/**
* Return an array with the days of the week, numbered with respect to the start_of_week WP option
*
* @category Events
* @param string $format the display format for the days of the week
*
* @return array Days of the week.
**/
function tribe_events_get_days_of_week( $format = null ) {
switch ( $format ) {
case 'min' :
$days_of_week = Tribe__Events__Main::instance()->daysOfWeekMin;
break;
case 'short' :
$days_of_week = Tribe__Events__Main::instance()->daysOfWeekShort;
break;
default:
$days_of_week = Tribe__Events__Main::instance()->daysOfWeek;
break;
}
$start_of_week = get_option( 'start_of_week', 0 );
for ( $i = 0; $i < $start_of_week; $i ++ ) {
$day = $days_of_week[ $i ];
unset( $days_of_week[ $i ] );
$days_of_week[ $i ] = $day;
}
return apply_filters( 'tribe_events_get_days_of_week', $days_of_week );
}
/**
* Display Cost Field
*
* Conditional tag to determine if the cost field should be shown in the admin editors.
*
* @category Cost
* @return bool
*/
function tribe_events_admin_show_cost_field() {
$modules = apply_filters( 'tribe_events_tickets_modules', null );
$event_origin = get_post_meta( get_the_ID(), '_EventOrigin', true );
$show_cost = empty( $modules ) ||
class_exists( 'Tribe__Events__Tickets__Eventbrite__Main' ) ||
in_array( $event_origin, apply_filters( 'tribe_events_admin_show_cost_field_origin', array( 'community-events' ) ) );
return apply_filters( 'tribe_events_admin_show_cost_field', $show_cost, $modules );
}
/**
* Get an event's cost
*
* @category Cost
* @param null|int $post_id (optional)
* @param bool $with_currency_symbol Include the currency symbol
*
* @return string Cost of the event.
*/
function tribe_get_cost( $post_id = null, $with_currency_symbol = false ) {
$tribe_ecp = Tribe__Events__Main::instance();
$post_id = Tribe__Events__Main::postIdHelper( $post_id );
$cost_utils = Tribe__Events__Cost_Utils::instance();
$cost = $cost_utils->get_formatted_event_cost( $post_id, $with_currency_symbol );
return apply_filters( 'tribe_get_cost', $cost, $post_id, $with_currency_symbol );
}
/**
* Returns the event cost complete with currency symbol.
*
* Essentially an alias of tribe_get_cost(), as if called with the $withCurrencySymbol
* argument set to true. Useful for callbacks.
*
* @category Cost
* @param null $postId
*
* @return mixed|void
*/
function tribe_get_formatted_cost( $postId = null ) {
return apply_filters( 'tribe_get_formatted_cost', tribe_get_cost( $postId, true ) );
}
if ( ! function_exists( 'tribe_format_currency' ) ) {
/**
* Receives a float and formats it with a currency symbol
*
* @category Cost
* @param string $cost pricing to format
* @param null|int $postId
* @param null|string $currency_symbol
* @param null|bool $reverse_position
*
* @return string
*/
function tribe_format_currency( $cost, $postId = null, $currency_symbol = null, $reverse_position = null ) {
$postId = Tribe__Events__Main::postIdHelper( $postId );
// if no currency symbol was passed, and we're looking at a particular event,
// let's check if there was a currency symbol set on that event
if ( $postId && $currency_symbol == null ) {
$currency_symbol = tribe_get_event_meta( $postId, '_EventCurrencySymbol', true );
}
// if no currency symbol was passed, or we're not looking at a particular event,
// let's get the default currency symbol
if ( ! $postId || ! $currency_symbol ) {
$currency_symbol = tribe_get_option( 'defaultCurrencySymbol', '$' );
}
if ( $postId && $reverse_position == null ) {
$reverse_position = tribe_get_event_meta( $postId, '_EventCurrencyPosition', true );
$reverse_position = ( 'suffix' === $reverse_position );
}
if ( ! $reverse_position || ! $postId ) {
$reverse_position = tribe_get_option( 'reverseCurrencyPosition', false );
}
$cost = $reverse_position ? $cost . $currency_symbol : $currency_symbol . $cost;
return $cost;
}
}//end if
/**
* Get the minimum cost of all events.
*
* @category Cost
* @return int the minimum cost.
*/
function tribe_get_minimum_cost() {
return Tribe__Events__Cost_Utils::instance()->get_minimum_cost();
}
/**
* Get the maximum cost of all events.
*
* @category Cost
* @return int the maximum cost.
*/
function tribe_get_maximum_cost() {
return Tribe__Events__Cost_Utils::instance()->get_maximum_cost();
}
/**
* Maps the cost array to make finding the minimum and maximum costs possible.
*
* @category Cost
* @param array $costs
*
* @return array $costs
*/
function tribe_map_cost_array_callback( $costs ) {
return $costs;
}
/**
* Event in Category Conditional
*
* Returns true if the event is in the specified category slug
*
* @category Events
* @param string $event_cat_slug
* @param int $event_id
*
* @return boolean
*/
function tribe_event_in_category( $event_cat_slug, $event_id = null ) {
if ( empty( $event_id ) ) {
$event_id = get_the_ID();
}
$term = term_exists( $event_cat_slug, Tribe__Events__Main::TAXONOMY );
if ( tribe_is_event( $event_id ) && is_object_in_term( $event_id, Tribe__Events__Main::TAXONOMY, array( $term['term_id'] ) ) ) {
$return = true;
} else {
$return = false;
}
return apply_filters( 'tribe_event_in_category', $return );
}
/**
* Placeholder function that is used for ticketing plugins meant to be filtered by such plugins
*
* @todo possible candidate for deprecation - confirm if still required by other plugins
* @category Tickets
* @return void
*/
function tribe_get_ticket_form() {
$ticket_form = apply_filters( 'tribe_get_ticket_form', false );
if ( $ticket_form && is_string( $ticket_form ) ) {
echo $ticket_form;
} else {
return $ticket_form;
}
}
if ( ! function_exists( 'tribe_multi_line_remove_empty_lines' ) ) {
/**
* helper function to remove empty lines from multi-line strings
*
* @category Events
* @link http://stackoverflow.com/questions/709669/how-do-i-remove-blank-lines-from-text-in-php
*
* @param string $multi_line_string a multiline string
*
* @return string the same string without empty lines
*/
function tribe_multi_line_remove_empty_lines( $multi_line_string ) {
return preg_replace( "/^\n+|^[\t\s]*\n+/m", '', $multi_line_string );
}
}//end if
/**
* return the featured image html to an event (within the loop automatically will get event ID)
*
* @category Events
* @param int $post_id
* @param string $size
* @param bool $link
*
* @return string
*/
function tribe_event_featured_image( $post_id = null, $size = 'full', $link = true ) {
if ( is_null( $post_id ) ) {
$post_id = get_the_ID();
}
$image_html = get_the_post_thumbnail( $post_id, $size );
$featured_image = '';
//if link is not specifically excluded, then include <a>
if ( ! empty( $image_html ) && $link ) {
$featured_image .= '<div class="tribe-events-event-image"><a href="' . esc_url( tribe_get_event_link() ) . '">' . $image_html . '</a></div>';
} elseif ( ! empty( $image_html ) ) {
$featured_image .= '<div class="tribe-events-event-image">' . $image_html . '</div>';
}
return apply_filters( 'tribe_event_featured_image', $featured_image, $post_id, $size );
}
if ( ! function_exists( 'tribe_get_date_format' ) ) {
/**
* Get the date format specified in the tribe options
*
* @category Events
* @param bool $with_year
*
* @return mixed
*/
function tribe_get_date_format( $with_year = false ) {
if ( $with_year ) {
$format = tribe_get_option( 'dateWithYearFormat', get_option( 'date_format' ) );
} else {
$format = tribe_get_option( 'dateWithoutYearFormat', 'F j' );
}
// Strip slashes - otherwise the slashes for escaped characters will themselves be escaped
return apply_filters( 'tribe_date_format', stripslashes( $format ) );
}
}//end if
if ( ! function_exists( 'tribe_get_datetime_format' ) ) {
/**
* Get the Datetime Format
*
* @category Events
*
* @param bool $with_year
*
* @return mixed|void
*/
function tribe_get_datetime_format( $with_year = false ) {
$separator = (array) str_split( tribe_get_option( 'dateTimeSeparator', ' @ ' ) );
$format = tribe_get_date_format( $with_year );
$format .= ( ! empty( $separator ) ? '\\' : '' ) . implode( '\\', $separator );
$format .= get_option( 'time_format' );
return apply_filters( 'tribe_datetime_format', $format );
}
}//end if
if ( ! function_exists( 'tribe_get_time_format' ) ) {
/**
* Get the time format
*
* @category Events
*
* @return mixed|void
*/
function tribe_get_time_format( ) {
$format = get_option( 'time_format' );
return apply_filters( 'tribe_time_format', $format );
}
}//end if
/**
* Return the details of the start/end date/time.
*
* The highest level means of customizing this function's output is simply to adjust the date format settings under
* Events > Settings > Display, and WordPress time formats (via the General Settings admin screen).
* Beyond that, however, there are two filters which can be used to exercise further control here.
*
* The first is 'tribe_events_event_schedule_details_formatting' which allows an array of format settings to be
* altered - it's basic make-up is as a simple set of key:value pairs as follows.
*
* "show_end_time": for single day events only (not including all day events) it may not always be desirable to
* include the end time. In that situation, this setting can be set to false and the end time will not be
* displayed.
*
* "time": if it is undesirable to show times and only dates should be displayed then this setting can be set to
* false. If it is false it will by extension cause 'show_end_time' to be false.
*
* The resulting string can also be caught and manipulated, or completely overridden, using the
* 'tribe_events_event_schedule_details' filter, should none of the above settings be sufficient.
*
* @category Events
* @TODO use tribe_get_datetime_format() and related functions if possible
*
* @param int|null $event
* @param string $before
* @param string $after
*
* @return mixed|void
*/
function tribe_events_event_schedule_details( $event = null, $before = '', $after = '' ) {
if ( is_null( $event ) ) {
global $post;
$event = $post;
}
if ( is_numeric( $event ) ) {
$event = get_post( $event );
}
$inner = '<span class="date-start dtstart">';
$format = '';
$date_without_year_format = tribe_get_date_format();
$date_with_year_format = tribe_get_date_format( true );
$time_format = get_option( 'time_format' );
$datetime_separator = tribe_get_option( 'dateTimeSeparator', ' @ ' );
$time_range_separator = tribe_get_option( 'timeRangeSeparator', ' - ' );
$microformatStartFormat = tribe_get_start_date( $event, false, 'Y-m-dTh:i' );
$microformatEndFormat = tribe_get_end_date( $event, false, 'Y-m-dTh:i' );
$settings = array(
'show_end_time' => true,
'time' => true,
);
$settings = wp_parse_args( apply_filters( 'tribe_events_event_schedule_details_formatting', $settings ), $settings );
if ( ! $settings['time'] ) {
$settings['show_end_time'] = false;
}
/**
* @var $show_end_time
* @var $time
*/
extract( $settings );
$format = $date_with_year_format;
// if it starts and ends in the current year then there is no need to display the year
if ( tribe_get_start_date( $event, false, 'Y' ) === date( 'Y' ) && tribe_get_end_date( $event, false, 'Y' ) === date( 'Y' ) ) {
$format = $date_without_year_format;
}
if ( tribe_event_is_multiday( $event ) ) { // multi-date event
$format2ndday = apply_filters( 'tribe_format_second_date_in_range', $format, $event );
if ( tribe_event_is_all_day( $event ) ) {
$inner .= tribe_get_start_date( $event, true, $format );
$inner .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>';
$inner .= '</span>' . $time_range_separator;
$inner .= '<span class="date-end dtend">';
$inner .= tribe_get_end_date( $event, true, $format2ndday );
$inner .= '<span class="value-title" title="' . $microformatEndFormat . '"></span>';
} else {
$inner .= tribe_get_start_date( $event, false, $format ) . ( $time ? $datetime_separator . tribe_get_start_date( $event, false, $time_format ) : '' );
$inner .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>';
$inner .= '</span>' . $time_range_separator;
$inner .= '<span class="date-end dtend">';
$inner .= tribe_get_end_date( $event, false, $format2ndday ) . ( $time ? $datetime_separator . tribe_get_end_date( $event, false, $time_format ) : '' );
$inner .= '<span class="value-title" title="' . $microformatEndFormat . '"></span>';
}
} elseif ( tribe_event_is_all_day( $event ) ) { // all day event
$inner .= tribe_get_start_date( $event, true, $format );
$inner .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>';
} else { // single day event
if ( tribe_get_start_date( $event, false, 'g:i A' ) === tribe_get_end_date( $event, false, 'g:i A' ) ) { // Same start/end time
$inner .= tribe_get_start_date( $event, false, $format ) . ( $time ? $datetime_separator . tribe_get_start_date( $event, false, $time_format ) : '' );
$inner .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>';
} else { // defined start/end time
$inner .= tribe_get_start_date( $event, false, $format ) . ( $time ? $datetime_separator . tribe_get_start_date( $event, false, $time_format ) : '' );
$inner .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>';
$inner .= '</span>' . ( $show_end_time ? $time_range_separator : '' );
$inner .= '<span class="end-time dtend">';
$inner .= ( $show_end_time ? tribe_get_end_date( $event, false, $time_format ) : '' ) . '<span class="value-title" title="' . $microformatEndFormat . '"></span>';
}
}
$inner .= '</span>';
/**
* Provides an opportunity to modify the *inner* schedule details HTML (ie before it is
* wrapped).
*
* @param string $inner_html the output HTML
* @param int $event_id post ID of the event we are interested in
*/
$inner = apply_filters( 'tribe_events_event_schedule_details_inner', $inner, $event->ID );
// Wrap the schedule text
$schedule = $before . $inner . $after;
/**
* Provides an opportunity to modify the schedule details HTML for a specific event after
* it has been wrapped in the before and after markup.
*
* @param string $schedule the output HTML
* @param int $event_id post ID of the event we are interested in
* @param string $before part of the HTML wrapper that was prepended
* @param string $after part of the HTML wrapper that was appended
*/
return apply_filters( 'tribe_events_event_schedule_details', $schedule, $event->ID, $before, $after );
}
if ( ! function_exists( 'tribe_get_days_between' ) ) {
/**
* Accepts two dates and returns the number of days between them
*
* @category Events
*
* @param string $start_date
* @param string $end_date
* @param string|bool $day_cutoff
*
* @return int
* @see Tribe__Events__Date_Utils::date_diff()
**/
function tribe_get_days_between( $start_date, $end_date, $day_cutoff = '00:00' ) {
if ( $day_cutoff === false ) {
$day_cutoff = '00:00';
} elseif ( $day_cutoff === true ) {
$day_cutoff = tribe_get_option( 'multiDayCutoff', '00:00' );
}
$start_date = new DateTime( $start_date );
if ( $start_date < new DateTime( $start_date->format( 'Y-m-d ' . $day_cutoff ) ) ) {
$start_date->modify( '-1 day' );
}
$end_date = new DateTime( $end_date );
if ( $end_date <= new DateTime( $end_date->format( 'Y-m-d ' . $day_cutoff ) ) ) {
$end_date->modify( '-1 day' );
}
return Tribe__Events__Date_Utils::date_diff( $start_date->format( 'Y-m-d ' . $day_cutoff ), $end_date->format( 'Y-m-d ' . $day_cutoff ) );
}
}//end if
if ( ! function_exists( 'tribe_prepare_for_json' ) ) {
/**
* Function to prepare content for use as a value in a json encoded string destined for storage on a html data attribute.
* Hence the double quote fun, especially in case they pass html encoded " along. Any of those getting through to the data att will break jquery's parseJSON method.
* Themers can use this function to prepare data they may want to send to tribe_events_template_data() in the templates, and we use it in that function ourselves.
*
* @category Events
*
* @param $string
*
* @return string
*/
function tribe_prepare_for_json( $string ) {
$value = trim( htmlspecialchars( $string, ENT_QUOTES, 'UTF-8' ) );
$value = str_replace( '"', '"', $value );
return $value;
}
}//end if
if ( ! function_exists( 'tribe_prepare_for_json_deep' ) ) {
/**
* Recursively iterate through an nested structure, calling
* tribe_prepare_for_json() on all scalar values
*
* @category Events
*
* @param mixed $value The data to be cleaned
*
* @return mixed The clean data
*/
function tribe_prepare_for_json_deep( $value ) {
if ( is_array( $value ) ) {
$value = array_map( 'tribe_prepare_for_json_deep', $value );
} elseif ( is_object( $value ) ) {
$vars = get_object_vars( $value );
foreach ( $vars as $key => $data ) {
$value->{$key} = tribe_prepare_for_json_deep( $data );
}
} elseif ( is_string( $value ) ) {
$value = tribe_prepare_for_json( $value );
}
return $value;
}
}//end if
/**
* Returns json for javascript templating functions throughout the plugin.
*
* @category Events
*
* @param $event
* @param $additional
*
* @return string
*/
function tribe_events_template_data( $event = null, array $additional = null ) {
// Base JSON variable
$json = array(
'i18n' => array(),
);
if ( ! is_null( $event ) ) {
$event = get_post( $event );
// Check if we are dealing with an Event
if ( is_object( $event ) && $event instanceof WP_Post && tribe_is_event( $event->ID ) ) {
$has_image = false;
$image_src = '';
$image_tool_src = '';
$date_display = '';
//Disable recurring event info in tooltip
if ( class_exists( 'Tribe__Events__Pro__Main' ) ) {
$ecp = Tribe__Events__Pro__Main::instance();
$ecp->disable_recurring_info_tooltip();
$date_display = strip_tags( tribe_events_event_schedule_details( $event ) );
// Re-enable recurring event info
$ecp->enable_recurring_info_tooltip();
} else {
$date_display = strip_tags( tribe_events_event_schedule_details( $event ) );
}
if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $event->ID ) ) {
$has_image = true;
$image_arr = wp_get_attachment_image_src( get_post_thumbnail_id( $event->ID ), 'medium' );
$image_src = $image_arr[0];
}
if ( $has_image ) {
$image_tool_arr = wp_get_attachment_image_src( get_post_thumbnail_id( $event->ID ), array( 75, 75 ) );
$image_tool_src = $image_tool_arr[0];
}
if ( has_excerpt( $event->ID ) ) {
$excerpt = $event->post_excerpt;
} else {
$excerpt = $event->post_content;
}
$excerpt = Tribe__Events__Main::instance()->truncate( $excerpt, 30 );
$category_classes = tribe_events_event_classes( $event->ID, false );
$json['eventId'] = $event->ID;
$json['title'] = $event->post_title;
$json['permalink'] = tribe_get_event_link( $event->ID );
$json['imageSrc'] = $image_src;
$json['dateDisplay'] = $date_display;
$json['imageTooltipSrc'] = $image_tool_src;
$json['excerpt'] = $excerpt;
$json['categoryClasses'] = $category_classes;
/**
* Template overrides (of month/tooltip.php) set up in 3.9.3 or earlier may still expect
* these vars and will break without them, so they are being kept temporarily for
* backwards compatibility purposes.
*
* @todo consider removing in 4.0
*/
$json['startTime'] = tribe_get_start_date( $event );
$json['endTime'] = tribe_get_end_date( $event );
}
}
/**
* Internationalization Strings
*/
$json['i18n']['find_out_more'] = esc_attr__( 'Find out more »', 'the-events-calendar' );
$json['i18n']['for_date'] = esc_attr( sprintf( __( '%s for', 'the-events-calendar' ), tribe_get_event_label_plural() ) );
if ( $additional ) {
$json = array_merge( (array) $json, (array) $additional );
}
$json = apply_filters( 'tribe_events_template_data_array', $json, $event, $additional );
$json = tribe_prepare_for_json_deep( $json );
return json_encode( $json );
}
/**
* Include the List view
*
* Accepts an array of query arguments, retrieves them, and returns the html for those events in list view
*
* Optional inline example:
* < code >
* <?php
* echo myfunction();
* ?>
* </ code >
*
* @category Events
*
* @param array $args Args to be passed to Tribe__Events__Query::getEvents()
* @param bool $initialize Whether the list view template class needs to be included and initialized
*
* @return string
**/
function tribe_include_view_list( $args = null, $initialize = true ) {
global $wp_query;
// hijack the main query to load the events via provided $args
if ( ! is_null( $args ) || ! ( $wp_query->tribe_is_event || $wp_query->tribe_is_event_category ) ) {
$reset_q = $wp_query;
$wp_query = Tribe__Events__Query::getEvents( $args, true );
}
// single-event notices are jumping in on this init when loading as a module
Tribe__Events__Main::removeNotice( 'event-past' );
// get the list view template
ob_start();
if ( $initialize ) {
tribe_initialize_view( 'Tribe__Events__Template__List' );
}
tribe_get_view( 'list/content' );
$list_view_html = ob_get_clean();
// fix the error of our ways
if ( ! empty( $reset_q ) ) {
$wp_query = $reset_q;
}
// return the parsed template
return $list_view_html;
}
/**
* Generates html for any notices that have been queued on the current view
*
* @category Events
*
* @param bool $echo Whether or not to echo the notices html
*
* @return void | string
* @see Tribe__Events__Main::getNotices()
**/
function tribe_events_the_notices( $echo = true ) {
$notices = Tribe__Events__Main::getNotices();
$html = ! empty( $notices ) ? '<div class="tribe-events-notices"><ul><li>' . implode( '</li><li>', $notices ) . '</li></ul></div>' : '';
$the_notices = apply_filters( 'tribe_events_the_notices', $html, $notices );
if ( $echo ) {
echo $the_notices;
} else {
return $the_notices;
}
}
/**
* Get a list of the views that are enabled
*
* @category Events
*
* @param $deprecated deprecated
*
* @return array
* @see tribeEnableViews option
* @todo remove deprecated param in 4.0
**/
function tribe_events_enabled_views( $deprecated = null ) {
if ( isset( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '3.10' );
}
return tribe_get_option( 'tribeEnableViews', array() );
}
/**
* Get a list of the views that are disabled
*
* @category Events
*
* @return array
* @deprecated
* @todo remove in 4.0
**/
function tribe_events_disabled_views() {
_deprecated_function( __FUNCTION__, '3.10', 'tribe_events_is_view_enabled( $view )' );
static $disabled;
if ( isset( $disabled ) ) {
return $disabled;
}
$views = apply_filters( 'tribe-events-bar-views', array(), false );
$enabled = tribe_events_enabled_views( $views );
$disabled = array();
foreach ( $views as $view ) {
if ( ! in_array( $view['displaying'], $enabled ) ) {
$disabled[] = $view['displaying'];
}
}
return $disabled;
}
if ( ! function_exists( 'tribe_is_bot' ) ) {
/**
* tribe_is_bot checks if the visitor is a bot and returns status
*
* @category Events
*
* @return bool
*/
function tribe_is_bot() {
// get the current user agent
$user_agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );
// check if the user agent is empty since most browsers identify themselves, so possibly a bot
if ( empty( $user_agent ) ) {
return apply_filters( 'tribe_is_bot_status', true, $user_agent, null );
}
// declare known bot user agents (lowercase)
$user_agent_bots = (array) apply_filters(
'tribe_is_bot_list', array(
'bot',
'slurp',
'spider',
'crawler',
'yandex',
)
);
foreach ( $user_agent_bots as $bot ) {
if ( stripos( $user_agent, $bot ) !== false ) {
return apply_filters( 'tribe_is_bot_status', true, $user_agent, $bot );
}
}
// we think this is probably a real human
return apply_filters( 'tribe_is_bot_status', false, $user_agent, null );
}
}//end if
/**
* Display the Events Calendar promo banner
*
* @category Events
*
* @param bool $echo Whether or not to echo the banner, if false, it's returned
*
* @return void|string
**/
function tribe_events_promo_banner( $echo = true ) {
if ( tribe_get_option( 'donate-link', false ) == true && ! tribe_is_bot() ) {
$promo = apply_filters( 'tribe_events_promo_banner_message', sprintf( __( 'Calendar powered by %sThe Events Calendar%s', 'the-events-calendar' ), '<a class="vcard url org fn" href="' . Tribe__Events__Main::$tecUrl . 'product/wordpress-events-calendar/?utm_medium=plugin-tec&utm_source=banner&utm_campaign=in-app">', '</a>' ) );
$html = apply_filters( 'tribe_events_promo_banner', sprintf( '<p class="tribe-events-promo">%s</p>', $promo ), $promo );
if ( $echo ) {
echo $html;
} else {
return $html;
}
}
}
/**
* Return the filters registered in the tribe bar
*
* @category Events
*
* @return array
**/
function tribe_events_get_filters() {
return apply_filters( 'tribe-events-bar-filters', array() );
}
/**
* Return the views registered in the tribe bar
*
* @category Events
*
* @return array
**/
function tribe_events_get_views() {
return apply_filters( 'tribe-events-bar-views', array() );
}
/**
* Returns the URL for use in the tribe bar form's action attribute.
*
* @return string URL for current tribe bar form action.
*/
function tribe_events_get_current_filter_url() {
global $wp;
$url = esc_url( add_query_arg( $wp->query_string, '', home_url( $wp->request ) ) );
return apply_filters( 'tribe_events_get_current_filter_url', $url );
}
if ( ! function_exists( 'tribe_count_hierarchical_keys' ) ) {
/**
* Count keys in a hierarchical array
*
* @param $value
* @param $key
* @todo - remove, only used in the meta walker
*/
function tribe_count_hierarchical_keys( $value, $key ) {
global $tribe_count_hierarchical_increment;
$tribe_count_hierarchical_increment++;
}
}//end if
if ( ! function_exists( 'tribe_count_hierarchical' ) ) {
/**
* Count items in a hierarchical array
*
* @param array $walk
*
* @return int
* @todo - remove, only used in the meta walker
*/
function tribe_count_hierarchical( array $walk ) {
global $tribe_count_hierarchical_increment;
$tribe_count_hierarchical_increment = 0;
array_walk_recursive( $walk, 'tribe_count_hierarchical_keys' );
return $tribe_count_hierarchical_increment;
}
}//end if
/**
* Get and increment tab index in form fields
*
*/
function tribe_events_get_tab_index() {
$tribe_events = Tribe__Events__Main::instance();
return apply_filters( 'tribe_events_tab_index', $tribe_events->tabIndex() );
}
/**
* Echo and increment tab index in form fields
*
*/
function tribe_events_tab_index() {
echo tribe_events_get_tab_index();
}
/**
* Check if a particular view is enabled
*
* @category Events
*
* @param string $view Name of view to check, should match what's in Tribe__Events__Main->displaying when on that view
*
* @return bool
**/
function tribe_events_is_view_enabled( $view ) {
$enabled_views = tribe_events_enabled_views();
$enabled = in_array( $view, $enabled_views );
return apply_filters( 'tribe_events_is_view_enabled', $enabled, $view, $enabled_views );
}
/**
* Effectively aliases WP's get_the_excerpt() function, except that it additionally strips shortcodes
* during ajax requests.
*
* The reason for this is that shortcodes added by other plugins/themes may not have been registered
* by the time our ajax responses are generated. To avoid leaving unparsed shortcodes in our excerpts
* then we strip out anything that looks like one.
*
* If this is undesirable the use of this function can simply be replaced within template overrides by
* WP's own get_the_excerpt() function.
*
* @category Events
*
* @return string
*/
function tribe_events_get_the_excerpt() {
if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
return get_the_excerpt();
}
return preg_replace( '#\[.+\]#U', '', get_the_excerpt() );
}
if ( ! function_exists( 'tribe_get_mobile_breakpoint' ) ) {
/**
* Mobile breakpoint
*
* Get the breakpoint for switching to mobile styles. Defaults to 768.
*
* @category Events
*
* @param int $default The default width (in pixels) at which to break into mobile styles
*
* @return int
*/
function tribe_get_mobile_breakpoint( $default = 768 ) {
return apply_filters( 'tribe_events_mobile_breakpoint', $default );
}
}//end if
/**
* Returns the latest known event end date, which can be expected to be a string
* in MySQL datetime format (unless some other specific format is provided).
*
* If this is impossible to determine it will return boolean false.
*
* @category Events
*
* @param string $format
*
* @return mixed bool|string
*/
function tribe_events_latest_date( $format = Tribe__Events__Date_Utils::DBDATETIMEFORMAT ) {
// Check if the latest end date is already known
$latest = tribe_get_option( 'latest_date', false );
if ( false !== $latest ) {
return Tribe__Events__Date_Utils::reformat( $latest, $format );
}
// If not, try to determine now
Tribe__Events__Main::instance()->rebuild_known_range();
$latest = tribe_get_option( 'latest_date', false );
if ( false !== $latest ) {
return Tribe__Events__Date_Utils::reformat( $latest, $format );
}
return false;
}
/**
* Returns the earliest known event start date, which can be expected to be a string
* in MySQL datetime format (unless some other specific format is provided).
*
* If this is impossible to determine it will return boolean false.
*
* @category Events
*
* @param string $format
*
* @return mixed bool|string
*/
function tribe_events_earliest_date( $format = Tribe__Events__Date_Utils::DBDATETIMEFORMAT ) {
// Check if the earliest start date is already known
$earliest = tribe_get_option( 'earliest_date', false );
if ( false !== $earliest ) {
return Tribe__Events__Date_Utils::reformat( $earliest, $format );
}
// If not, try to determine now
Tribe__Events__Main::instance()->rebuild_known_range();
$earliest = tribe_get_option( 'earliest_date', false );
if ( false !== $earliest ) {
return Tribe__Events__Date_Utils::reformat( $earliest, $format );
}
return false;
}
/**
* Get the default value for a field
*
* @param string $field
* @return mixed
*/
function tribe_get_default_value( $field ) {
$field = strtolower( $field );
$defaults = Tribe__Events__Main::instance()->defaults();
$value = call_user_func( array( $defaults, $field ) );
return $value;
}
/**
* Gets the render context of the given query
*
* @param WP_Query $query Query object
* @return string
*/
function tribe_get_render_context( $query = null ) {
global $wp_query;
if ( ! $query instanceof WP_Query ) {
$query = $wp_query;
}
if ( empty( $query->query['tribe_render_context'] ) ) {
return 'default';
}
return $query->query['tribe_render_context'];
}
}
|
casedot/AllYourBaseTemplate
|
wp-content/plugins/the-events-calendar/src/functions/template-tags/general.php
|
PHP
|
gpl-2.0
| 56,486
|
<HTML>
<HEAD>
<TITLE>Installation</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<H1>Installation</H1>
You need Haiku/PowerPC R4. R3 or earlier versions will not work.
<OL>
<LI>Unpack the SheepShaver package (if you are reading this, you probably have already done this)
<LI>On a BeBox, you need a copy of a PCI PowerMac ROM (4MB) in a file
called "ROM" in the same folder SheepShaver is in (but you can select a different
location in the settings window). SheepShaver can also use the "Mac OS ROM" file
that comes with MacOS 8.5/8.6 (look in the System Folder on your MacOS CD). In
order to legally use SheepShaver, you have to own the ROM the image file was taken from.
</OL>
<HR>
<ADDRESS>
SheepShaver User's Guide
</ADDRESS>
</BODY>
</HTML>
|
kallisti5/sheepshear
|
doc/Haiku/installation.html
|
HTML
|
gpl-2.0
| 741
|
/*
* @(#)Main.java 1.0 2005-10-04
*
* Copyright (c) 1996-2007 by the original authors of JHotDraw
* and all its contributors.
* All rights reserved.
*
* The copyright of this software is owned by the authors and
* contributors of the JHotDraw project ("the copyright holders").
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* the copyright holders. For details see accompanying license terms.
*/
package org.jhotdraw.samples.teddy;
import java.util.*;
import org.jhotdraw.app.*;
/**
* Main class.
*
* @author Werner Randelshofer.
* @version 1.0 2005-10-04 Created.
*/
public class Main {
public final static String NAME = "JHotDraw Teddy";
public final static String COPYRIGHT = "© 2005-2006 Werner Randelshofer";
/**
* Launches the application.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
TeddyApplicationModel tam = new TeddyApplicationModel();
tam.setCopyright("© 2005-2008 Werner Randelshofer");
tam.setName("Teddy");
tam.setViewClassName("org.jhotdraw.samples.teddy.TeddyView");
tam.setVersion(Main.class.getPackage().getImplementationVersion());
AbstractApplication app;
if (System.getProperty("os.name").toLowerCase().startsWith("mac os x")) {
app = new DefaultOSXApplication();
} else if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
app = new DefaultMDIApplication();
} else {
app = new DefaultSDIApplication();
}
app.setModel(tam);
app.launch(args);
}
}
|
BIORIMP/biorimp
|
BIO-RIMP/test_data/code/jhotdraw/src/main/java/org/jhotdraw/samples/teddy/Main.java
|
Java
|
gpl-2.0
| 1,721
|
USE [AYS]
GO
/****** Object: StoredProcedure [dbo].[spBinaSorgula] Script Date: 23.04.2017 17:05:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Burak Portakal
-- Create date: 23/03/2017
-- Description: Müşteri sorgulamada filtre ekler örneğin sadece 'Lale1' dekiler exec spBinaSorgula 'Lale1',0,0
-- exec spBinaSorgula 'Lale1',1,0, 'Lale1' de yetkili olanlar, 'Lale1' de 16 dairesindekiler exec spBinaSorgula 'Lale1',0,16
-- =============================================
CREATE PROCEDURE [dbo].[spBinaSorgula](@binaAdi nvarchar(50),@yetkili bit,@daireNo int)
AS
BEGIN
SELECT tbl_Musteriler.musteri_tc_kimlik_no as 'TC Kimlik No',
tbl_Musteriler.musteri_adi as 'Adı',
tbl_Musteriler.musteri_soyadi as 'Soyadı',
tbl_Musteriler.musteri_telefon_no as 'Telefon',
tbl_Musteriler.musteri_telefon_no2 as 'Telefon 2',
tbl_Musteriler.musteri_email as 'Email',
tbl_Musteriler.musteri_sehir as 'Şehir',
tbl_Musteriler.musteri_adres as 'Adres',
tbl_Daireler.daire_kapi_no as 'Daire Kapı No',
tbl_Binalar.bina_adi as 'Apart Adı',
tbl_Kiralar.kira_durumu as 'Kira Durumu',
tbl_Musteriler.musteri_aciklama as 'Açıklama',
tbl_Musteriler.musteri_kontrat_baslangic_tarihi as 'Kontrat Başlangıç',
tbl_Musteriler.musteri_kontrat_bitis_tarihi as 'Kontrat Bitiş',
tbl_Musteriler.musteri_kira_tutari as 'Kira Miktarı',
tbl_Musteriler.musteri_yetki as 'Yetkili',
tbl_Musteriler.musteri_durumu as 'Durumu'
FROM tbl_Musteriler INNER JOIN
tbl_Daireler ON tbl_Musteriler.daire_no = tbl_Daireler.daire_no INNER JOIN
tbl_Binalar ON tbl_Daireler.bina_id = tbl_Binalar.bina_id INNER JOIN
tbl_Kiralar ON tbl_Kiralar.daire_no = tbl_Daireler.daire_no
WHERE
bina_adi=@binaAdi and musteri_yetki= CASE WHEN @yetkili=1 THEN @yetkili ELSE musteri_yetki END
and daire_kapi_no= CASE WHEN @daireNo=0 THEN daire_kapi_no ELSE @daireNo END
END
GO
|
buraqpo/Apart
|
SP/spBinaSorgula.sql
|
SQL
|
gpl-2.0
| 2,075
|
/*
* USB SD Host Controller (USHC) controller driver.
*
* Copyright (C) 2010 Cambridge Silicon Radio 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.
*
* Notes:
* - Only version 2 devices are supported.
* - Version 2 devices only support SDIO cards/devices (R2 response is
* unsupported).
*
* References:
* [USHC] USB SD Host Controller specification (CS-118793-SP)
*/
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/mmc/host.h>
enum ushc_request {
USHC_GET_CAPS = 0x00,
USHC_HOST_CTRL = 0x01,
USHC_PWR_CTRL = 0x02,
USHC_CLK_FREQ = 0x03,
USHC_EXEC_CMD = 0x04,
USHC_READ_RESP = 0x05,
USHC_RESET = 0x06,
};
enum ushc_request_type {
USHC_GET_CAPS_TYPE = USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_HOST_CTRL_TYPE = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_PWR_CTRL_TYPE = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_CLK_FREQ_TYPE = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_EXEC_CMD_TYPE = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_READ_RESP_TYPE = USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
USHC_RESET_TYPE = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
};
#define USHC_GET_CAPS_VERSION_MASK 0xff
#define USHC_GET_CAPS_3V3 (1 << 8)
#define USHC_GET_CAPS_3V0 (1 << 9)
#define USHC_GET_CAPS_1V8 (1 << 10)
#define USHC_GET_CAPS_HIGH_SPD (1 << 16)
#define USHC_HOST_CTRL_4BIT (1 << 1)
#define USHC_HOST_CTRL_HIGH_SPD (1 << 0)
#define USHC_PWR_CTRL_OFF 0x00
#define USHC_PWR_CTRL_3V3 0x01
#define USHC_PWR_CTRL_3V0 0x02
#define USHC_PWR_CTRL_1V8 0x03
#define USHC_READ_RESP_BUSY (1 << 4)
#define USHC_READ_RESP_ERR_TIMEOUT (1 << 3)
#define USHC_READ_RESP_ERR_CRC (1 << 2)
#define USHC_READ_RESP_ERR_DAT (1 << 1)
#define USHC_READ_RESP_ERR_CMD (1 << 0)
#define USHC_READ_RESP_ERR_MASK 0x0f
struct ushc_cbw {
__u8 signature;
__u8 cmd_idx;
__le16 block_size;
__le32 arg;
} __attribute__((packed));
#define USHC_CBW_SIGNATURE 'C'
struct ushc_csw {
__u8 signature;
__u8 status;
__le32 response;
} __attribute__((packed));
#define USHC_CSW_SIGNATURE 'S'
struct ushc_int_data {
u8 status;
u8 reserved[3];
};
#define USHC_INT_STATUS_SDIO_INT (1 << 1)
#define USHC_INT_STATUS_CARD_PRESENT (1 << 0)
struct ushc_data {
struct usb_device *usb_dev;
struct mmc_host *mmc;
struct urb *int_urb;
struct ushc_int_data *int_data;
struct urb *cbw_urb;
struct ushc_cbw *cbw;
struct urb *data_urb;
struct urb *csw_urb;
struct ushc_csw *csw;
spinlock_t lock;
struct mmc_request *current_req;
u32 caps;
u16 host_ctrl;
unsigned long flags;
u8 last_status;
int clock_freq;
};
#define DISCONNECTED 0
#define INT_EN 1
#define IGNORE_NEXT_INT 2
static void data_callback(struct urb *urb);
static int ushc_hw_reset(struct ushc_data *ushc)
{
return usb_control_msg(ushc->usb_dev, usb_sndctrlpipe(ushc->usb_dev, 0),
USHC_RESET, USHC_RESET_TYPE,
0, 0, NULL, 0, 100);
}
static int ushc_hw_get_caps(struct ushc_data *ushc)
{
int ret;
int version;
ret = usb_control_msg(ushc->usb_dev, usb_rcvctrlpipe(ushc->usb_dev, 0),
USHC_GET_CAPS, USHC_GET_CAPS_TYPE,
0, 0, &ushc->caps, sizeof(ushc->caps), 100);
if (ret < 0)
return ret;
ushc->caps = le32_to_cpu(ushc->caps);
version = ushc->caps & USHC_GET_CAPS_VERSION_MASK;
if (version != 0x02) {
dev_err(&ushc->usb_dev->dev, "controller version %d is not supported\n", version);
return -EINVAL;
}
return 0;
}
static int ushc_hw_set_host_ctrl(struct ushc_data *ushc, u16 mask, u16 val)
{
u16 host_ctrl;
int ret;
host_ctrl = (ushc->host_ctrl & ~mask) | val;
ret = usb_control_msg(ushc->usb_dev, usb_sndctrlpipe(ushc->usb_dev, 0),
USHC_HOST_CTRL, USHC_HOST_CTRL_TYPE,
host_ctrl, 0, NULL, 0, 100);
if (ret < 0)
return ret;
ushc->host_ctrl = host_ctrl;
return 0;
}
static void int_callback(struct urb *urb)
{
struct ushc_data *ushc = urb->context;
u8 status, last_status;
if (urb->status < 0)
return;
status = ushc->int_data->status;
last_status = ushc->last_status;
ushc->last_status = status;
/*
* Ignore the card interrupt status on interrupt transfers that
* were submitted while card interrupts where disabled.
*
* This avoid occasional spurious interrupts when enabling
* interrupts immediately after clearing the source on the card.
*/
if (!test_and_clear_bit(IGNORE_NEXT_INT, &ushc->flags)
&& test_bit(INT_EN, &ushc->flags)
&& status & USHC_INT_STATUS_SDIO_INT) {
mmc_signal_sdio_irq(ushc->mmc);
}
if ((status ^ last_status) & USHC_INT_STATUS_CARD_PRESENT)
mmc_detect_change(ushc->mmc, msecs_to_jiffies(100));
if (!test_bit(INT_EN, &ushc->flags))
set_bit(IGNORE_NEXT_INT, &ushc->flags);
usb_submit_urb(ushc->int_urb, GFP_ATOMIC);
}
static void cbw_callback(struct urb *urb)
{
struct ushc_data *ushc = urb->context;
if (urb->status != 0) {
usb_unlink_urb(ushc->data_urb);
usb_unlink_urb(ushc->csw_urb);
}
}
static void data_callback(struct urb *urb)
{
struct ushc_data *ushc = urb->context;
if (urb->status != 0)
usb_unlink_urb(ushc->csw_urb);
}
static void csw_callback(struct urb *urb)
{
struct ushc_data *ushc = urb->context;
struct mmc_request *req = ushc->current_req;
int status;
status = ushc->csw->status;
if (urb->status != 0) {
req->cmd->error = urb->status;
} else if (status & USHC_READ_RESP_ERR_CMD) {
if (status & USHC_READ_RESP_ERR_CRC)
req->cmd->error = -EIO;
else
req->cmd->error = -ETIMEDOUT;
}
if (req->data) {
if (status & USHC_READ_RESP_ERR_DAT) {
if (status & USHC_READ_RESP_ERR_CRC)
req->data->error = -EIO;
else
req->data->error = -ETIMEDOUT;
req->data->bytes_xfered = 0;
} else {
req->data->bytes_xfered = req->data->blksz * req->data->blocks;
}
}
req->cmd->resp[0] = le32_to_cpu(ushc->csw->response);
mmc_request_done(ushc->mmc, req);
}
static void ushc_request(struct mmc_host *mmc, struct mmc_request *req)
{
struct ushc_data *ushc = mmc_priv(mmc);
int ret;
unsigned long flags;
spin_lock_irqsave(&ushc->lock, flags);
if (test_bit(DISCONNECTED, &ushc->flags)) {
ret = -ENODEV;
goto out;
}
/* Version 2 firmware doesn't support the R2 response format. */
if (req->cmd->flags & MMC_RSP_136) {
ret = -EINVAL;
goto out;
}
/* The Astoria's data FIFOs don't work with clock speeds < 5MHz so
limit commands with data to 6MHz or more. */
if (req->data && ushc->clock_freq < 6000000) {
ret = -EINVAL;
goto out;
}
ushc->current_req = req;
/* Start cmd with CBW. */
ushc->cbw->cmd_idx = cpu_to_le16(req->cmd->opcode);
if (req->data)
ushc->cbw->block_size = cpu_to_le16(req->data->blksz);
else
ushc->cbw->block_size = 0;
ushc->cbw->arg = cpu_to_le32(req->cmd->arg);
ret = usb_submit_urb(ushc->cbw_urb, GFP_ATOMIC);
if (ret < 0)
goto out;
/* Submit data (if any). */
if (req->data) {
struct mmc_data *data = req->data;
int pipe;
if (data->flags & MMC_DATA_READ)
pipe = usb_rcvbulkpipe(ushc->usb_dev, 6);
else
pipe = usb_sndbulkpipe(ushc->usb_dev, 2);
usb_fill_bulk_urb(ushc->data_urb, ushc->usb_dev, pipe,
sg_virt(data->sg), data->sg->length,
data_callback, ushc);
ret = usb_submit_urb(ushc->data_urb, GFP_ATOMIC);
if (ret < 0)
goto out;
}
/* Submit CSW. */
ret = usb_submit_urb(ushc->csw_urb, GFP_ATOMIC);
if (ret < 0)
goto out;
out:
spin_unlock_irqrestore(&ushc->lock, flags);
if (ret < 0) {
usb_unlink_urb(ushc->cbw_urb);
usb_unlink_urb(ushc->data_urb);
req->cmd->error = ret;
mmc_request_done(mmc, req);
}
}
static int ushc_set_power(struct ushc_data *ushc, unsigned char power_mode)
{
u16 voltage;
switch (power_mode) {
case MMC_POWER_OFF:
voltage = USHC_PWR_CTRL_OFF;
break;
case MMC_POWER_UP:
case MMC_POWER_ON:
voltage = USHC_PWR_CTRL_3V3;
break;
default:
return -EINVAL;
}
return usb_control_msg(ushc->usb_dev, usb_sndctrlpipe(ushc->usb_dev, 0),
USHC_PWR_CTRL, USHC_PWR_CTRL_TYPE,
voltage, 0, NULL, 0, 100);
}
static int ushc_set_bus_width(struct ushc_data *ushc, int bus_width)
{
return ushc_hw_set_host_ctrl(ushc, USHC_HOST_CTRL_4BIT,
bus_width == 4 ? USHC_HOST_CTRL_4BIT : 0);
}
static int ushc_set_bus_freq(struct ushc_data *ushc, int clk, bool enable_hs)
{
int ret;
/* Hardware can't detect interrupts while the clock is off. */
if (clk == 0)
clk = 400000;
ret = ushc_hw_set_host_ctrl(ushc, USHC_HOST_CTRL_HIGH_SPD,
enable_hs ? USHC_HOST_CTRL_HIGH_SPD : 0);
if (ret < 0)
return ret;
ret = usb_control_msg(ushc->usb_dev, usb_sndctrlpipe(ushc->usb_dev, 0),
USHC_CLK_FREQ, USHC_CLK_FREQ_TYPE,
clk & 0xffff, (clk >> 16) & 0xffff, NULL, 0, 100);
if (ret < 0)
return ret;
ushc->clock_freq = clk;
return 0;
}
static void ushc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct ushc_data *ushc = mmc_priv(mmc);
ushc_set_power(ushc, ios->power_mode);
ushc_set_bus_width(ushc, 1 << ios->bus_width);
ushc_set_bus_freq(ushc, ios->clock, ios->timing == MMC_TIMING_SD_HS);
}
static int ushc_get_cd(struct mmc_host *mmc)
{
struct ushc_data *ushc = mmc_priv(mmc);
return !!(ushc->last_status & USHC_INT_STATUS_CARD_PRESENT);
}
static void ushc_enable_sdio_irq(struct mmc_host *mmc, int enable)
{
struct ushc_data *ushc = mmc_priv(mmc);
if (enable)
set_bit(INT_EN, &ushc->flags);
else
clear_bit(INT_EN, &ushc->flags);
}
static void ushc_clean_up(struct ushc_data *ushc)
{
usb_free_urb(ushc->int_urb);
usb_free_urb(ushc->csw_urb);
usb_free_urb(ushc->data_urb);
usb_free_urb(ushc->cbw_urb);
kfree(ushc->int_data);
kfree(ushc->cbw);
kfree(ushc->csw);
mmc_free_host(ushc->mmc);
}
static const struct mmc_host_ops ushc_ops = {
.request = ushc_request,
.set_ios = ushc_set_ios,
.get_cd = ushc_get_cd,
.enable_sdio_irq = ushc_enable_sdio_irq,
};
static int ushc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct mmc_host *mmc;
struct ushc_data *ushc;
int ret;
mmc = mmc_alloc_host(sizeof(struct ushc_data), &intf->dev);
if (mmc == NULL)
return -ENOMEM;
ushc = mmc_priv(mmc);
usb_set_intfdata(intf, ushc);
ushc->usb_dev = usb_dev;
ushc->mmc = mmc;
spin_lock_init(&ushc->lock);
ret = ushc_hw_reset(ushc);
if (ret < 0)
goto err;
/* Read capabilities. */
ret = ushc_hw_get_caps(ushc);
if (ret < 0)
goto err;
mmc->ops = &ushc_ops;
mmc->f_min = 400000;
mmc->f_max = 50000000;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_SDIO_IRQ;
mmc->caps |= (ushc->caps & USHC_GET_CAPS_HIGH_SPD) ? MMC_CAP_SD_HIGHSPEED : 0;
mmc->max_seg_size = 512*511;
mmc->max_segs = 1;
mmc->max_req_size = 512*511;
mmc->max_blk_size = 512;
mmc->max_blk_count = 511;
ushc->int_urb = usb_alloc_urb(0, GFP_KERNEL);
if (ushc->int_urb == NULL) {
ret = -ENOMEM;
goto err;
}
ushc->int_data = kzalloc(sizeof(struct ushc_int_data), GFP_KERNEL);
if (ushc->int_data == NULL) {
ret = -ENOMEM;
goto err;
}
usb_fill_int_urb(ushc->int_urb, ushc->usb_dev,
usb_rcvintpipe(usb_dev,
intf->cur_altsetting->endpoint[0].desc.bEndpointAddress),
ushc->int_data, sizeof(struct ushc_int_data),
int_callback, ushc,
intf->cur_altsetting->endpoint[0].desc.bInterval);
ushc->cbw_urb = usb_alloc_urb(0, GFP_KERNEL);
if (ushc->cbw_urb == NULL) {
ret = -ENOMEM;
goto err;
}
ushc->cbw = kzalloc(sizeof(struct ushc_cbw), GFP_KERNEL);
if (ushc->cbw == NULL) {
ret = -ENOMEM;
goto err;
}
ushc->cbw->signature = USHC_CBW_SIGNATURE;
usb_fill_bulk_urb(ushc->cbw_urb, ushc->usb_dev, usb_sndbulkpipe(usb_dev, 2),
ushc->cbw, sizeof(struct ushc_cbw),
cbw_callback, ushc);
ushc->data_urb = usb_alloc_urb(0, GFP_KERNEL);
if (ushc->data_urb == NULL) {
ret = -ENOMEM;
goto err;
}
ushc->csw_urb = usb_alloc_urb(0, GFP_KERNEL);
if (ushc->csw_urb == NULL) {
ret = -ENOMEM;
goto err;
}
ushc->csw = kzalloc(sizeof(struct ushc_cbw), GFP_KERNEL);
if (ushc->csw == NULL) {
ret = -ENOMEM;
goto err;
}
usb_fill_bulk_urb(ushc->csw_urb, ushc->usb_dev, usb_rcvbulkpipe(usb_dev, 6),
ushc->csw, sizeof(struct ushc_csw),
csw_callback, ushc);
ret = mmc_add_host(ushc->mmc);
if (ret)
goto err;
ret = usb_submit_urb(ushc->int_urb, GFP_KERNEL);
if (ret < 0) {
mmc_remove_host(ushc->mmc);
goto err;
}
return 0;
err:
ushc_clean_up(ushc);
return ret;
}
static void ushc_disconnect(struct usb_interface *intf)
{
struct ushc_data *ushc = usb_get_intfdata(intf);
spin_lock_irq(&ushc->lock);
set_bit(DISCONNECTED, &ushc->flags);
spin_unlock_irq(&ushc->lock);
usb_kill_urb(ushc->int_urb);
usb_kill_urb(ushc->cbw_urb);
usb_kill_urb(ushc->data_urb);
usb_kill_urb(ushc->csw_urb);
mmc_remove_host(ushc->mmc);
ushc_clean_up(ushc);
}
static struct usb_device_id ushc_id_table[] = {
/* CSR USB SD Host Controller */
{ USB_DEVICE(0x0a12, 0x5d10) },
{ },
};
MODULE_DEVICE_TABLE(usb, ushc_id_table);
static struct usb_driver ushc_driver = {
.name = "ushc",
.id_table = ushc_id_table,
.probe = ushc_probe,
.disconnect = ushc_disconnect,
};
static int __init ushc_init(void)
{
return usb_register(&ushc_driver);
}
module_init(ushc_init);
static void __exit ushc_exit(void)
{
usb_deregister(&ushc_driver);
}
module_exit(ushc_exit);
MODULE_DESCRIPTION("USB SD Host Controller driver");
MODULE_AUTHOR("David Vrabel <david.vrabel@csr.com>");
MODULE_LICENSE("GPL");
|
jeffegg/beaglebone
|
drivers/mmc/host/ushc.c
|
C
|
gpl-2.0
| 14,378
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.