code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package org.jiserte.bioformats.readers.phylip;
import org.jiserte.bioformats.readers.faults.AlignmentReadingFault;
public class FirstBlockLinePhylipFault extends AlignmentReadingFault {
public FirstBlockLinePhylipFault() {
super();
this.setMessage("Sequences in the first block of data must have a description of 10 characters and then the sequence.");
}
}
| javieriserte/XI-bio-formats | XI-Bio-Formats/src/org/jiserte/bioformats/readers/phylip/FirstBlockLinePhylipFault.java | Java | gpl-2.0 | 378 |
<?php
/*=======================================================================
// File: BACKEND.INC.PHP
// Description: All various output backends for QR barcodes available
// Created: 2008-08-01
// Ver: $Id: backend.inc.php 1504 2009-07-06 13:34:57Z ljp $
//
// Copyright (c) 2008 Aditus Consulting. All rights reserved.
//========================================================================
*/
DEFINE('BACKEND_ASCII', 0);
DEFINE('BACKEND_IMAGE', 1);
DEFINE('BACKEND_PS', 2);
DEFINE('BACKEND_EPS', 3);
//--------------------------------------------------------------------------------
// Class: QRCodeBackend
// Description: Parent class for all common functionality for barcode backends
//--------------------------------------------------------------------------------
class QRCodeBackend {
protected $iEncoder = NULL;
protected $iModWidth = 2;
protected $iInv = false;
protected $iQuietZone = 0;
protected $iError = 0;
protected $iQRInfo = array(); // Holds some infromation the QR code just generated
function __construct($aBarcodeEncoder) {
$this->iEncoder = $aBarcodeEncoder;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
if( $aDebug !== FALSE ) {
$this->iEncoder->SetDebugLevel($aDebug);
}
// If data is an array we assume it is supposed to be manual encodation.
// (A more thorough data check is made in the encodation class)
$manual = is_array($aData) ;
// Return the print specificiation (QRLayout)
return $this->iEncoder->Enc($aData, $manual);
}
function GetQRInfo() {
return $this->iQRInfo;
}
function isCmdLine() {
$s=php_sapi_name();
return substr($s, 0, 3) == 'cli';
}
function fmtInfo($aS) {
if ( !$this->isCmdLine() ) {
return '<pre>' . $aS . '<pre>';
}
else return $aS;
}
function SetModuleWidth($aW) {
$this->iModWidth = $aW;
}
function SetQuietZone($aW) {
$this->iQuietZone = $aW;
}
function SetTilde($aFlg = true) {
//throw new QRException('Tilde processing is not yet supported for QR Barcodes.',-1);
throw new QRExceptionL(1000);
//$this->iEncoder->SetTilde($aFlg);
}
function SetInvert($aFlg = true) {
//throw new QRException("Inverting the bit pattern is not supported for QR Barcodes.",-1);
throw new QRExceptionL(1001);
}
function GetError() {
return $this->iError;
}
function StrokeFromFile($aFromFileName,$aFileName='',$aDebug=FALSE) {
$data = @file_get_contents($aFromFileName);
if( $data === FALSE ) {
//throw new QRException("Cannot read data from file $aFromFileName");
throw new QRExceptionL(1002,$aFromFileName);
}
$this->Stroke($data,$aFileName,$aDebug);
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_PS
// Description: Backend to generate postscript (or EPS) representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_PS extends QRCodeBackend {
private $iEPS = false;
function __construct($aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
}
function SetEPS($aFlg=true) {
$this->iEPS = $aFlg;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
$w = $this->iModWidth;
$n = $pspec->iSize[0]; // width/height of matrix
$ystart = 4*$w + $n*$w;
$xstart = 4*$w ;
$totwidth = $n*$w+8*$w ;
$totheight = $n*$w+8*$w ;
$psbar = "%Data: $aData\n";
$psbar .= "%Each line represents one row and the x-position for black modules: [xpos]\n";
if( is_array($aData)) {
$data = " (manual encodation schemas) \n";
$m = count($aData);
for($i=0; $i < $m; $i++) {
$data .= "%% (" . $aData[$i][0] . " : " . $aData[$i][1] . ")\n" ;
}
$aData = $data;
}
$y = $ystart;
$psbar .= "\n";
$psbar .= ($w+0.05)." setlinewidth\n";
for( $r=0; $r < $n ; ++$r, $y -= $w ) {
$psbar .= '[';
$x = $xstart;
for( $i=0; $i < $n; ++$i, $x += $w ) {
if( $pspec->iMatrix[$r][$i] == 1) {
$psbar .= "[$x]";
}
}
$psbar .= "] {{} forall $y moveto 0 -".($w+0.05)." rlineto stroke} forall\n";
}
$psbar .= "\n";
$y += 4*$w;
$psbar .= "%End of QR Barcode \n\n";
if( !$this->iEPS )
$psbar .= "showpage \n\n";
$psbar .= "%%Trailer\n\n";
$errStr = array('L', 'M', 'Q', 'H');
$ps = ($this->iEPS ? "%!PS-Adobe EPSF-3.0\n" : "%!PS-Adobe-3.0\n" ) .
"%%Title: QR Barcode ".$pspec->iVersion."-".$errStr[$pspec->iErrLevel].", mask=".$pspec->iMaskIdx."\n".
"%%Creator: JpGraph Barcode http://www.aditus.nu/jpgraph/\n".
"%%CreationDate: ".date("D j M H:i:s Y",time())."\n";
if( $this->iEPS ) {
$ps .= "%%BoundingBox: 0 0 $totwidth $totheight\n";
}
else {
$ps .= "%%DocumentPaperSizes: A4\n";
}
$ps .=
"%%EndComments\n".
"%%BeginProlog\n".
"%%EndProlog\n";
if( !$this->iEPS )
$ps .= "%%Page: 1 1\n";
$ps .= "\n%Module width: $this->iModWidth pt\n\n";
/*
if( $this->iScale != 1 ) {
$ps .=
"%%Scale barcode\n".
"$this->iScale $this->iScale scale\n\n";
}
*/
$ps = $ps.$psbar;
$errStr=array ( 'L', 'M', 'Q', 'H' );
$this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx);
if( $aFileName !== '' ) {
$fp = @fopen($aFileName,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open file $aFileName.");
throw new QRExceptionL(1003,$aFileName);
}
if( fwrite($fp,$ps) === FALSE ) {
//throw new QRException("Cannot write barcode to file $aFileName.");
throw new QRExceptionL(1004,$aFileName);
}
return fclose($fp);
}
else {
return $ps;
}
}
}
require_once('rgb_colors.inc.php');
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_IMAGE
// Description: Backend to generate image representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_IMAGE extends QRCodeBackend {
private $iColor = array ( array ( 0, 0, 0 ), array ( 255, 255, 255 ), array ( 255, 255, 255 ) );
private $iRGB = null;
private $iImgFormat = 'png', $iQualityJPEG = 75;
function __construct($aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
$this->iRGB=new BarcodeRGB();
}
function SetSize($aShapeIdx) {
$this->iEncoder->SetSize($aShapeIdx);
}
function SetColor($aOne, $aZero, $aBackground = array ( 255, 255, 255 )) {
$this->iColor[0]=$aOne;
$this->iColor[1]=$aZero;
$this->iColor[2]=$aBackground;
}
// Specify image format. Note depending on your installation
// of PHP not all formats may be supported.
function SetImgFormat($aFormat, $aQuality = 75) {
$this->iQualityJPEG=$aQuality;
$this->iImgFormat=$aFormat;
}
function PrepareImgFormat() {
$format=strtolower($this->iImgFormat);
if ( $format == 'jpg' ) {
$format = 'jpeg';
}
$tst=true;
$supported=imagetypes();
if ( $format == "auto" ) {
if ( $supported & IMG_PNG )
$this->iImgFormat="png";
elseif( $supported & IMG_JPG )
$this->iImgFormat="jpeg";
elseif( $supported & IMG_GIF )
$this->iImgFormat="gif";
elseif( $supported & IMG_WBMP )
$this->iImgFormat="wbmp";
else {
//throw new QRException('Unsupported image format selected. Check your GD installation', -1);
throw new QRExceptionL(1005);
}
}
else {
if ( $format == "jpeg" || $format == "png" || $format == "gif" ) {
if ( $format == "jpeg" && !($supported & IMG_JPG) )
$tst=false;
elseif( $format == "png" && !($supported & IMG_PNG) )
$tst=false;
elseif( $format == "gif" && !($supported & IMG_GIF) )
$tst=false;
elseif( $format == "wbmp" && !($supported & IMG_WBMP) )
$tst=false;
else {
$this->iImgFormat = $format;
}
}
else
$tst=false;
if ( !$tst ) {
//throw new QRException('Unsupported image format selected. Check your GD installation', -1);
throw new QRExceptionL(1005);
}
}
return true;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
// Check the chosen graphic format
$this->PrepareImgFormat();
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
$mat=$pspec->iMatrix;
$m=$this->iModWidth;
$this->iQuietZone = $pspec->iQuietZone;
$h=$pspec->iSize[0] * $m + 2 * $m * $this->iQuietZone;
$w=$pspec->iSize[1] * $m + 2 * $m * $this->iQuietZone;
$img=@imagecreatetruecolor($w, $h);
if ( !$img ) {
$this->iError=-12;
return false;
}
$canvas_color = $this->iRGB->Allocate($img, 'white');
$one_color = $this->iRGB->Allocate($img, $this->iColor[0]);
$zero_color = $this->iRGB->Allocate($img, $this->iColor[1]);
$bkg_color = $this->iRGB->Allocate($img, $this->iColor[2]);
if ( $this->iInv && $pspec->iAllowColorInversion ) {
// Swap one/zero colors
$tmp=$one_color;
$one_color=$zero_color;
$zero_color=$tmp;
}
if ( $canvas_color === false || $one_color === false || $zero_color === false || $bkg_color === false ) {
// throw new QRException('Cannot set the selected colors. Check your GD installation and spelling of color name', -1);
throw new QRExceptionL(1006);
}
imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $canvas_color);
imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $bkg_color);
$borderoffset=0;
if ( $pspec->iDrawLeftBottomBorder ) {
// Left alignment line
imagefilledrectangle($img, $m * $this->iQuietZone, $m * $this->iQuietZone, $m * $this->iQuietZone + $m - 1,
$h - $m * $this->iQuietZone - 1, $one_color);
// Bottom alignment line
imagefilledrectangle($img, $m * $this->iQuietZone, $h - $m * $this->iQuietZone - $m,
$w - $m * $this->iQuietZone - 1, $h - $m * $this->iQuietZone - 1, $one_color);
$borderoffset=1;
}
for( $i = 0; $i < $pspec->iSize[0] - $borderoffset; ++$i ) {
for( $j = $borderoffset; $j < $pspec->iSize[1]; ++$j ) {
$bit = $mat[$i][$j] == 1 ? $one_color : $zero_color;
if ( $m == 1 ) {
imagesetpixel($img, $j + $m * $this->iQuietZone, $i + $m * $this->iQuietZone, $bit);
}
else {
imagefilledrectangle($img, $j * $m + $m * $this->iQuietZone,
$i * $m + $m * $this->iQuietZone, $j * $m + $m - 1 + $m * $this->iQuietZone,
$i * $m + $m - 1 + $m * $this->iQuietZone, $bit);
}
}
}
if ( $pspec->iDrawLeftBottomBorder ) {
// Left alignment line
imagefilledrectangle($img, $this->iQuietZone, $this->iQuietZone, $this->iQuietZone + $m - 1,
$h - $this->iQuietZone - 1, $one_color);
// Bottom alignment line
imagefilledrectangle($img, $this->iQuietZone, $h - $this->iQuietZone - $m, $w - $this->iQuietZone - 1,
$h - $this->iQuietZone - 1, $one_color);
}
if ( headers_sent($file, $lineno) ) {
// Headers already sent special error
throw new QRExceptionL(1007,$file,$lineno);
}
if ( $aFileName == '' ) {
$s=php_sapi_name();
if ( substr($s, 0, 3) != 'cli' ) {
header("Content-type: image/$this->iImgFormat");
}
switch( $this->iImgFormat ) {
case 'png':
$res=@imagepng($img);
break;
case 'jpeg':
$res=@imagejpeg($img, NULL, $this->iQualityJPEG);
break;
case 'gif':
$res=@imagegif($img);
break;
case 'wbmp':
$res=@imagewbmp($img);
break;
}
if( $res === FALSE ) {
throw new QRExceptionL(1008,$this->iImgFormat);
//throw new QRException("Could not create the barcode image. Check your GD/PHP installation.");
}
}
else {
switch( $this->iImgFormat ) {
case 'png':
$res=@imagepng($img, $aFileName);
break;
case 'jpeg':
$res=@imagejpeg($img, $aFileName, $this->iQualityJPEG);
break;
case 'gif':
$res=@imagegif($img, $aFileName);
break;
case 'wbmp':
$res=@imagewbmp($img, $aFileName);
break;
}
if( $res === FALSE ) {
throw new QRExceptionL(1011,$this->iImgFormat);
// 1011 => 'Could not write the barcode to file. Check the filesystem permission.',
}
}
// If debugging is enabled store encoding info in the specified log file
if( $aDebug !== FALSE && $aDebugFile !== '' ) {
$s = "QR Barcode Log created: " . date('r')."\n";
$s .= "Debug level = $aDebug \n";
$s .= "SAPI: " . php_sapi_name() ."\n\n";
$s .= $this->iEncoder;
$s .= $pspec;
$fp = @fopen($aDebugFile,'wt');
if( $fp === FALSE ) {
//throw new QRException("Cannot open log file for writing $aDebugFile.");
throw new QRExceptionL(1009,$aDebugFile);
}
if( @fwrite($fp,$s) === FALSE ) {
//throw new QRException("Cannot write log info to log file $aDebugFile.");
throw new QRExceptionL(1010,$aDebugFile);
}
fclose($fp);
}
$errStr=array ( 'L', 'M', 'Q', 'H' );
$this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx);
return 'true';
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_ASCII
// Description: Backend to generate ASCII representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_ASCII extends QRCodeBackend {
function __construct(&$aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
}
function GetMatrixString($mat, $inv = false, $width = 1, $aOne = 'X', $aZero = '-') {
if ( $width > 1 ) {
$m=count($mat);
$n=count($mat[0]);
$newmat=array();
for( $i = 0; $i < $m; ++$i )
for( $j = 0; $j < $n; ++$j )
for( $k = 0; $k < $width; ++$k )
for( $l = 0; $l < $width; ++$l )
$newmat[$i * $width + $k][$j * $width + $l]=$mat[$i][$j];
$mat=$newmat;
}
$m=count($mat);
$n=count($mat[0]);
$s = '';
for( $i = 0; $i < $m; ++$i ) {
for( $j = 0; $j < $n; ++$j ) {
if ( !$inv ) {
$s .= $mat[$i][$j] ? $aOne : $aZero;
}
else {
$s .= !$mat[$i][$j] ? $aOne : $aZero;
}
}
$s .= "\n";
}
$s .= "\n";
return $this->fmtInfo($s);
}
function Stroke(&$aData, $aFileName='', $aDebug = FALSE, $aDebugFile = '') {
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
// If debugging is enabled store encoding info in the specified log file
if( $aDebug !== FALSE ) {
$s = str_repeat('=',80)."\n";
$s .= "QR Barcode Log created: " . date('r')."\n";
$s .= str_repeat('=',80)."\n";
$s .= "Debug level = $aDebug \n";
$s .= "SAPI: " . php_sapi_name() ."\n\n";
$s .= $this->iEncoder;
$s .= $pspec . "\n";
$s .= str_repeat('=',80)."\nEnd of QR Barcode log file.\n".str_repeat('=',80)."\n\n";
if( $aDebugFile != '' ) {
$fp = @fopen($aDebugFile,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open log file for writing $aDebugFile.");
throw new QRExceptionL(1009,$aDebugFile);
}
if( @fwrite($fp,$s) === FALSE ) {
// throw new QRException("Cannot write log info to log file $aDebugFile.");
throw new QRExceptionL(1010,$aDebugFile);
}
fclose($fp);
}
else {
echo $this->fmtInfo($s);
}
}
$s = $this->GetMatrixString($pspec->iMatrix, $this->iInv, $this->iModWidth, 'X', '-') . "\n";
if( $aFileName !== '' ) {
$fp = @fopen($aFileName,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open file $aFileName.");
throw new QRExceptionL(1003,$aFileName);
}
if( fwrite($fp,$s) === FALSE ) {
// throw new QRException("Cannot write barcode to file $aFileName.");
throw new QRExceptionL(1004,$aFileName);
}
return fclose($fp);
}
else {
return $s;
}
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackendFactory
// Description: Factory to return a suitable backend for generating barcode
//--------------------------------------------------------------------------------
class QRCodeBackendFactory {
static function Create(&$aBarcodeEncoder, $aBackend = BACKEND_IMAGE) {
switch( $aBackend ) {
case BACKEND_ASCII:
return new QRCodeBackend_ASCII($aBarcodeEncoder);
break;
case BACKEND_IMAGE:
return new QRCodeBackend_Image($aBarcodeEncoder);
break;
case BACKEND_PS:
return new QRCodeBackend_PS($aBarcodeEncoder);
break;
case BACKEND_EPS:
$b = new QRCodeBackend_PS($aBarcodeEncoder);
$b->SetEPS(true);
return $b;
break;
default:
return false;
}
}
}
?> | noparking/alticcio | core/outils/exterieurs/jpgraph/src/QR/backend.inc.php | PHP | gpl-2.0 | 19,943 |
namespace Tipshare
{
partial class Tipshare
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.gbAM = new System.Windows.Forms.GroupBox();
this.tbAMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblAMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbAMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblAMUnallocated = new System.Windows.Forms.Label();
this.lAMAdj = new System.Windows.Forms.Label();
this.lAMSugg = new System.Windows.Forms.Label();
this.lAMID = new System.Windows.Forms.Label();
this.lAMName = new System.Windows.Forms.Label();
this.gbControls = new System.Windows.Forms.GroupBox();
this.btnDistributeUnallocated = new System.Windows.Forms.Button();
this.btnSettings = new System.Windows.Forms.Button();
this.btnReset = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.lDate = new System.Windows.Forms.Label();
this.lDay = new System.Windows.Forms.Label();
this.bDayBack = new System.Windows.Forms.Button();
this.bDayForward = new System.Windows.Forms.Button();
this.gbPM = new System.Windows.Forms.GroupBox();
this.tbPMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblPMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbPMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblPMUnallocated = new System.Windows.Forms.Label();
this.lPMAdj = new System.Windows.Forms.Label();
this.lPMSugg = new System.Windows.Forms.Label();
this.lPMID = new System.Windows.Forms.Label();
this.lPMName = new System.Windows.Forms.Label();
this.msMenu = new System.Windows.Forms.MenuStrip();
this.mFile = new System.Windows.Forms.ToolStripMenuItem();
this.miJump = new System.Windows.Forms.ToolStripMenuItem();
this.miPrint = new System.Windows.Forms.ToolStripMenuItem();
this.miExit = new System.Windows.Forms.ToolStripMenuItem();
this.mAbout = new System.Windows.Forms.ToolStripMenuItem();
this.miHelp = new System.Windows.Forms.ToolStripMenuItem();
this.miAbout = new System.Windows.Forms.ToolStripMenuItem();
this.tTimer = new System.Windows.Forms.Timer(this.components);
this.gbTotals = new System.Windows.Forms.GroupBox();
this.lTotalSugg = new System.Windows.Forms.Label();
this.lTotalAdj = new System.Windows.Forms.Label();
this.lLabTotSug = new System.Windows.Forms.Label();
this.lTotalAMSugg = new System.Windows.Forms.Label();
this.lTotalAMAdj = new System.Windows.Forms.Label();
this.lLabTotAMSugg = new System.Windows.Forms.Label();
this.lTotalPMSugg = new System.Windows.Forms.Label();
this.lTotalPMAdj = new System.Windows.Forms.Label();
this.lLabTotPMSugg = new System.Windows.Forms.Label();
this.gbAM.SuspendLayout();
this.gbControls.SuspendLayout();
this.gbPM.SuspendLayout();
this.msMenu.SuspendLayout();
this.gbTotals.SuspendLayout();
this.SuspendLayout();
//
// gbAM
//
this.gbAM.Controls.Add(this.tbAMUnallocatedAdj);
this.gbAM.Controls.Add(this.lblAMCurrentUnallocated);
this.gbAM.Controls.Add(this.tbAMUnallocatedSugg);
this.gbAM.Controls.Add(this.lblAMUnallocated);
this.gbAM.Controls.Add(this.lAMAdj);
this.gbAM.Controls.Add(this.lAMSugg);
this.gbAM.Controls.Add(this.lAMID);
this.gbAM.Controls.Add(this.lAMName);
this.gbAM.Location = new System.Drawing.Point(12, 27);
this.gbAM.Name = "gbAM";
this.gbAM.Size = new System.Drawing.Size(318, 430);
this.gbAM.TabIndex = 1;
this.gbAM.TabStop = false;
this.gbAM.Text = "AM Declarations";
//
// tbAMUnallocatedAdj
//
this.tbAMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbAMUnallocatedAdj.Name = "tbAMUnallocatedAdj";
this.tbAMUnallocatedAdj.ReadOnly = true;
this.tbAMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedAdj.TabIndex = 14;
//
// lblAMCurrentUnallocated
//
this.lblAMCurrentUnallocated.AutoSize = true;
this.lblAMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblAMCurrentUnallocated.Name = "lblAMCurrentUnallocated";
this.lblAMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblAMCurrentUnallocated.TabIndex = 13;
this.lblAMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbAMUnallocatedSugg
//
this.tbAMUnallocatedSugg.Location = new System.Drawing.Point(118, 404);
this.tbAMUnallocatedSugg.Name = "tbAMUnallocatedSugg";
this.tbAMUnallocatedSugg.ReadOnly = true;
this.tbAMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedSugg.TabIndex = 12;
//
// lblAMUnallocated
//
this.lblAMUnallocated.AutoSize = true;
this.lblAMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblAMUnallocated.Name = "lblAMUnallocated";
this.lblAMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblAMUnallocated.TabIndex = 10;
this.lblAMUnallocated.Text = "Starting Unallocated:";
//
// lAMAdj
//
this.lAMAdj.AutoSize = true;
this.lAMAdj.Location = new System.Drawing.Point(276, 16);
this.lAMAdj.Name = "lAMAdj";
this.lAMAdj.Size = new System.Drawing.Size(22, 13);
this.lAMAdj.TabIndex = 9;
this.lAMAdj.Text = "Adj";
//
// lAMSugg
//
this.lAMSugg.AutoSize = true;
this.lAMSugg.Location = new System.Drawing.Point(216, 16);
this.lAMSugg.Name = "lAMSugg";
this.lAMSugg.Size = new System.Drawing.Size(32, 13);
this.lAMSugg.TabIndex = 8;
this.lAMSugg.Text = "Sugg";
//
// lAMID
//
this.lAMID.AutoSize = true;
this.lAMID.Location = new System.Drawing.Point(169, 16);
this.lAMID.Name = "lAMID";
this.lAMID.Size = new System.Drawing.Size(18, 13);
this.lAMID.TabIndex = 7;
this.lAMID.Text = "ID";
//
// lAMName
//
this.lAMName.AutoSize = true;
this.lAMName.Location = new System.Drawing.Point(69, 16);
this.lAMName.Name = "lAMName";
this.lAMName.Size = new System.Drawing.Size(35, 13);
this.lAMName.TabIndex = 6;
this.lAMName.Text = "Name";
//
// gbControls
//
this.gbControls.Controls.Add(this.btnDistributeUnallocated);
this.gbControls.Controls.Add(this.btnSettings);
this.gbControls.Controls.Add(this.btnReset);
this.gbControls.Controls.Add(this.btnSave);
this.gbControls.Controls.Add(this.lDate);
this.gbControls.Controls.Add(this.lDay);
this.gbControls.Controls.Add(this.bDayBack);
this.gbControls.Controls.Add(this.bDayForward);
this.gbControls.Location = new System.Drawing.Point(12, 518);
this.gbControls.Name = "gbControls";
this.gbControls.Size = new System.Drawing.Size(648, 62);
this.gbControls.TabIndex = 2;
this.gbControls.TabStop = false;
this.gbControls.Text = "Controls";
//
// btnDistributeUnallocated
//
this.btnDistributeUnallocated.Enabled = false;
this.btnDistributeUnallocated.Location = new System.Drawing.Point(123, 19);
this.btnDistributeUnallocated.Name = "btnDistributeUnallocated";
this.btnDistributeUnallocated.Size = new System.Drawing.Size(111, 35);
this.btnDistributeUnallocated.TabIndex = 13;
this.btnDistributeUnallocated.Text = "Distribute Unallocated";
this.btnDistributeUnallocated.UseVisualStyleBackColor = true;
this.btnDistributeUnallocated.Click += new System.EventHandler(this.btnDistributeUnallocated_Click);
//
// btnSettings
//
this.btnSettings.Location = new System.Drawing.Point(6, 19);
this.btnSettings.Name = "btnSettings";
this.btnSettings.Size = new System.Drawing.Size(111, 35);
this.btnSettings.TabIndex = 12;
this.btnSettings.Text = "Advanced Settings";
this.btnSettings.UseVisualStyleBackColor = true;
this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click);
//
// btnReset
//
this.btnReset.Location = new System.Drawing.Point(414, 19);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(111, 35);
this.btnReset.TabIndex = 11;
this.btnReset.Text = "Reset Day";
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(531, 19);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(111, 35);
this.btnSave.TabIndex = 10;
this.btnSave.Text = "SAVE";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// lDate
//
this.lDate.AutoSize = true;
this.lDate.Location = new System.Drawing.Point(297, 19);
this.lDate.Name = "lDate";
this.lDate.Size = new System.Drawing.Size(64, 13);
this.lDate.TabIndex = 9;
this.lDate.Text = "##DATE##";
//
// lDay
//
this.lDay.AutoSize = true;
this.lDay.Location = new System.Drawing.Point(308, 41);
this.lDay.Name = "lDay";
this.lDay.Size = new System.Drawing.Size(26, 13);
this.lDay.TabIndex = 8;
this.lDay.Text = "Day";
//
// bDayBack
//
this.bDayBack.Location = new System.Drawing.Point(263, 35);
this.bDayBack.Name = "bDayBack";
this.bDayBack.Size = new System.Drawing.Size(39, 23);
this.bDayBack.TabIndex = 1;
this.bDayBack.Text = "<<";
this.bDayBack.UseVisualStyleBackColor = true;
this.bDayBack.Click += new System.EventHandler(this.bDayBack_Click);
//
// bDayForward
//
this.bDayForward.Location = new System.Drawing.Point(340, 36);
this.bDayForward.Name = "bDayForward";
this.bDayForward.Size = new System.Drawing.Size(39, 23);
this.bDayForward.TabIndex = 0;
this.bDayForward.Text = ">>";
this.bDayForward.UseVisualStyleBackColor = true;
this.bDayForward.Click += new System.EventHandler(this.bDayForward_Click);
//
// gbPM
//
this.gbPM.Controls.Add(this.tbPMUnallocatedAdj);
this.gbPM.Controls.Add(this.lblPMCurrentUnallocated);
this.gbPM.Controls.Add(this.tbPMUnallocatedSugg);
this.gbPM.Controls.Add(this.lblPMUnallocated);
this.gbPM.Controls.Add(this.lPMAdj);
this.gbPM.Controls.Add(this.lPMSugg);
this.gbPM.Controls.Add(this.lPMID);
this.gbPM.Controls.Add(this.lPMName);
this.gbPM.Location = new System.Drawing.Point(342, 27);
this.gbPM.Name = "gbPM";
this.gbPM.Size = new System.Drawing.Size(318, 430);
this.gbPM.TabIndex = 4;
this.gbPM.TabStop = false;
this.gbPM.Text = "PM Declarations";
//
// tbPMUnallocatedAdj
//
this.tbPMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbPMUnallocatedAdj.Name = "tbPMUnallocatedAdj";
this.tbPMUnallocatedAdj.ReadOnly = true;
this.tbPMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedAdj.TabIndex = 18;
//
// lblPMCurrentUnallocated
//
this.lblPMCurrentUnallocated.AutoSize = true;
this.lblPMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblPMCurrentUnallocated.Name = "lblPMCurrentUnallocated";
this.lblPMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblPMCurrentUnallocated.TabIndex = 17;
this.lblPMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbPMUnallocatedSugg
//
this.tbPMUnallocatedSugg.Location = new System.Drawing.Point(115, 404);
this.tbPMUnallocatedSugg.Name = "tbPMUnallocatedSugg";
this.tbPMUnallocatedSugg.ReadOnly = true;
this.tbPMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedSugg.TabIndex = 15;
//
// lblPMUnallocated
//
this.lblPMUnallocated.AutoSize = true;
this.lblPMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblPMUnallocated.Name = "lblPMUnallocated";
this.lblPMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblPMUnallocated.TabIndex = 14;
this.lblPMUnallocated.Text = "Starting Unallocated:";
//
// lPMAdj
//
this.lPMAdj.AutoSize = true;
this.lPMAdj.Location = new System.Drawing.Point(276, 16);
this.lPMAdj.Name = "lPMAdj";
this.lPMAdj.Size = new System.Drawing.Size(22, 13);
this.lPMAdj.TabIndex = 13;
this.lPMAdj.Text = "Adj";
//
// lPMSugg
//
this.lPMSugg.AutoSize = true;
this.lPMSugg.Location = new System.Drawing.Point(216, 16);
this.lPMSugg.Name = "lPMSugg";
this.lPMSugg.Size = new System.Drawing.Size(32, 13);
this.lPMSugg.TabIndex = 12;
this.lPMSugg.Text = "Sugg";
//
// lPMID
//
this.lPMID.AutoSize = true;
this.lPMID.Location = new System.Drawing.Point(169, 16);
this.lPMID.Name = "lPMID";
this.lPMID.Size = new System.Drawing.Size(18, 13);
this.lPMID.TabIndex = 11;
this.lPMID.Text = "ID";
//
// lPMName
//
this.lPMName.AutoSize = true;
this.lPMName.Location = new System.Drawing.Point(69, 16);
this.lPMName.Name = "lPMName";
this.lPMName.Size = new System.Drawing.Size(35, 13);
this.lPMName.TabIndex = 10;
this.lPMName.Text = "Name";
//
// msMenu
//
this.msMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mFile,
this.mAbout});
this.msMenu.Location = new System.Drawing.Point(0, 0);
this.msMenu.Name = "msMenu";
this.msMenu.Size = new System.Drawing.Size(672, 24);
this.msMenu.TabIndex = 5;
this.msMenu.Text = "MenuStrip";
//
// mFile
//
this.mFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miJump,
this.miPrint,
this.miExit});
this.mFile.Name = "mFile";
this.mFile.Size = new System.Drawing.Size(37, 20);
this.mFile.Text = "File";
//
// miJump
//
this.miJump.Name = "miJump";
this.miJump.Size = new System.Drawing.Size(148, 22);
this.miJump.Text = "Jump to day...";
//
// miPrint
//
this.miPrint.Name = "miPrint";
this.miPrint.Size = new System.Drawing.Size(148, 22);
this.miPrint.Text = "Print Today";
this.miPrint.Click += new System.EventHandler(this.miPrint_Click);
//
// miExit
//
this.miExit.Name = "miExit";
this.miExit.Size = new System.Drawing.Size(148, 22);
this.miExit.Text = "Exit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// mAbout
//
this.mAbout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miHelp,
this.miAbout});
this.mAbout.Name = "mAbout";
this.mAbout.Size = new System.Drawing.Size(52, 20);
this.mAbout.Text = "About";
//
// miHelp
//
this.miHelp.Name = "miHelp";
this.miHelp.Size = new System.Drawing.Size(107, 22);
this.miHelp.Text = "Help";
this.miHelp.Click += new System.EventHandler(this.miHelp_Click);
//
// miAbout
//
this.miAbout.Name = "miAbout";
this.miAbout.Size = new System.Drawing.Size(107, 22);
this.miAbout.Text = "About";
this.miAbout.Click += new System.EventHandler(this.miAbout_Click);
//
// tTimer
//
this.tTimer.Tick += new System.EventHandler(this.tTimer_Tick);
//
// gbTotals
//
this.gbTotals.Controls.Add(this.lTotalSugg);
this.gbTotals.Controls.Add(this.lTotalAdj);
this.gbTotals.Controls.Add(this.lLabTotSug);
this.gbTotals.Controls.Add(this.lTotalAMSugg);
this.gbTotals.Controls.Add(this.lTotalAMAdj);
this.gbTotals.Controls.Add(this.lLabTotAMSugg);
this.gbTotals.Controls.Add(this.lTotalPMSugg);
this.gbTotals.Controls.Add(this.lTotalPMAdj);
this.gbTotals.Controls.Add(this.lLabTotPMSugg);
this.gbTotals.Location = new System.Drawing.Point(12, 463);
this.gbTotals.Name = "gbTotals";
this.gbTotals.Size = new System.Drawing.Size(648, 49);
this.gbTotals.TabIndex = 6;
this.gbTotals.TabStop = false;
this.gbTotals.Text = "Totals";
//
// lTotalSugg
//
this.lTotalSugg.AutoSize = true;
this.lTotalSugg.Location = new System.Drawing.Point(285, 29);
this.lTotalSugg.Name = "lTotalSugg";
this.lTotalSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalSugg.TabIndex = 8;
this.lTotalSugg.Text = "##";
//
// lTotalAdj
//
this.lTotalAdj.AutoSize = true;
this.lTotalAdj.Location = new System.Drawing.Point(348, 29);
this.lTotalAdj.Name = "lTotalAdj";
this.lTotalAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAdj.TabIndex = 7;
this.lTotalAdj.Text = "##";
//
// lLabTotSug
//
this.lLabTotSug.AutoSize = true;
this.lLabTotSug.Location = new System.Drawing.Point(285, 16);
this.lLabTotSug.Name = "lLabTotSug";
this.lLabTotSug.Size = new System.Drawing.Size(79, 13);
this.lLabTotSug.TabIndex = 6;
this.lLabTotSug.Text = "Total Sugg/Adj";
//
// lTotalAMSugg
//
this.lTotalAMSugg.AutoSize = true;
this.lTotalAMSugg.Location = new System.Drawing.Point(32, 29);
this.lTotalAMSugg.Name = "lTotalAMSugg";
this.lTotalAMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalAMSugg.TabIndex = 5;
this.lTotalAMSugg.Text = "##";
//
// lTotalAMAdj
//
this.lTotalAMAdj.AutoSize = true;
this.lTotalAMAdj.Location = new System.Drawing.Point(83, 29);
this.lTotalAMAdj.Name = "lTotalAMAdj";
this.lTotalAMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAMAdj.TabIndex = 4;
this.lTotalAMAdj.Text = "##";
//
// lLabTotAMSugg
//
this.lLabTotAMSugg.AutoSize = true;
this.lLabTotAMSugg.Location = new System.Drawing.Point(19, 16);
this.lLabTotAMSugg.Name = "lLabTotAMSugg";
this.lLabTotAMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotAMSugg.TabIndex = 3;
this.lLabTotAMSugg.Text = "Total AM Sugg/Adj";
//
// lTotalPMSugg
//
this.lTotalPMSugg.AutoSize = true;
this.lTotalPMSugg.Location = new System.Drawing.Point(545, 29);
this.lTotalPMSugg.Name = "lTotalPMSugg";
this.lTotalPMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalPMSugg.TabIndex = 2;
this.lTotalPMSugg.Text = "##";
//
// lTotalPMAdj
//
this.lTotalPMAdj.AutoSize = true;
this.lTotalPMAdj.Location = new System.Drawing.Point(596, 29);
this.lTotalPMAdj.Name = "lTotalPMAdj";
this.lTotalPMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalPMAdj.TabIndex = 1;
this.lTotalPMAdj.Text = "##";
//
// lLabTotPMSugg
//
this.lLabTotPMSugg.AutoSize = true;
this.lLabTotPMSugg.Location = new System.Drawing.Point(530, 16);
this.lLabTotPMSugg.Name = "lLabTotPMSugg";
this.lLabTotPMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotPMSugg.TabIndex = 0;
this.lLabTotPMSugg.Text = "Total PM Sugg/Adj";
//
// Tipshare
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(672, 592);
this.Controls.Add(this.gbTotals);
this.Controls.Add(this.gbPM);
this.Controls.Add(this.gbControls);
this.Controls.Add(this.gbAM);
this.Controls.Add(this.msMenu);
this.MainMenuStrip = this.msMenu;
this.Name = "Tipshare";
this.Text = "Tipshare##VERSION## - ##STORENAME##";
this.Load += new System.EventHandler(this.Tipshare_Load);
this.gbAM.ResumeLayout(false);
this.gbAM.PerformLayout();
this.gbControls.ResumeLayout(false);
this.gbControls.PerformLayout();
this.gbPM.ResumeLayout(false);
this.gbPM.PerformLayout();
this.msMenu.ResumeLayout(false);
this.msMenu.PerformLayout();
this.gbTotals.ResumeLayout(false);
this.gbTotals.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox gbAM;
private System.Windows.Forms.GroupBox gbControls;
private System.Windows.Forms.GroupBox gbPM;
private System.Windows.Forms.Button bDayBack;
private System.Windows.Forms.Button bDayForward;
private System.Windows.Forms.Label lAMName;
private System.Windows.Forms.Label lAMAdj;
private System.Windows.Forms.Label lAMSugg;
private System.Windows.Forms.Label lAMID;
private System.Windows.Forms.Label lDate;
private System.Windows.Forms.Label lDay;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnDistributeUnallocated;
private System.Windows.Forms.Button btnSettings;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.Label lPMAdj;
private System.Windows.Forms.Label lPMSugg;
private System.Windows.Forms.Label lPMID;
private System.Windows.Forms.Label lPMName;
private System.Windows.Forms.MenuStrip msMenu;
private System.Windows.Forms.ToolStripMenuItem mFile;
private System.Windows.Forms.ToolStripMenuItem miJump;
private System.Windows.Forms.ToolStripMenuItem miPrint;
private System.Windows.Forms.ToolStripMenuItem miExit;
private System.Windows.Forms.ToolStripMenuItem mAbout;
private System.Windows.Forms.ToolStripMenuItem miHelp;
private System.Windows.Forms.ToolStripMenuItem miAbout;
private System.Windows.Forms.Timer tTimer;
private System.Windows.Forms.GroupBox gbTotals;
private System.Windows.Forms.Label lTotalPMAdj;
private System.Windows.Forms.Label lLabTotPMSugg;
private System.Windows.Forms.Label lTotalAMSugg;
private System.Windows.Forms.Label lTotalAMAdj;
private System.Windows.Forms.Label lLabTotAMSugg;
private System.Windows.Forms.Label lTotalPMSugg;
private System.Windows.Forms.Label lTotalSugg;
private System.Windows.Forms.Label lTotalAdj;
private System.Windows.Forms.Label lLabTotSug;
private System.Windows.Forms.TextBox tbAMUnallocatedSugg;
private System.Windows.Forms.Label lblAMUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedSugg;
private System.Windows.Forms.Label lblPMUnallocated;
private System.Windows.Forms.TextBox tbAMUnallocatedAdj;
private System.Windows.Forms.Label lblAMCurrentUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedAdj;
private System.Windows.Forms.Label lblPMCurrentUnallocated;
}
}
| nsherrill/Consulting | Concord/Tipshare/Tipshare.Designer.cs | C# | gpl-2.0 | 27,660 |
using SFML.Graphics;
using SFML.Window;
namespace LudumDare.ParticleSystem
{
public class Emitter
{
public Vector2f Position;
public int ParticlesSpawnRate;
public float Spread;
public Color Color;
}
} | WebFreak001/LD-30 | ParticleSystem/Emitter.cs | C# | gpl-2.0 | 249 |
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2012 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
[email protected]
*/
#include "SDL_config.h"
#include "SDL_mouse.h"
#include "../../events/SDL_events_c.h"
#include "SDL_vglvideo.h"
#include "SDL_vglmouse_c.h"
struct WMcursor {
int unused;
};
void VGL_FreeWMCursor(_THIS, WMcursor *cursor)
{
return;
}
WMcursor *VGL_CreateWMCursor(_THIS,
Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
{
return(NULL);
}
int VGL_ShowWMCursor(_THIS, WMcursor *cursor)
{
return(0);
}
void VGL_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
{
SDL_PrivateMouseMotion(0, 0, x, y);
}
| qtekfun/htcDesire820Kernel | external/qemu/distrib/sdl-1.2.15/src/video/vgl/SDL_vglmouse.c | C | gpl-2.0 | 1,382 |
/*
Copyright (c) 2006 Paolo Capriotti <[email protected]>
(c) 2006 Maurizio Monge <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include <cmath>
#include <QDebug>
#include <QString>
#include "common.h"
#include "point.h"
Point::Point(int x, int y)
: x(x), y(y) {
}
Point::Point(const QPoint& p)
: x(p.x()), y(p.y()) {
}
Point::Point() {
}
Point::Point(const QString& str, int ysize) {
x = y = -1;
int length = str.length();
if(length == 0)
return;
if(str[0].isLetter()) {
char c = str[0].toAscii();
if(c >= 'a' && c <= 'z')
x = c-'a';
else if(c >= 'A' && c <= 'Z')
x = c-'A';
if(length>1)
y = ysize - str.mid(1).toInt();
}
else
y = ysize - str.toInt();
}
QString Point::row(int ysize) const {
if (y != -1)
return QString::number(ysize - y);
else
return QString();
}
QString Point::numcol(int xsize) const {
if (x != -1)
return QString::number(xsize - x);
else
return QString();
}
QString Point::col() const {
if (x != -1) {
if(x >= 26)
return QChar(static_cast<char>(x - 26 + 'A'));
else
return QChar(static_cast<char>(x + 'a'));
}
else
return QString();
}
QString Point::alpharow() const {
if (y != -1) {
if(y >= 26)
return QChar(static_cast<char>(y - 26 + 'A'));
else
return QChar(static_cast<char>(y + 'a'));
}
else
return QString();
}
QString Point::toString(int ysize) const {
return col() + row(ysize);
}
Point Point::operator+(const Point& other) const {
return Point(x + other.x, y + other.y);
}
Point Point::operator+=(const Point& other) {
return *this = *this + other;
}
Point Point::operator-() const {
return Point(-x, -y);
}
Point Point::operator-(const Point& other) const {
return Point(x - other.x, y - other.y);
}
Point Point::operator*(int n) const {
return Point(x * n, y * n);
}
Point Point::operator/(int n) const {
return Point(x / n, y / n);
}
Point Point::div(int n) const {
return Point(x >= 0 ? x / n : x / n - 1,
y >= 0 ? y / n : y / n - 1);
}
bool Point::operator==(const Point& other) const {
return x == other.x && y == other.y;
}
bool Point::operator!=(const Point& other) const {
return !(*this == other);
}
bool Point::operator<(const Point& other) const {
return y < other.y || (y == other.y && x < other.x);
}
bool Point::operator<=(const Point& other) const {
return y <= other.y || (y == other.y && x <= other.x);
}
bool Point::resembles(const Point& other) const {
return (other.x == -1 || x == other.x) &&
(other.y == -1 || y == other.y);
}
Point::operator QPoint() const {
return QPoint(x,y);
}
Point Point::normalizeInfinity() const {
return Point(
normalizeInfinityHelper(x),
normalizeInfinityHelper(y)
);
}
double Point::norm() const {
return sqrt((double)(x*x + y*y));
}
int Point::normalizeInfinityHelper(int n) const {
if (n == 0)
return 0;
else
return n > 0 ? 1 : -1;
}
QDebug operator<<(QDebug dbg, const Point& p) {
dbg << "(" << (p.x == -1 ? QString("?") : QString::number(p.x))
<< ", " << (p.y == -1 ? QString("?") : QString::number(p.y)) << ")";
return dbg;
}
| ruphy/tagua | src/point.cpp | C++ | gpl-2.0 | 3,545 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_04) on Thu May 15 10:36:11 IDT 2014 -->
<title>Painter (Codename One API)</title>
<meta name="date" content="2014-05-15">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Painter (Codename One API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li>
<li><a href="Painter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.codename1.ui</div>
<h2 title="Interface Painter" class="title">Interface Painter</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../com/codename1/ui/painter/BackgroundPainter.html" title="class in com.codename1.ui.painter">BackgroundPainter</a>, <a href="../../../com/codename1/ui/util/GlassTutorial.html" title="class in com.codename1.ui.util">GlassTutorial</a>, <a href="../../../com/codename1/ui/painter/PainterChain.html" title="class in com.codename1.ui.painter">PainterChain</a>, <a href="../../../com/codename1/ui/animations/Timeline.html" title="class in com.codename1.ui.animations">Timeline</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">Painter</span></pre>
<div class="block">Painter can be used to draw on components backgrounds.
The use of such painter allows reuse of a background painters for various
components.
Note in order to view the painter drawing, component need to have some level
of transparency.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../com/codename1/ui/Painter.html#paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)">paint</a></strong>(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a> g,
<a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a> rect)</code>
<div class="block">Draws inside the given rectangle clipping area.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>paint</h4>
<pre>void paint(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a> g,
<a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a> rect)</pre>
<div class="block">Draws inside the given rectangle clipping area.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>g</code> - the <a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui"><code>Graphics</code></a> object</dd><dd><code>rect</code> - the given rectangle cliping area</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li>
<li><a href="Painter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| shannah/cn1 | CodenameOne/javadoc/com/codename1/ui/Painter.html | HTML | gpl-2.0 | 8,079 |
# class.upload by verot.net
## contributor github.com/paulds
#### v0.31 Download from verot.net/php_class_upload_download.htm
This version is not PHP 5.3 compatible | paulds/class.upload | README.md | Markdown | gpl-2.0 | 167 |
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Felix Natter in 2013.
*
* 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/>.
*/
package org.freeplane.core.resources.components;
import javax.swing.JButton;
import com.jgoodies.forms.builder.DefaultFormBuilder;
public class ButtonProperty extends PropertyBean implements IPropertyControl {
final JButton mButton;
/**
*/
public ButtonProperty(final String name, JButton button) {
super(name);
mButton = button;
}
@Override
public String getValue() {
return "";
}
public void appendToForm(final DefaultFormBuilder builder) {
appendToForm(builder, mButton);
}
public void setEnabled(final boolean pEnabled) {
mButton.setEnabled(pEnabled);
super.setEnabled(pEnabled);
}
@Override
public void setValue(final String value) {
}
public void setToolTipText(String text) {
mButton.setToolTipText(text);
}
}
| freeplane/freeplane | freeplane/src/main/java/org/freeplane/core/resources/components/ButtonProperty.java | Java | gpl-2.0 | 1,600 |
/*
* @author Philip Stutz
* @author Francisco de Freitas
*
* Copyright 2011 University of Zurich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.signalcollect.configuration
import com.signalcollect.interfaces._
import java.util.HashMap
import com.signalcollect._
import com.signalcollect.logging.DefaultLogger
import akka.actor.ActorRef
import com.signalcollect.nodeprovisioning.NodeProvisioner
import com.signalcollect.nodeprovisioning.local.LocalNodeProvisioner
/**
* All the graph configuration parameters with their defaults.
*/
case class GraphConfiguration(
maxInboxSize: Option[Long] = Some(Runtime.getRuntime.availableProcessors * 5000), //None
loggingLevel: Int = LoggingLevel.Warning,
logger: LogMessage => Unit = DefaultLogger.log,
workerFactory: WorkerFactory = factory.worker.Akka,
messageBusFactory: MessageBusFactory = factory.messagebus.SharedMemory,
storageFactory: StorageFactory = factory.storage.InMemory,
statusUpdateIntervalInMillis: Option[Long] = Some(500l),
akkaDispatcher: AkkaDispatcher = Pinned,
nodeProvisioner: NodeProvisioner = new LocalNodeProvisioner)
object LoggingLevel {
val Debug = 0
val Config = 100
val Info = 200
val Warning = 300
val Severe = 400
}
sealed trait AkkaDispatcher
case object EventBased extends AkkaDispatcher
case object Pinned extends AkkaDispatcher
| Tjoene/thesis | Case_Programs/signal-collect/src/main/scala/com/signalcollect/configuration/GraphConfiguration.scala | Scala | gpl-2.0 | 1,931 |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "sd-id128.h"
#include "sd-messages.h"
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-util.h"
#include "cgroup-util.h"
#include "dbus-unit.h"
#include "dbus.h"
#include "dropin.h"
#include "escape.h"
#include "execute.h"
#include "fileio-label.h"
#include "formats-util.h"
#include "load-dropin.h"
#include "load-fragment.h"
#include "log.h"
#include "macro.h"
#include "missing.h"
#include "mkdir.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "set.h"
#include "special.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "unit-name.h"
#include "unit.h"
#include "user-util.h"
#include "virt.h"
const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
[UNIT_SERVICE] = &service_vtable,
[UNIT_SOCKET] = &socket_vtable,
[UNIT_BUSNAME] = &busname_vtable,
[UNIT_TARGET] = &target_vtable,
[UNIT_DEVICE] = &device_vtable,
[UNIT_MOUNT] = &mount_vtable,
[UNIT_AUTOMOUNT] = &automount_vtable,
[UNIT_SWAP] = &swap_vtable,
[UNIT_TIMER] = &timer_vtable,
[UNIT_PATH] = &path_vtable,
[UNIT_SLICE] = &slice_vtable,
[UNIT_SCOPE] = &scope_vtable
};
static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
Unit *unit_new(Manager *m, size_t size) {
Unit *u;
assert(m);
assert(size >= sizeof(Unit));
u = malloc0(size);
if (!u)
return NULL;
u->names = set_new(&string_hash_ops);
if (!u->names) {
free(u);
return NULL;
}
u->manager = m;
u->type = _UNIT_TYPE_INVALID;
u->default_dependencies = true;
u->unit_file_state = _UNIT_FILE_STATE_INVALID;
u->unit_file_preset = -1;
u->on_failure_job_mode = JOB_REPLACE;
u->cgroup_inotify_wd = -1;
RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16);
return u;
}
bool unit_has_name(Unit *u, const char *name) {
assert(u);
assert(name);
return !!set_get(u->names, (char*) name);
}
static void unit_init(Unit *u) {
CGroupContext *cc;
ExecContext *ec;
KillContext *kc;
assert(u);
assert(u->manager);
assert(u->type >= 0);
cc = unit_get_cgroup_context(u);
if (cc) {
cgroup_context_init(cc);
/* Copy in the manager defaults into the cgroup
* context, _before_ the rest of the settings have
* been initialized */
cc->cpu_accounting = u->manager->default_cpu_accounting;
cc->blockio_accounting = u->manager->default_blockio_accounting;
cc->memory_accounting = u->manager->default_memory_accounting;
cc->tasks_accounting = u->manager->default_tasks_accounting;
}
ec = unit_get_exec_context(u);
if (ec)
exec_context_init(ec);
kc = unit_get_kill_context(u);
if (kc)
kill_context_init(kc);
if (UNIT_VTABLE(u)->init)
UNIT_VTABLE(u)->init(u);
}
int unit_add_name(Unit *u, const char *text) {
_cleanup_free_ char *s = NULL, *i = NULL;
UnitType t;
int r;
assert(u);
assert(text);
if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(text, u->instance, &s);
if (r < 0)
return r;
} else {
s = strdup(text);
if (!s)
return -ENOMEM;
}
if (set_contains(u->names, s))
return 0;
if (hashmap_contains(u->manager->units, s))
return -EEXIST;
if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
return -EINVAL;
t = unit_name_to_type(s);
if (t < 0)
return -EINVAL;
if (u->type != _UNIT_TYPE_INVALID && t != u->type)
return -EINVAL;
r = unit_name_to_instance(s, &i);
if (r < 0)
return r;
if (i && unit_vtable[t]->no_instances)
return -EINVAL;
/* Ensure that this unit is either instanced or not instanced,
* but not both. Note that we do allow names with different
* instance names however! */
if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i)
return -EINVAL;
if (unit_vtable[t]->no_alias && !set_isempty(u->names))
return -EEXIST;
if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
return -E2BIG;
r = set_put(u->names, s);
if (r < 0)
return r;
assert(r > 0);
r = hashmap_put(u->manager->units, s, u);
if (r < 0) {
(void) set_remove(u->names, s);
return r;
}
if (u->type == _UNIT_TYPE_INVALID) {
u->type = t;
u->id = s;
u->instance = i;
LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
unit_init(u);
i = NULL;
}
s = NULL;
unit_add_to_dbus_queue(u);
return 0;
}
int unit_choose_id(Unit *u, const char *name) {
_cleanup_free_ char *t = NULL;
char *s, *i;
int r;
assert(u);
assert(name);
if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(name, u->instance, &t);
if (r < 0)
return r;
name = t;
}
/* Selects one of the names of this unit as the id */
s = set_get(u->names, (char*) name);
if (!s)
return -ENOENT;
/* Determine the new instance from the new id */
r = unit_name_to_instance(s, &i);
if (r < 0)
return r;
u->id = s;
free(u->instance);
u->instance = i;
unit_add_to_dbus_queue(u);
return 0;
}
int unit_set_description(Unit *u, const char *description) {
char *s;
assert(u);
if (isempty(description))
s = NULL;
else {
s = strdup(description);
if (!s)
return -ENOMEM;
}
free(u->description);
u->description = s;
unit_add_to_dbus_queue(u);
return 0;
}
bool unit_check_gc(Unit *u) {
UnitActiveState state;
assert(u);
if (u->job)
return true;
if (u->nop_job)
return true;
state = unit_active_state(u);
/* If the unit is inactive and failed and no job is queued for
* it, then release its runtime resources */
if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
UNIT_VTABLE(u)->release_resources)
UNIT_VTABLE(u)->release_resources(u);
/* But we keep the unit object around for longer when it is
* referenced or configured to not be gc'ed */
if (state != UNIT_INACTIVE)
return true;
if (UNIT_VTABLE(u)->no_gc)
return true;
if (u->no_gc)
return true;
if (u->refs)
return true;
if (UNIT_VTABLE(u)->check_gc)
if (UNIT_VTABLE(u)->check_gc(u))
return true;
return false;
}
void unit_add_to_load_queue(Unit *u) {
assert(u);
assert(u->type != _UNIT_TYPE_INVALID);
if (u->load_state != UNIT_STUB || u->in_load_queue)
return;
LIST_PREPEND(load_queue, u->manager->load_queue, u);
u->in_load_queue = true;
}
void unit_add_to_cleanup_queue(Unit *u) {
assert(u);
if (u->in_cleanup_queue)
return;
LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
u->in_cleanup_queue = true;
}
void unit_add_to_gc_queue(Unit *u) {
assert(u);
if (u->in_gc_queue || u->in_cleanup_queue)
return;
if (unit_check_gc(u))
return;
LIST_PREPEND(gc_queue, u->manager->gc_queue, u);
u->in_gc_queue = true;
u->manager->n_in_gc_queue ++;
}
void unit_add_to_dbus_queue(Unit *u) {
assert(u);
assert(u->type != _UNIT_TYPE_INVALID);
if (u->load_state == UNIT_STUB || u->in_dbus_queue)
return;
/* Shortcut things if nobody cares */
if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
set_isempty(u->manager->private_buses)) {
u->sent_dbus_new_signal = true;
return;
}
LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
u->in_dbus_queue = true;
}
static void bidi_set_free(Unit *u, Set *s) {
Iterator i;
Unit *other;
assert(u);
/* Frees the set and makes sure we are dropped from the
* inverse pointers */
SET_FOREACH(other, s, i) {
UnitDependency d;
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
set_remove(other->dependencies[d], u);
unit_add_to_gc_queue(other);
}
set_free(s);
}
static void unit_remove_transient(Unit *u) {
char **i;
assert(u);
if (!u->transient)
return;
if (u->fragment_path)
(void) unlink(u->fragment_path);
STRV_FOREACH(i, u->dropin_paths) {
_cleanup_free_ char *p = NULL;
(void) unlink(*i);
p = dirname_malloc(*i);
if (p)
(void) rmdir(p);
}
}
static void unit_free_requires_mounts_for(Unit *u) {
char **j;
STRV_FOREACH(j, u->requires_mounts_for) {
char s[strlen(*j) + 1];
PATH_FOREACH_PREFIX_MORE(s, *j) {
char *y;
Set *x;
x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
if (!x)
continue;
set_remove(x, u);
if (set_isempty(x)) {
hashmap_remove(u->manager->units_requiring_mounts_for, y);
free(y);
set_free(x);
}
}
}
u->requires_mounts_for = strv_free(u->requires_mounts_for);
}
static void unit_done(Unit *u) {
ExecContext *ec;
CGroupContext *cc;
int r;
assert(u);
if (u->type < 0)
return;
if (UNIT_VTABLE(u)->done)
UNIT_VTABLE(u)->done(u);
ec = unit_get_exec_context(u);
if (ec)
exec_context_done(ec);
cc = unit_get_cgroup_context(u);
if (cc)
cgroup_context_done(cc);
r = unit_remove_from_netclass_cgroup(u);
if (r < 0)
log_warning_errno(r, "Unable to remove unit from netclass group: %m");
}
void unit_free(Unit *u) {
UnitDependency d;
Iterator i;
char *t;
assert(u);
if (u->manager->n_reloading <= 0)
unit_remove_transient(u);
bus_unit_send_removed_signal(u);
unit_done(u);
sd_bus_slot_unref(u->match_bus_slot);
unit_free_requires_mounts_for(u);
SET_FOREACH(t, u->names, i)
hashmap_remove_value(u->manager->units, t, u);
if (u->job) {
Job *j = u->job;
job_uninstall(j);
job_free(j);
}
if (u->nop_job) {
Job *j = u->nop_job;
job_uninstall(j);
job_free(j);
}
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
bidi_set_free(u, u->dependencies[d]);
if (u->type != _UNIT_TYPE_INVALID)
LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
if (u->in_load_queue)
LIST_REMOVE(load_queue, u->manager->load_queue, u);
if (u->in_dbus_queue)
LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
if (u->in_cleanup_queue)
LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
if (u->in_gc_queue) {
LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
u->manager->n_in_gc_queue--;
}
if (u->in_cgroup_queue)
LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
unit_release_cgroup(u);
(void) manager_update_failed_units(u->manager, u, false);
set_remove(u->manager->startup_units, u);
free(u->description);
strv_free(u->documentation);
free(u->fragment_path);
free(u->source_path);
strv_free(u->dropin_paths);
free(u->instance);
free(u->job_timeout_reboot_arg);
set_free_free(u->names);
unit_unwatch_all_pids(u);
condition_free_list(u->conditions);
condition_free_list(u->asserts);
unit_ref_unset(&u->slice);
while (u->refs)
unit_ref_unset(u->refs);
free(u);
}
UnitActiveState unit_active_state(Unit *u) {
assert(u);
if (u->load_state == UNIT_MERGED)
return unit_active_state(unit_follow_merge(u));
/* After a reload it might happen that a unit is not correctly
* loaded but still has a process around. That's why we won't
* shortcut failed loading to UNIT_INACTIVE_FAILED. */
return UNIT_VTABLE(u)->active_state(u);
}
const char* unit_sub_state_to_string(Unit *u) {
assert(u);
return UNIT_VTABLE(u)->sub_state_to_string(u);
}
static int complete_move(Set **s, Set **other) {
int r;
assert(s);
assert(other);
if (!*other)
return 0;
if (*s) {
r = set_move(*s, *other);
if (r < 0)
return r;
} else {
*s = *other;
*other = NULL;
}
return 0;
}
static int merge_names(Unit *u, Unit *other) {
char *t;
Iterator i;
int r;
assert(u);
assert(other);
r = complete_move(&u->names, &other->names);
if (r < 0)
return r;
set_free_free(other->names);
other->names = NULL;
other->id = NULL;
SET_FOREACH(t, u->names, i)
assert_se(hashmap_replace(u->manager->units, t, u) == 0);
return 0;
}
static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
unsigned n_reserve;
assert(u);
assert(other);
assert(d < _UNIT_DEPENDENCY_MAX);
/*
* If u does not have this dependency set allocated, there is no need
* to reserve anything. In that case other's set will be transferred
* as a whole to u by complete_move().
*/
if (!u->dependencies[d])
return 0;
/* merge_dependencies() will skip a u-on-u dependency */
n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
return set_reserve(u->dependencies[d], n_reserve);
}
static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
Iterator i;
Unit *back;
int r;
assert(u);
assert(other);
assert(d < _UNIT_DEPENDENCY_MAX);
/* Fix backwards pointers */
SET_FOREACH(back, other->dependencies[d], i) {
UnitDependency k;
for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
/* Do not add dependencies between u and itself */
if (back == u) {
if (set_remove(back->dependencies[k], other))
maybe_warn_about_dependency(u, other_id, k);
} else {
r = set_remove_and_put(back->dependencies[k], other, u);
if (r == -EEXIST)
set_remove(back->dependencies[k], other);
else
assert(r >= 0 || r == -ENOENT);
}
}
}
/* Also do not move dependencies on u to itself */
back = set_remove(other->dependencies[d], u);
if (back)
maybe_warn_about_dependency(u, other_id, d);
/* The move cannot fail. The caller must have performed a reservation. */
assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
other->dependencies[d] = set_free(other->dependencies[d]);
}
int unit_merge(Unit *u, Unit *other) {
UnitDependency d;
const char *other_id = NULL;
int r;
assert(u);
assert(other);
assert(u->manager == other->manager);
assert(u->type != _UNIT_TYPE_INVALID);
other = unit_follow_merge(other);
if (other == u)
return 0;
if (u->type != other->type)
return -EINVAL;
if (!u->instance != !other->instance)
return -EINVAL;
if (other->load_state != UNIT_STUB &&
other->load_state != UNIT_NOT_FOUND)
return -EEXIST;
if (other->job)
return -EEXIST;
if (other->nop_job)
return -EEXIST;
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
return -EEXIST;
if (other->id)
other_id = strdupa(other->id);
/* Make reservations to ensure merge_dependencies() won't fail */
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
r = reserve_dependencies(u, other, d);
/*
* We don't rollback reservations if we fail. We don't have
* a way to undo reservations. A reservation is not a leak.
*/
if (r < 0)
return r;
}
/* Merge names */
r = merge_names(u, other);
if (r < 0)
return r;
/* Redirect all references */
while (other->refs)
unit_ref_set(other->refs, u);
/* Merge dependencies */
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
merge_dependencies(u, other, other_id, d);
other->load_state = UNIT_MERGED;
other->merged_into = u;
/* If there is still some data attached to the other node, we
* don't need it anymore, and can free it. */
if (other->load_state != UNIT_STUB)
if (UNIT_VTABLE(other)->done)
UNIT_VTABLE(other)->done(other);
unit_add_to_dbus_queue(u);
unit_add_to_cleanup_queue(other);
return 0;
}
int unit_merge_by_name(Unit *u, const char *name) {
Unit *other;
int r;
_cleanup_free_ char *s = NULL;
assert(u);
assert(name);
if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(name, u->instance, &s);
if (r < 0)
return r;
name = s;
}
other = manager_get_unit(u->manager, name);
if (other)
return unit_merge(u, other);
return unit_add_name(u, name);
}
Unit* unit_follow_merge(Unit *u) {
assert(u);
while (u->load_state == UNIT_MERGED)
assert_se(u = u->merged_into);
return u;
}
int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
int r;
assert(u);
assert(c);
if (c->working_directory) {
r = unit_require_mounts_for(u, c->working_directory);
if (r < 0)
return r;
}
if (c->root_directory) {
r = unit_require_mounts_for(u, c->root_directory);
if (r < 0)
return r;
}
if (u->manager->running_as != MANAGER_SYSTEM)
return 0;
if (c->private_tmp) {
r = unit_require_mounts_for(u, "/tmp");
if (r < 0)
return r;
r = unit_require_mounts_for(u, "/var/tmp");
if (r < 0)
return r;
}
if (c->std_output != EXEC_OUTPUT_KMSG &&
c->std_output != EXEC_OUTPUT_SYSLOG &&
c->std_output != EXEC_OUTPUT_JOURNAL &&
c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_KMSG &&
c->std_error != EXEC_OUTPUT_SYSLOG &&
c->std_error != EXEC_OUTPUT_JOURNAL &&
c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
return 0;
/* If syslog or kernel logging is requested, make sure our own
* logging daemon is run first. */
r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
if (r < 0)
return r;
return 0;
}
const char *unit_description(Unit *u) {
assert(u);
if (u->description)
return u->description;
return strna(u->id);
}
void unit_dump(Unit *u, FILE *f, const char *prefix) {
char *t, **j;
UnitDependency d;
Iterator i;
const char *prefix2;
char
timestamp1[FORMAT_TIMESTAMP_MAX],
timestamp2[FORMAT_TIMESTAMP_MAX],
timestamp3[FORMAT_TIMESTAMP_MAX],
timestamp4[FORMAT_TIMESTAMP_MAX],
timespan[FORMAT_TIMESPAN_MAX];
Unit *following;
_cleanup_set_free_ Set *following_set = NULL;
int r;
assert(u);
assert(u->type >= 0);
prefix = strempty(prefix);
prefix2 = strjoina(prefix, "\t");
fprintf(f,
"%s-> Unit %s:\n"
"%s\tDescription: %s\n"
"%s\tInstance: %s\n"
"%s\tUnit Load State: %s\n"
"%s\tUnit Active State: %s\n"
"%s\tInactive Exit Timestamp: %s\n"
"%s\tActive Enter Timestamp: %s\n"
"%s\tActive Exit Timestamp: %s\n"
"%s\tInactive Enter Timestamp: %s\n"
"%s\tGC Check Good: %s\n"
"%s\tNeed Daemon Reload: %s\n"
"%s\tTransient: %s\n"
"%s\tSlice: %s\n"
"%s\tCGroup: %s\n"
"%s\tCGroup realized: %s\n"
"%s\tCGroup mask: 0x%x\n"
"%s\tCGroup members mask: 0x%x\n",
prefix, u->id,
prefix, unit_description(u),
prefix, strna(u->instance),
prefix, unit_load_state_to_string(u->load_state),
prefix, unit_active_state_to_string(unit_active_state(u)),
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
prefix, yes_no(unit_check_gc(u)),
prefix, yes_no(unit_need_daemon_reload(u)),
prefix, yes_no(u->transient),
prefix, strna(unit_slice_name(u)),
prefix, strna(u->cgroup_path),
prefix, yes_no(u->cgroup_realized),
prefix, u->cgroup_realized_mask,
prefix, u->cgroup_members_mask);
SET_FOREACH(t, u->names, i)
fprintf(f, "%s\tName: %s\n", prefix, t);
STRV_FOREACH(j, u->documentation)
fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
following = unit_following(u);
if (following)
fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
r = unit_following_set(u, &following_set);
if (r >= 0) {
Unit *other;
SET_FOREACH(other, following_set, i)
fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
}
if (u->fragment_path)
fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
if (u->source_path)
fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
STRV_FOREACH(j, u->dropin_paths)
fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
if (u->job_timeout > 0)
fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
if (u->job_timeout_action != FAILURE_ACTION_NONE)
fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
if (u->job_timeout_reboot_arg)
fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
if (dual_timestamp_is_set(&u->condition_timestamp))
fprintf(f,
"%s\tCondition Timestamp: %s\n"
"%s\tCondition Result: %s\n",
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
prefix, yes_no(u->condition_result));
if (dual_timestamp_is_set(&u->assert_timestamp))
fprintf(f,
"%s\tAssert Timestamp: %s\n"
"%s\tAssert Result: %s\n",
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
prefix, yes_no(u->assert_result));
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
Unit *other;
SET_FOREACH(other, u->dependencies[d], i)
fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
}
if (!strv_isempty(u->requires_mounts_for)) {
fprintf(f,
"%s\tRequiresMountsFor:", prefix);
STRV_FOREACH(j, u->requires_mounts_for)
fprintf(f, " %s", *j);
fputs("\n", f);
}
if (u->load_state == UNIT_LOADED) {
fprintf(f,
"%s\tStopWhenUnneeded: %s\n"
"%s\tRefuseManualStart: %s\n"
"%s\tRefuseManualStop: %s\n"
"%s\tDefaultDependencies: %s\n"
"%s\tOnFailureJobMode: %s\n"
"%s\tIgnoreOnIsolate: %s\n",
prefix, yes_no(u->stop_when_unneeded),
prefix, yes_no(u->refuse_manual_start),
prefix, yes_no(u->refuse_manual_stop),
prefix, yes_no(u->default_dependencies),
prefix, job_mode_to_string(u->on_failure_job_mode),
prefix, yes_no(u->ignore_on_isolate));
if (UNIT_VTABLE(u)->dump)
UNIT_VTABLE(u)->dump(u, f, prefix2);
} else if (u->load_state == UNIT_MERGED)
fprintf(f,
"%s\tMerged into: %s\n",
prefix, u->merged_into->id);
else if (u->load_state == UNIT_ERROR)
fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
if (u->job)
job_dump(u->job, f, prefix2);
if (u->nop_job)
job_dump(u->nop_job, f, prefix2);
}
/* Common implementation for multiple backends */
int unit_load_fragment_and_dropin(Unit *u) {
int r;
assert(u);
/* Load a .{service,socket,...} file */
r = unit_load_fragment(u);
if (r < 0)
return r;
if (u->load_state == UNIT_STUB)
return -ENOENT;
/* Load drop-in directory data */
r = unit_load_dropin(unit_follow_merge(u));
if (r < 0)
return r;
return 0;
}
/* Common implementation for multiple backends */
int unit_load_fragment_and_dropin_optional(Unit *u) {
int r;
assert(u);
/* Same as unit_load_fragment_and_dropin(), but whether
* something can be loaded or not doesn't matter. */
/* Load a .service file */
r = unit_load_fragment(u);
if (r < 0)
return r;
if (u->load_state == UNIT_STUB)
u->load_state = UNIT_LOADED;
/* Load drop-in directory data */
r = unit_load_dropin(unit_follow_merge(u));
if (r < 0)
return r;
return 0;
}
int unit_add_default_target_dependency(Unit *u, Unit *target) {
assert(u);
assert(target);
if (target->type != UNIT_TARGET)
return 0;
/* Only add the dependency if both units are loaded, so that
* that loop check below is reliable */
if (u->load_state != UNIT_LOADED ||
target->load_state != UNIT_LOADED)
return 0;
/* If either side wants no automatic dependencies, then let's
* skip this */
if (!u->default_dependencies ||
!target->default_dependencies)
return 0;
/* Don't create loops */
if (set_get(target->dependencies[UNIT_BEFORE], u))
return 0;
return unit_add_dependency(target, UNIT_AFTER, u, true);
}
static int unit_add_target_dependencies(Unit *u) {
static const UnitDependency deps[] = {
UNIT_REQUIRED_BY,
UNIT_REQUISITE_OF,
UNIT_WANTED_BY,
UNIT_BOUND_BY
};
Unit *target;
Iterator i;
unsigned k;
int r = 0;
assert(u);
for (k = 0; k < ELEMENTSOF(deps); k++)
SET_FOREACH(target, u->dependencies[deps[k]], i) {
r = unit_add_default_target_dependency(u, target);
if (r < 0)
return r;
}
return r;
}
static int unit_add_slice_dependencies(Unit *u) {
assert(u);
if (!UNIT_HAS_CGROUP_CONTEXT(u))
return 0;
if (UNIT_ISSET(u->slice))
return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
if (unit_has_name(u, SPECIAL_ROOT_SLICE))
return 0;
return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
}
static int unit_add_mount_dependencies(Unit *u) {
char **i;
int r;
assert(u);
STRV_FOREACH(i, u->requires_mounts_for) {
char prefix[strlen(*i) + 1];
PATH_FOREACH_PREFIX_MORE(prefix, *i) {
_cleanup_free_ char *p = NULL;
Unit *m;
r = unit_name_from_path(prefix, ".mount", &p);
if (r < 0)
return r;
m = manager_get_unit(u->manager, p);
if (!m) {
/* Make sure to load the mount unit if
* it exists. If so the dependencies
* on this unit will be added later
* during the loading of the mount
* unit. */
(void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
continue;
}
if (m == u)
continue;
if (m->load_state != UNIT_LOADED)
continue;
r = unit_add_dependency(u, UNIT_AFTER, m, true);
if (r < 0)
return r;
if (m->fragment_path) {
r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
if (r < 0)
return r;
}
}
}
return 0;
}
static int unit_add_startup_units(Unit *u) {
CGroupContext *c;
int r;
c = unit_get_cgroup_context(u);
if (!c)
return 0;
if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
return 0;
r = set_ensure_allocated(&u->manager->startup_units, NULL);
if (r < 0)
return r;
return set_put(u->manager->startup_units, u);
}
int unit_load(Unit *u) {
int r;
assert(u);
if (u->in_load_queue) {
LIST_REMOVE(load_queue, u->manager->load_queue, u);
u->in_load_queue = false;
}
if (u->type == _UNIT_TYPE_INVALID)
return -EINVAL;
if (u->load_state != UNIT_STUB)
return 0;
if (UNIT_VTABLE(u)->load) {
r = UNIT_VTABLE(u)->load(u);
if (r < 0)
goto fail;
}
if (u->load_state == UNIT_STUB) {
r = -ENOENT;
goto fail;
}
if (u->load_state == UNIT_LOADED) {
r = unit_add_target_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_slice_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_mount_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_startup_units(u);
if (r < 0)
goto fail;
if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
r = -EINVAL;
goto fail;
}
unit_update_cgroup_members_masks(u);
/* If we are reloading, we need to wait for the deserializer
* to restore the net_cls ids that have been set previously */
if (u->manager->n_reloading <= 0) {
r = unit_add_to_netclass_cgroup(u);
if (r < 0)
return r;
}
}
assert((u->load_state != UNIT_MERGED) == !u->merged_into);
unit_add_to_dbus_queue(unit_follow_merge(u));
unit_add_to_gc_queue(u);
return 0;
fail:
u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
u->load_error = r;
unit_add_to_dbus_queue(u);
unit_add_to_gc_queue(u);
log_unit_debug_errno(u, r, "Failed to load configuration: %m");
return r;
}
static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
Condition *c;
int triggered = -1;
assert(u);
assert(to_string);
/* If the condition list is empty, then it is true */
if (!first)
return true;
/* Otherwise, if all of the non-trigger conditions apply and
* if any of the trigger conditions apply (unless there are
* none) we return true */
LIST_FOREACH(conditions, c, first) {
int r;
r = condition_test(c);
if (r < 0)
log_unit_warning(u,
"Couldn't determine result for %s=%s%s%s, assuming failed: %m",
to_string(c->type),
c->trigger ? "|" : "",
c->negate ? "!" : "",
c->parameter);
else
log_unit_debug(u,
"%s=%s%s%s %s.",
to_string(c->type),
c->trigger ? "|" : "",
c->negate ? "!" : "",
c->parameter,
condition_result_to_string(c->result));
if (!c->trigger && r <= 0)
return false;
if (c->trigger && triggered <= 0)
triggered = r > 0;
}
return triggered != 0;
}
static bool unit_condition_test(Unit *u) {
assert(u);
dual_timestamp_get(&u->condition_timestamp);
u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
return u->condition_result;
}
static bool unit_assert_test(Unit *u) {
assert(u);
dual_timestamp_get(&u->assert_timestamp);
u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
return u->assert_result;
}
_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
const char *format;
const UnitStatusMessageFormats *format_table;
assert(u);
assert(t == JOB_START || t == JOB_STOP || t == JOB_RELOAD);
if (t != JOB_RELOAD) {
format_table = &UNIT_VTABLE(u)->status_message_formats;
if (format_table) {
format = format_table->starting_stopping[t == JOB_STOP];
if (format)
return format;
}
}
/* Return generic strings */
if (t == JOB_START)
return "Starting %s.";
else if (t == JOB_STOP)
return "Stopping %s.";
else
return "Reloading %s.";
}
static void unit_status_print_starting_stopping(Unit *u, JobType t) {
const char *format;
assert(u);
format = unit_get_status_message_format(u, t);
DISABLE_WARNING_FORMAT_NONLITERAL;
unit_status_printf(u, "", format);
REENABLE_WARNING;
}
static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
const char *format;
char buf[LINE_MAX];
sd_id128_t mid;
assert(u);
if (t != JOB_START && t != JOB_STOP && t != JOB_RELOAD)
return;
if (log_on_console())
return;
/* We log status messages for all units and all operations. */
format = unit_get_status_message_format(u, t);
DISABLE_WARNING_FORMAT_NONLITERAL;
snprintf(buf, sizeof(buf), format, unit_description(u));
REENABLE_WARNING;
mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
SD_MESSAGE_UNIT_RELOADING;
/* Note that we deliberately use LOG_MESSAGE() instead of
* LOG_UNIT_MESSAGE() here, since this is supposed to mimic
* closely what is written to screen using the status output,
* which is supposed the highest level, friendliest output
* possible, which means we should avoid the low-level unit
* name. */
log_struct(LOG_INFO,
LOG_MESSAGE_ID(mid),
LOG_UNIT_ID(u),
LOG_MESSAGE("%s", buf),
NULL);
}
void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
unit_status_log_starting_stopping_reloading(u, t);
/* Reload status messages have traditionally not been printed to console. */
if (t != JOB_RELOAD)
unit_status_print_starting_stopping(u, t);
}
/* Errors:
* -EBADR: This unit type does not support starting.
* -EALREADY: Unit is already started.
* -EAGAIN: An operation is already in progress. Retry later.
* -ECANCELED: Too many requests for now.
* -EPROTO: Assert failed
*/
int unit_start(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
/* Units that aren't loaded cannot be started */
if (u->load_state != UNIT_LOADED)
return -EINVAL;
/* If this is already started, then this will succeed. Note
* that this will even succeed if this unit is not startable
* by the user. This is relied on to detect when we need to
* wait for units and when waiting is finished. */
state = unit_active_state(u);
if (UNIT_IS_ACTIVE_OR_RELOADING(state))
return -EALREADY;
/* If the conditions failed, don't do anything at all. If we
* already are activating this call might still be useful to
* speed up activation in case there is some hold-off time,
* but we don't want to recheck the condition in that case. */
if (state != UNIT_ACTIVATING &&
!unit_condition_test(u)) {
log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
return -EALREADY;
}
/* If the asserts failed, fail the entire job */
if (state != UNIT_ACTIVATING &&
!unit_assert_test(u)) {
log_unit_notice(u, "Starting requested but asserts failed.");
return -EPROTO;
}
/* Units of types that aren't supported cannot be
* started. Note that we do this test only after the condition
* checks, so that we rather return condition check errors
* (which are usually not considered a true failure) than "not
* supported" errors (which are considered a failure).
*/
if (!unit_supported(u))
return -EOPNOTSUPP;
/* Forward to the main object, if we aren't it. */
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
return unit_start(following);
}
/* If it is stopped, but we cannot start it, then fail */
if (!UNIT_VTABLE(u)->start)
return -EBADR;
/* We don't suppress calls to ->start() here when we are
* already starting, to allow this request to be used as a
* "hurry up" call, for example when the unit is in some "auto
* restart" state where it waits for a holdoff timer to elapse
* before it will start again. */
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->start(u);
}
bool unit_can_start(Unit *u) {
assert(u);
if (u->load_state != UNIT_LOADED)
return false;
if (!unit_supported(u))
return false;
return !!UNIT_VTABLE(u)->start;
}
bool unit_can_isolate(Unit *u) {
assert(u);
return unit_can_start(u) &&
u->allow_isolate;
}
/* Errors:
* -EBADR: This unit type does not support stopping.
* -EALREADY: Unit is already stopped.
* -EAGAIN: An operation is already in progress. Retry later.
*/
int unit_stop(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
state = unit_active_state(u);
if (UNIT_IS_INACTIVE_OR_FAILED(state))
return -EALREADY;
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
return unit_stop(following);
}
if (!UNIT_VTABLE(u)->stop)
return -EBADR;
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->stop(u);
}
/* Errors:
* -EBADR: This unit type does not support reloading.
* -ENOEXEC: Unit is not started.
* -EAGAIN: An operation is already in progress. Retry later.
*/
int unit_reload(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
if (u->load_state != UNIT_LOADED)
return -EINVAL;
if (!unit_can_reload(u))
return -EBADR;
state = unit_active_state(u);
if (state == UNIT_RELOADING)
return -EALREADY;
if (state != UNIT_ACTIVE) {
log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
return -ENOEXEC;
}
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
return unit_reload(following);
}
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->reload(u);
}
bool unit_can_reload(Unit *u) {
assert(u);
if (!UNIT_VTABLE(u)->reload)
return false;
if (!UNIT_VTABLE(u)->can_reload)
return true;
return UNIT_VTABLE(u)->can_reload(u);
}
static void unit_check_unneeded(Unit *u) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
static const UnitDependency needed_dependencies[] = {
UNIT_REQUIRED_BY,
UNIT_REQUISITE_OF,
UNIT_WANTED_BY,
UNIT_BOUND_BY,
};
Unit *other;
Iterator i;
unsigned j;
int r;
assert(u);
/* If this service shall be shut down when unneeded then do
* so. */
if (!u->stop_when_unneeded)
return;
if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
return;
for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
if (unit_active_or_pending(other))
return;
/* If stopping a unit fails continously we might enter a stop
* loop here, hence stop acting on the service being
* unnecessary after a while. */
if (!ratelimit_test(&u->auto_stop_ratelimit)) {
log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
return;
}
log_unit_info(u, "Unit not needed anymore. Stopping.");
/* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
if (r < 0)
log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
}
static void unit_check_binds_to(Unit *u) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
bool stop = false;
Unit *other;
Iterator i;
int r;
assert(u);
if (u->job)
return;
if (unit_active_state(u) != UNIT_ACTIVE)
return;
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
if (other->job)
continue;
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
continue;
stop = true;
break;
}
if (!stop)
return;
/* If stopping a unit fails continously we might enter a stop
* loop here, hence stop acting on the service being
* unnecessary after a while. */
if (!ratelimit_test(&u->auto_stop_ratelimit)) {
log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
return;
}
assert(other);
log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
/* A unit we need to run is gone. Sniff. Let's stop this. */
r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
if (r < 0)
log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
}
static void retroactively_start_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
}
static void retroactively_stop_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
/* Pull down units which are bound to us recursively if enabled */
SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
}
static void check_unneeded_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
/* Garbage collect services that might not be needed anymore, if enabled */
SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
}
void unit_start_on_failure(Unit *u) {
Unit *other;
Iterator i;
assert(u);
if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
return;
log_unit_info(u, "Triggering OnFailure= dependencies.");
SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
int r;
r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
if (r < 0)
log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
}
}
void unit_trigger_notify(Unit *u) {
Unit *other;
Iterator i;
assert(u);
SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
if (UNIT_VTABLE(other)->trigger_notify)
UNIT_VTABLE(other)->trigger_notify(other, u);
}
void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
Manager *m;
bool unexpected;
assert(u);
assert(os < _UNIT_ACTIVE_STATE_MAX);
assert(ns < _UNIT_ACTIVE_STATE_MAX);
/* Note that this is called for all low-level state changes,
* even if they might map to the same high-level
* UnitActiveState! That means that ns == os is an expected
* behavior here. For example: if a mount point is remounted
* this function will be called too! */
m = u->manager;
/* Update timestamps for state changes */
if (m->n_reloading <= 0) {
dual_timestamp ts;
dual_timestamp_get(&ts);
if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_exit_timestamp = ts;
else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_enter_timestamp = ts;
if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_enter_timestamp = ts;
else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_exit_timestamp = ts;
}
/* Keep track of failed units */
(void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
/* Make sure the cgroup is always removed when we become inactive */
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
unit_prune_cgroup(u);
/* Note that this doesn't apply to RemainAfterExit services exiting
* successfully, since there's no change of state in that case. Which is
* why it is handled in service_set_state() */
if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
ExecContext *ec;
ec = unit_get_exec_context(u);
if (ec && exec_context_may_touch_console(ec)) {
if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
m->n_on_console --;
if (m->n_on_console == 0)
/* unset no_console_output flag, since the console is free */
m->no_console_output = false;
} else
m->n_on_console ++;
}
}
if (u->job) {
unexpected = false;
if (u->job->state == JOB_WAITING)
/* So we reached a different state for this
* job. Let's see if we can run it now if it
* failed previously due to EAGAIN. */
job_add_to_run_queue(u->job);
/* Let's check whether this state change constitutes a
* finished job, or maybe contradicts a running job and
* hence needs to invalidate jobs. */
switch (u->job->type) {
case JOB_START:
case JOB_VERIFY_ACTIVE:
if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
job_finish_and_invalidate(u->job, JOB_DONE, true);
else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
unexpected = true;
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
}
break;
case JOB_RELOAD:
case JOB_RELOAD_OR_START:
if (u->job->state == JOB_RUNNING) {
if (ns == UNIT_ACTIVE)
job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
unexpected = true;
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
}
}
break;
case JOB_STOP:
case JOB_RESTART:
case JOB_TRY_RESTART:
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, JOB_DONE, true);
else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
unexpected = true;
job_finish_and_invalidate(u->job, JOB_FAILED, true);
}
break;
default:
assert_not_reached("Job type unknown");
}
} else
unexpected = true;
if (m->n_reloading <= 0) {
/* If this state change happened without being
* requested by a job, then let's retroactively start
* or stop dependencies. We skip that step when
* deserializing, since we don't want to create any
* additional jobs just because something is already
* activated. */
if (unexpected) {
if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
retroactively_start_dependencies(u);
else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
retroactively_stop_dependencies(u);
}
/* stop unneeded units regardless if going down was expected or not */
if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
check_unneeded_dependencies(u);
if (ns != os && ns == UNIT_FAILED) {
log_unit_notice(u, "Unit entered failed state.");
unit_start_on_failure(u);
}
}
/* Some names are special */
if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
/* The bus might have just become available,
* hence try to connect to it, if we aren't
* yet connected. */
bus_init(m, true);
if (u->type == UNIT_SERVICE &&
!UNIT_IS_ACTIVE_OR_RELOADING(os) &&
m->n_reloading <= 0) {
/* Write audit record if we have just finished starting up */
manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
u->in_audit = true;
}
if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
manager_send_unit_plymouth(m, u);
} else {
/* We don't care about D-Bus here, since we'll get an
* asynchronous notification for it anyway. */
if (u->type == UNIT_SERVICE &&
UNIT_IS_INACTIVE_OR_FAILED(ns) &&
!UNIT_IS_INACTIVE_OR_FAILED(os) &&
m->n_reloading <= 0) {
/* Hmm, if there was no start record written
* write it now, so that we always have a nice
* pair */
if (!u->in_audit) {
manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
if (ns == UNIT_INACTIVE)
manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
} else
/* Write audit record if we have just finished shutting down */
manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
u->in_audit = false;
}
}
manager_recheck_journal(m);
unit_trigger_notify(u);
if (u->manager->n_reloading <= 0) {
/* Maybe we finished startup and are now ready for
* being stopped because unneeded? */
unit_check_unneeded(u);
/* Maybe we finished startup, but something we needed
* has vanished? Let's die then. (This happens when
* something BindsTo= to a Type=oneshot unit, as these
* units go directly from starting to inactive,
* without ever entering started.) */
unit_check_binds_to(u);
}
unit_add_to_dbus_queue(u);
unit_add_to_gc_queue(u);
}
int unit_watch_pid(Unit *u, pid_t pid) {
int q, r;
assert(u);
assert(pid >= 1);
/* Watch a specific PID. We only support one or two units
* watching each PID for now, not more. */
r = set_ensure_allocated(&u->pids, NULL);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
if (r < 0)
return r;
r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
if (r == -EEXIST) {
r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
if (r < 0)
return r;
r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
}
q = set_put(u->pids, PID_TO_PTR(pid));
if (q < 0)
return q;
return r;
}
void unit_unwatch_pid(Unit *u, pid_t pid) {
assert(u);
assert(pid >= 1);
(void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
(void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
(void) set_remove(u->pids, PID_TO_PTR(pid));
}
void unit_unwatch_all_pids(Unit *u) {
assert(u);
while (!set_isempty(u->pids))
unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
u->pids = set_free(u->pids);
}
void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
Iterator i;
void *e;
assert(u);
/* Cleans dead PIDs from our list */
SET_FOREACH(e, u->pids, i) {
pid_t pid = PTR_TO_PID(e);
if (pid == except1 || pid == except2)
continue;
if (!pid_is_unwaited(pid))
unit_unwatch_pid(u, pid);
}
}
bool unit_job_is_applicable(Unit *u, JobType j) {
assert(u);
assert(j >= 0 && j < _JOB_TYPE_MAX);
switch (j) {
case JOB_VERIFY_ACTIVE:
case JOB_START:
case JOB_STOP:
case JOB_NOP:
return true;
case JOB_RESTART:
case JOB_TRY_RESTART:
return unit_can_start(u);
case JOB_RELOAD:
return unit_can_reload(u);
case JOB_RELOAD_OR_START:
return unit_can_reload(u) && unit_can_start(u);
default:
assert_not_reached("Invalid job type");
}
}
static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
assert(u);
/* Only warn about some unit types */
if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
return;
if (streq_ptr(u->id, other))
log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
else
log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
}
int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
[UNIT_REQUIRES] = UNIT_REQUIRED_BY,
[UNIT_WANTS] = UNIT_WANTED_BY,
[UNIT_REQUISITE] = UNIT_REQUISITE_OF,
[UNIT_BINDS_TO] = UNIT_BOUND_BY,
[UNIT_PART_OF] = UNIT_CONSISTS_OF,
[UNIT_REQUIRED_BY] = UNIT_REQUIRES,
[UNIT_REQUISITE_OF] = UNIT_REQUISITE,
[UNIT_WANTED_BY] = UNIT_WANTS,
[UNIT_BOUND_BY] = UNIT_BINDS_TO,
[UNIT_CONSISTS_OF] = UNIT_PART_OF,
[UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
[UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
[UNIT_BEFORE] = UNIT_AFTER,
[UNIT_AFTER] = UNIT_BEFORE,
[UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
[UNIT_REFERENCES] = UNIT_REFERENCED_BY,
[UNIT_REFERENCED_BY] = UNIT_REFERENCES,
[UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
[UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
[UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
[UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
[UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
};
int r, q = 0, v = 0, w = 0;
Unit *orig_u = u, *orig_other = other;
assert(u);
assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
assert(other);
u = unit_follow_merge(u);
other = unit_follow_merge(other);
/* We won't allow dependencies on ourselves. We will not
* consider them an error however. */
if (u == other) {
maybe_warn_about_dependency(orig_u, orig_other->id, d);
return 0;
}
r = set_ensure_allocated(&u->dependencies[d], NULL);
if (r < 0)
return r;
if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
if (r < 0)
return r;
}
if (add_reference) {
r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
if (r < 0)
return r;
r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
if (r < 0)
return r;
}
q = set_put(u->dependencies[d], other);
if (q < 0)
return q;
if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
v = set_put(other->dependencies[inverse_table[d]], u);
if (v < 0) {
r = v;
goto fail;
}
}
if (add_reference) {
w = set_put(u->dependencies[UNIT_REFERENCES], other);
if (w < 0) {
r = w;
goto fail;
}
r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
if (r < 0)
goto fail;
}
unit_add_to_dbus_queue(u);
return 0;
fail:
if (q > 0)
set_remove(u->dependencies[d], other);
if (v > 0)
set_remove(other->dependencies[inverse_table[d]], u);
if (w > 0)
set_remove(u->dependencies[UNIT_REFERENCES], other);
return r;
}
int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
int r;
assert(u);
r = unit_add_dependency(u, d, other, add_reference);
if (r < 0)
return r;
return unit_add_dependency(u, e, other, add_reference);
}
static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
int r;
assert(u);
assert(name || path);
assert(buf);
assert(ret);
if (!name)
name = basename(path);
if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
*buf = NULL;
*ret = name;
return 0;
}
if (u->instance)
r = unit_name_replace_instance(name, u->instance, buf);
else {
_cleanup_free_ char *i = NULL;
r = unit_name_to_prefix(u->id, &i);
if (r < 0)
return r;
r = unit_name_replace_instance(name, i, buf);
}
if (r < 0)
return r;
*ret = *buf;
return 0;
}
int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
_cleanup_free_ char *buf = NULL;
Unit *other;
int r;
assert(u);
assert(name || path);
r = resolve_template(u, name, path, &buf, &name);
if (r < 0)
return r;
r = manager_load_unit(u->manager, name, path, NULL, &other);
if (r < 0)
return r;
return unit_add_dependency(u, d, other, add_reference);
}
int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
_cleanup_free_ char *buf = NULL;
Unit *other;
int r;
assert(u);
assert(name || path);
r = resolve_template(u, name, path, &buf, &name);
if (r < 0)
return r;
r = manager_load_unit(u->manager, name, path, NULL, &other);
if (r < 0)
return r;
return unit_add_two_dependencies(u, d, e, other, add_reference);
}
int set_unit_path(const char *p) {
/* This is mostly for debug purposes */
if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
return -errno;
return 0;
}
char *unit_dbus_path(Unit *u) {
assert(u);
if (!u->id)
return NULL;
return unit_dbus_path_from_name(u->id);
}
int unit_set_slice(Unit *u, Unit *slice) {
assert(u);
assert(slice);
/* Sets the unit slice if it has not been set before. Is extra
* careful, to only allow this for units that actually have a
* cgroup context. Also, we don't allow to set this for slices
* (since the parent slice is derived from the name). Make
* sure the unit we set is actually a slice. */
if (!UNIT_HAS_CGROUP_CONTEXT(u))
return -EOPNOTSUPP;
if (u->type == UNIT_SLICE)
return -EINVAL;
if (unit_active_state(u) != UNIT_INACTIVE)
return -EBUSY;
if (slice->type != UNIT_SLICE)
return -EINVAL;
if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
!unit_has_name(slice, SPECIAL_ROOT_SLICE))
return -EPERM;
if (UNIT_DEREF(u->slice) == slice)
return 0;
if (UNIT_ISSET(u->slice))
return -EBUSY;
unit_ref_set(&u->slice, slice);
return 1;
}
int unit_set_default_slice(Unit *u) {
_cleanup_free_ char *b = NULL;
const char *slice_name;
Unit *slice;
int r;
assert(u);
if (UNIT_ISSET(u->slice))
return 0;
if (u->instance) {
_cleanup_free_ char *prefix = NULL, *escaped = NULL;
/* Implicitly place all instantiated units in their
* own per-template slice */
r = unit_name_to_prefix(u->id, &prefix);
if (r < 0)
return r;
/* The prefix is already escaped, but it might include
* "-" which has a special meaning for slice units,
* hence escape it here extra. */
escaped = unit_name_escape(prefix);
if (!escaped)
return -ENOMEM;
if (u->manager->running_as == MANAGER_SYSTEM)
b = strjoin("system-", escaped, ".slice", NULL);
else
b = strappend(escaped, ".slice");
if (!b)
return -ENOMEM;
slice_name = b;
} else
slice_name =
u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
? SPECIAL_SYSTEM_SLICE
: SPECIAL_ROOT_SLICE;
r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
if (r < 0)
return r;
return unit_set_slice(u, slice);
}
const char *unit_slice_name(Unit *u) {
assert(u);
if (!UNIT_ISSET(u->slice))
return NULL;
return UNIT_DEREF(u->slice)->id;
}
int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
_cleanup_free_ char *t = NULL;
int r;
assert(u);
assert(type);
assert(_found);
r = unit_name_change_suffix(u->id, type, &t);
if (r < 0)
return r;
if (unit_has_name(u, t))
return -EINVAL;
r = manager_load_unit(u->manager, t, NULL, NULL, _found);
assert(r < 0 || *_found != u);
return r;
}
static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
const char *name, *old_owner, *new_owner;
Unit *u = userdata;
int r;
assert(message);
assert(u);
r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
if (r < 0) {
bus_log_parse_error(r);
return 0;
}
if (UNIT_VTABLE(u)->bus_name_owner_change)
UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
return 0;
}
int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
const char *match;
assert(u);
assert(bus);
assert(name);
if (u->match_bus_slot)
return -EBUSY;
match = strjoina("type='signal',"
"sender='org.freedesktop.DBus',"
"path='/org/freedesktop/DBus',"
"interface='org.freedesktop.DBus',"
"member='NameOwnerChanged',"
"arg0='", name, "'",
NULL);
return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
}
int unit_watch_bus_name(Unit *u, const char *name) {
int r;
assert(u);
assert(name);
/* Watch a specific name on the bus. We only support one unit
* watching each name for now. */
if (u->manager->api_bus) {
/* If the bus is already available, install the match directly.
* Otherwise, just put the name in the list. bus_setup_api() will take care later. */
r = unit_install_bus_match(u, u->manager->api_bus, name);
if (r < 0)
return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
}
r = hashmap_put(u->manager->watch_bus, name, u);
if (r < 0) {
u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
}
return 0;
}
void unit_unwatch_bus_name(Unit *u, const char *name) {
assert(u);
assert(name);
hashmap_remove_value(u->manager->watch_bus, name, u);
u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
}
bool unit_can_serialize(Unit *u) {
assert(u);
return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
}
int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
int r;
assert(u);
assert(f);
assert(fds);
if (unit_can_serialize(u)) {
ExecRuntime *rt;
r = UNIT_VTABLE(u)->serialize(u, f, fds);
if (r < 0)
return r;
rt = unit_get_exec_runtime(u);
if (rt) {
r = exec_runtime_serialize(u, rt, f, fds);
if (r < 0)
return r;
}
}
dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
if (dual_timestamp_is_set(&u->condition_timestamp))
unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
if (dual_timestamp_is_set(&u->assert_timestamp))
unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
unit_serialize_item(u, f, "transient", yes_no(u->transient));
unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
if (u->cgroup_path)
unit_serialize_item(u, f, "cgroup", u->cgroup_path);
unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
if (u->cgroup_netclass_id)
unit_serialize_item_format(u, f, "netclass-id", "%" PRIu32, u->cgroup_netclass_id);
if (serialize_jobs) {
if (u->job) {
fprintf(f, "job\n");
job_serialize(u->job, f, fds);
}
if (u->nop_job) {
fprintf(f, "job\n");
job_serialize(u->nop_job, f, fds);
}
}
/* End marker */
fputc('\n', f);
return 0;
}
int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
assert(u);
assert(f);
assert(key);
if (!value)
return 0;
fputs(key, f);
fputc('=', f);
fputs(value, f);
fputc('\n', f);
return 1;
}
int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
_cleanup_free_ char *c = NULL;
assert(u);
assert(f);
assert(key);
if (!value)
return 0;
c = cescape(value);
if (!c)
return -ENOMEM;
fputs(key, f);
fputc('=', f);
fputs(c, f);
fputc('\n', f);
return 1;
}
int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
int copy;
assert(u);
assert(f);
assert(key);
if (fd < 0)
return 0;
copy = fdset_put_dup(fds, fd);
if (copy < 0)
return copy;
fprintf(f, "%s=%i\n", key, copy);
return 1;
}
void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
va_list ap;
assert(u);
assert(f);
assert(key);
assert(format);
fputs(key, f);
fputc('=', f);
va_start(ap, format);
vfprintf(f, format, ap);
va_end(ap);
fputc('\n', f);
}
int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
ExecRuntime **rt = NULL;
size_t offset;
int r;
assert(u);
assert(f);
assert(fds);
offset = UNIT_VTABLE(u)->exec_runtime_offset;
if (offset > 0)
rt = (ExecRuntime**) ((uint8_t*) u + offset);
for (;;) {
char line[LINE_MAX], *l, *v;
size_t k;
if (!fgets(line, sizeof(line), f)) {
if (feof(f))
return 0;
return -errno;
}
char_array_0(line);
l = strstrip(line);
/* End marker */
if (isempty(l))
return 0;
k = strcspn(l, "=");
if (l[k] == '=') {
l[k] = 0;
v = l+k+1;
} else
v = l+k;
if (streq(l, "job")) {
if (v[0] == '\0') {
/* new-style serialized job */
Job *j;
j = job_new_raw(u);
if (!j)
return log_oom();
r = job_deserialize(j, f, fds);
if (r < 0) {
job_free(j);
return r;
}
r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
if (r < 0) {
job_free(j);
return r;
}
r = job_install_deserialized(j);
if (r < 0) {
hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
job_free(j);
return r;
}
} else /* legacy for pre-44 */
log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
continue;
} else if (streq(l, "inactive-exit-timestamp")) {
dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
continue;
} else if (streq(l, "active-enter-timestamp")) {
dual_timestamp_deserialize(v, &u->active_enter_timestamp);
continue;
} else if (streq(l, "active-exit-timestamp")) {
dual_timestamp_deserialize(v, &u->active_exit_timestamp);
continue;
} else if (streq(l, "inactive-enter-timestamp")) {
dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
continue;
} else if (streq(l, "condition-timestamp")) {
dual_timestamp_deserialize(v, &u->condition_timestamp);
continue;
} else if (streq(l, "assert-timestamp")) {
dual_timestamp_deserialize(v, &u->assert_timestamp);
continue;
} else if (streq(l, "condition-result")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
else
u->condition_result = r;
continue;
} else if (streq(l, "assert-result")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
else
u->assert_result = r;
continue;
} else if (streq(l, "transient")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
else
u->transient = r;
continue;
} else if (streq(l, "cpuacct-usage-base")) {
r = safe_atou64(v, &u->cpuacct_usage_base);
if (r < 0)
log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
continue;
} else if (streq(l, "cgroup")) {
r = unit_set_cgroup_path(u, v);
if (r < 0)
log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
(void) unit_watch_cgroup(u);
continue;
} else if (streq(l, "cgroup-realized")) {
int b;
b = parse_boolean(v);
if (b < 0)
log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
else
u->cgroup_realized = b;
continue;
} else if (streq(l, "netclass-id")) {
r = safe_atou32(v, &u->cgroup_netclass_id);
if (r < 0)
log_unit_debug(u, "Failed to parse netclass ID %s, ignoring.", v);
else {
r = unit_add_to_netclass_cgroup(u);
if (r < 0)
log_unit_debug_errno(u, r, "Failed to add unit to netclass cgroup, ignoring: %m");
}
continue;
}
if (unit_can_serialize(u)) {
if (rt) {
r = exec_runtime_deserialize_item(u, rt, l, v, fds);
if (r < 0) {
log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
continue;
}
/* Returns positive if key was handled by the call */
if (r > 0)
continue;
}
r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
if (r < 0)
log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
}
}
}
int unit_add_node_link(Unit *u, const char *what, bool wants) {
Unit *device;
_cleanup_free_ char *e = NULL;
int r;
assert(u);
/* Adds in links to the device node that this unit is based on */
if (isempty(what))
return 0;
if (!is_device_path(what))
return 0;
/* When device units aren't supported (such as in a
* container), don't create dependencies on them. */
if (!unit_type_supported(UNIT_DEVICE))
return 0;
r = unit_name_from_path(what, ".device", &e);
if (r < 0)
return r;
r = manager_load_unit(u->manager, e, NULL, NULL, &device);
if (r < 0)
return r;
r = unit_add_two_dependencies(u, UNIT_AFTER, u->manager->running_as == MANAGER_SYSTEM ? UNIT_BINDS_TO : UNIT_WANTS, device, true);
if (r < 0)
return r;
if (wants) {
r = unit_add_dependency(device, UNIT_WANTS, u, false);
if (r < 0)
return r;
}
return 0;
}
int unit_coldplug(Unit *u) {
int r = 0, q = 0;
assert(u);
/* Make sure we don't enter a loop, when coldplugging
* recursively. */
if (u->coldplugged)
return 0;
u->coldplugged = true;
if (UNIT_VTABLE(u)->coldplug)
r = UNIT_VTABLE(u)->coldplug(u);
if (u->job)
q = job_coldplug(u->job);
if (r < 0)
return r;
if (q < 0)
return q;
return 0;
}
void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
DISABLE_WARNING_FORMAT_NONLITERAL;
manager_status_printf(u->manager, STATUS_TYPE_NORMAL,
status, unit_status_msg_format, unit_description(u));
REENABLE_WARNING;
}
bool unit_need_daemon_reload(Unit *u) {
_cleanup_strv_free_ char **t = NULL;
char **path;
struct stat st;
unsigned loaded_cnt, current_cnt;
assert(u);
if (u->fragment_path) {
zero(st);
if (stat(u->fragment_path, &st) < 0)
/* What, cannot access this anymore? */
return true;
if (u->fragment_mtime > 0 &&
timespec_load(&st.st_mtim) != u->fragment_mtime)
return true;
}
if (u->source_path) {
zero(st);
if (stat(u->source_path, &st) < 0)
return true;
if (u->source_mtime > 0 &&
timespec_load(&st.st_mtim) != u->source_mtime)
return true;
}
(void) unit_find_dropin_paths(u, &t);
loaded_cnt = strv_length(t);
current_cnt = strv_length(u->dropin_paths);
if (loaded_cnt == current_cnt) {
if (loaded_cnt == 0)
return false;
if (strv_overlap(u->dropin_paths, t)) {
STRV_FOREACH(path, u->dropin_paths) {
zero(st);
if (stat(*path, &st) < 0)
return true;
if (u->dropin_mtime > 0 &&
timespec_load(&st.st_mtim) > u->dropin_mtime)
return true;
}
return false;
} else
return true;
} else
return true;
}
void unit_reset_failed(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->reset_failed)
UNIT_VTABLE(u)->reset_failed(u);
}
Unit *unit_following(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->following)
return UNIT_VTABLE(u)->following(u);
return NULL;
}
bool unit_stop_pending(Unit *u) {
assert(u);
/* This call does check the current state of the unit. It's
* hence useful to be called from state change calls of the
* unit itself, where the state isn't updated yet. This is
* different from unit_inactive_or_pending() which checks both
* the current state and for a queued job. */
return u->job && u->job->type == JOB_STOP;
}
bool unit_inactive_or_pending(Unit *u) {
assert(u);
/* Returns true if the unit is inactive or going down */
if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
return true;
if (unit_stop_pending(u))
return true;
return false;
}
bool unit_active_or_pending(Unit *u) {
assert(u);
/* Returns true if the unit is active or going up */
if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
return true;
if (u->job &&
(u->job->type == JOB_START ||
u->job->type == JOB_RELOAD_OR_START ||
u->job->type == JOB_RESTART))
return true;
return false;
}
int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
assert(u);
assert(w >= 0 && w < _KILL_WHO_MAX);
assert(signo > 0);
assert(signo < _NSIG);
if (!UNIT_VTABLE(u)->kill)
return -EOPNOTSUPP;
return UNIT_VTABLE(u)->kill(u, w, signo, error);
}
static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
Set *pid_set;
int r;
pid_set = set_new(NULL);
if (!pid_set)
return NULL;
/* Exclude the main/control pids from being killed via the cgroup */
if (main_pid > 0) {
r = set_put(pid_set, PID_TO_PTR(main_pid));
if (r < 0)
goto fail;
}
if (control_pid > 0) {
r = set_put(pid_set, PID_TO_PTR(control_pid));
if (r < 0)
goto fail;
}
return pid_set;
fail:
set_free(pid_set);
return NULL;
}
int unit_kill_common(
Unit *u,
KillWho who,
int signo,
pid_t main_pid,
pid_t control_pid,
sd_bus_error *error) {
int r = 0;
bool killed = false;
if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
if (main_pid < 0)
return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
else if (main_pid == 0)
return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
}
if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
if (control_pid < 0)
return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
else if (control_pid == 0)
return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
}
if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
if (control_pid > 0) {
if (kill(control_pid, signo) < 0)
r = -errno;
else
killed = true;
}
if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
if (main_pid > 0) {
if (kill(main_pid, signo) < 0)
r = -errno;
else
killed = true;
}
if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
_cleanup_set_free_ Set *pid_set = NULL;
int q;
/* Exclude the main/control pids from being killed via the cgroup */
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set);
if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
r = q;
else
killed = true;
}
if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_ALL_FAIL))
return -ESRCH;
return r;
}
int unit_following_set(Unit *u, Set **s) {
assert(u);
assert(s);
if (UNIT_VTABLE(u)->following_set)
return UNIT_VTABLE(u)->following_set(u, s);
*s = NULL;
return 0;
}
UnitFileState unit_get_unit_file_state(Unit *u) {
int r;
assert(u);
if (u->unit_file_state < 0 && u->fragment_path) {
r = unit_file_get_state(
u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
NULL,
basename(u->fragment_path),
&u->unit_file_state);
if (r < 0)
u->unit_file_state = UNIT_FILE_BAD;
}
return u->unit_file_state;
}
int unit_get_unit_file_preset(Unit *u) {
assert(u);
if (u->unit_file_preset < 0 && u->fragment_path)
u->unit_file_preset = unit_file_query_preset(
u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
NULL,
basename(u->fragment_path));
return u->unit_file_preset;
}
Unit* unit_ref_set(UnitRef *ref, Unit *u) {
assert(ref);
assert(u);
if (ref->unit)
unit_ref_unset(ref);
ref->unit = u;
LIST_PREPEND(refs, u->refs, ref);
return u;
}
void unit_ref_unset(UnitRef *ref) {
assert(ref);
if (!ref->unit)
return;
LIST_REMOVE(refs, ref->unit->refs, ref);
ref->unit = NULL;
}
int unit_patch_contexts(Unit *u) {
CGroupContext *cc;
ExecContext *ec;
unsigned i;
int r;
assert(u);
/* Patch in the manager defaults into the exec and cgroup
* contexts, _after_ the rest of the settings have been
* initialized */
ec = unit_get_exec_context(u);
if (ec) {
/* This only copies in the ones that need memory */
for (i = 0; i < _RLIMIT_MAX; i++)
if (u->manager->rlimit[i] && !ec->rlimit[i]) {
ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
if (!ec->rlimit[i])
return -ENOMEM;
}
if (u->manager->running_as == MANAGER_USER &&
!ec->working_directory) {
r = get_home_dir(&ec->working_directory);
if (r < 0)
return r;
/* Allow user services to run, even if the
* home directory is missing */
ec->working_directory_missing_ok = true;
}
if (u->manager->running_as == MANAGER_USER &&
(ec->syscall_whitelist ||
!set_isempty(ec->syscall_filter) ||
!set_isempty(ec->syscall_archs) ||
ec->address_families_whitelist ||
!set_isempty(ec->address_families)))
ec->no_new_privileges = true;
if (ec->private_devices)
ec->capability_bounding_set_drop |= (uint64_t) 1ULL << (uint64_t) CAP_MKNOD;
}
cc = unit_get_cgroup_context(u);
if (cc) {
if (ec &&
ec->private_devices &&
cc->device_policy == CGROUP_AUTO)
cc->device_policy = CGROUP_CLOSED;
}
return 0;
}
ExecContext *unit_get_exec_context(Unit *u) {
size_t offset;
assert(u);
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->exec_context_offset;
if (offset <= 0)
return NULL;
return (ExecContext*) ((uint8_t*) u + offset);
}
KillContext *unit_get_kill_context(Unit *u) {
size_t offset;
assert(u);
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->kill_context_offset;
if (offset <= 0)
return NULL;
return (KillContext*) ((uint8_t*) u + offset);
}
CGroupContext *unit_get_cgroup_context(Unit *u) {
size_t offset;
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->cgroup_context_offset;
if (offset <= 0)
return NULL;
return (CGroupContext*) ((uint8_t*) u + offset);
}
ExecRuntime *unit_get_exec_runtime(Unit *u) {
size_t offset;
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->exec_runtime_offset;
if (offset <= 0)
return NULL;
return *(ExecRuntime**) ((uint8_t*) u + offset);
}
static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) {
assert(u);
if (u->manager->running_as == MANAGER_USER) {
int r;
if (mode == UNIT_PERSISTENT && !transient)
r = user_config_home(dir);
else
r = user_runtime_dir(dir);
if (r == 0)
return -ENOENT;
return r;
}
if (mode == UNIT_PERSISTENT && !transient)
*dir = strdup("/etc/systemd/system");
else
*dir = strdup("/run/systemd/system");
if (!*dir)
return -ENOMEM;
return 0;
}
int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
_cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL;
int r;
assert(u);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
r = unit_drop_in_dir(u, mode, u->transient, &dir);
if (r < 0)
return r;
r = write_drop_in(dir, u->id, 50, name, data);
if (r < 0)
return r;
r = drop_in_file(dir, u->id, 50, name, &p, &q);
if (r < 0)
return r;
r = strv_extend(&u->dropin_paths, q);
if (r < 0)
return r;
strv_sort(u->dropin_paths);
strv_uniq(u->dropin_paths);
u->dropin_mtime = now(CLOCK_REALTIME);
return 0;
}
int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(u);
assert(name);
assert(format);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return unit_write_drop_in(u, mode, name, p);
}
int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
_cleanup_free_ char *ndata = NULL;
assert(u);
assert(name);
assert(data);
if (!UNIT_VTABLE(u)->private_section)
return -EINVAL;
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL);
if (!ndata)
return -ENOMEM;
return unit_write_drop_in(u, mode, name, ndata);
}
int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(u);
assert(name);
assert(format);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return unit_write_drop_in_private(u, mode, name, p);
}
int unit_make_transient(Unit *u) {
assert(u);
if (!UNIT_VTABLE(u)->can_transient)
return -EOPNOTSUPP;
u->load_state = UNIT_STUB;
u->load_error = 0;
u->transient = true;
u->fragment_path = mfree(u->fragment_path);
return 0;
}
int unit_kill_context(
Unit *u,
KillContext *c,
KillOperation k,
pid_t main_pid,
pid_t control_pid,
bool main_pid_alien) {
bool wait_for_exit = false;
int sig, r;
assert(u);
assert(c);
if (c->kill_mode == KILL_NONE)
return 0;
switch (k) {
case KILL_KILL:
sig = SIGKILL;
break;
case KILL_ABORT:
sig = SIGABRT;
break;
case KILL_TERMINATE:
sig = c->kill_signal;
break;
default:
assert_not_reached("KillOperation unknown");
}
if (main_pid > 0) {
r = kill_and_sigcont(main_pid, sig);
if (r < 0 && r != -ESRCH) {
_cleanup_free_ char *comm = NULL;
get_process_comm(main_pid, &comm);
log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
} else {
if (!main_pid_alien)
wait_for_exit = true;
if (c->send_sighup && k == KILL_TERMINATE)
(void) kill(main_pid, SIGHUP);
}
}
if (control_pid > 0) {
r = kill_and_sigcont(control_pid, sig);
if (r < 0 && r != -ESRCH) {
_cleanup_free_ char *comm = NULL;
get_process_comm(control_pid, &comm);
log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
} else {
wait_for_exit = true;
if (c->send_sighup && k == KILL_TERMINATE)
(void) kill(control_pid, SIGHUP);
}
}
if (u->cgroup_path &&
(c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
_cleanup_set_free_ Set *pid_set = NULL;
/* Exclude the main/control pids from being killed via the cgroup */
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set);
if (r < 0) {
if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
} else if (r > 0) {
/* FIXME: For now, on the legacy hierarchy, we
* will not wait for the cgroup members to die
* if we are running in a container or if this
* is a delegation unit, simply because cgroup
* notification is unreliable in these
* cases. It doesn't work at all in
* containers, and outside of containers it
* can be confused easily by left-over
* directories in the cgroup -- which however
* should not exist in non-delegated units. On
* the unified hierarchy that's different,
* there we get proper events. Hence rely on
* them.*/
if (cg_unified() > 0 ||
(detect_container() == 0 && !unit_cgroup_delegate(u)))
wait_for_exit = true;
if (c->send_sighup && k != KILL_KILL) {
set_free(pid_set);
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set);
}
}
}
return wait_for_exit;
}
int unit_require_mounts_for(Unit *u, const char *path) {
char prefix[strlen(path) + 1], *p;
int r;
assert(u);
assert(path);
/* Registers a unit for requiring a certain path and all its
* prefixes. We keep a simple array of these paths in the
* unit, since its usually short. However, we build a prefix
* table for all possible prefixes so that new appearing mount
* units can easily determine which units to make themselves a
* dependency of. */
if (!path_is_absolute(path))
return -EINVAL;
p = strdup(path);
if (!p)
return -ENOMEM;
path_kill_slashes(p);
if (!path_is_safe(p)) {
free(p);
return -EPERM;
}
if (strv_contains(u->requires_mounts_for, p)) {
free(p);
return 0;
}
r = strv_consume(&u->requires_mounts_for, p);
if (r < 0)
return r;
PATH_FOREACH_PREFIX_MORE(prefix, p) {
Set *x;
x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
if (!x) {
char *q;
r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
if (r < 0)
return r;
q = strdup(prefix);
if (!q)
return -ENOMEM;
x = set_new(NULL);
if (!x) {
free(q);
return -ENOMEM;
}
r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
if (r < 0) {
free(q);
set_free(x);
return r;
}
}
r = set_put(x, u);
if (r < 0)
return r;
}
return 0;
}
int unit_setup_exec_runtime(Unit *u) {
ExecRuntime **rt;
size_t offset;
Iterator i;
Unit *other;
offset = UNIT_VTABLE(u)->exec_runtime_offset;
assert(offset > 0);
/* Check if there already is an ExecRuntime for this unit? */
rt = (ExecRuntime**) ((uint8_t*) u + offset);
if (*rt)
return 0;
/* Try to get it from somebody else */
SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
*rt = unit_get_exec_runtime(other);
if (*rt) {
exec_runtime_ref(*rt);
return 0;
}
}
return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
}
bool unit_type_supported(UnitType t) {
if (_unlikely_(t < 0))
return false;
if (_unlikely_(t >= _UNIT_TYPE_MAX))
return false;
if (!unit_vtable[t]->supported)
return true;
return unit_vtable[t]->supported();
}
void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
int r;
assert(u);
assert(where);
r = dir_is_empty(where);
if (r > 0)
return;
if (r < 0) {
log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
return;
}
log_struct(LOG_NOTICE,
LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
LOG_UNIT_ID(u),
LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
"WHERE=%s", where,
NULL);
}
int unit_fail_if_symlink(Unit *u, const char* where) {
int r;
assert(u);
assert(where);
r = is_symlink(where);
if (r < 0) {
log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
return 0;
}
if (r == 0)
return 0;
log_struct(LOG_ERR,
LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
LOG_UNIT_ID(u),
LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
"WHERE=%s", where,
NULL);
return -ELOOP;
}
| lnykryn/systemd | src/core/unit.c | C | gpl-2.0 | 116,041 |
// logs.cpp
//
// Rivendell web service portal -- Log services
//
// (C) Copyright 2013,2016 Fred Gleason <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <rdcreate_log.h>
#include <rddb.h>
#include <rdformpost.h>
#include <rdweb.h>
#include <rdsvc.h>
#include <rduser.h>
#include <rdlog.h>
#include <rdlog_event.h>
#include <rdlog_line.h>
#include <rdconf.h>
#include <rdescape_string.h>
#include <rdxport.h>
void Xport::AddLog()
{
QString log_name;
QString service_name;
//
// Get Arguments
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("SERVICE_NAME",&service_name)) {
XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER);
}
RDSvc *svc=new RDSvc(service_name);
if(!svc->exists()) {
XmlExit("No such service",404,"logs.cpp",LINE_NUMBER);
}
//
// Verify User Perms
//
if(!xport_user->createLog()) {
XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER);
}
RDLog *log=new RDLog(log_name);
if(!log->exists()) {
delete log;
log=new RDLog(log_name,true);
if(!log->exists()) {
delete log;
XmlExit("Unable to create log",500,"logs.cpp",LINE_NUMBER);
}
log->setOriginUser(xport_user->name());
log->setDescription("[new log]");
log->setService(service_name);
}
delete log;
RDCreateLogTable(RDLog::tableName(log_name));
XmlExit("OK",200,"logs.cpp",LINE_NUMBER);
}
void Xport::DeleteLog()
{
QString log_name;
//
// Get Arguments
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
//
// Verify User Perms
//
if(!xport_user->deleteLog()) {
XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER);
}
RDLog *log=new RDLog(log_name);
if(log->exists()) {
if(!log->remove(xport_station,xport_user,xport_config)) {
delete log;
XmlExit("Unable to delete log",500,"logs.cpp",LINE_NUMBER);
}
}
delete log;
XmlExit("OK",200,"logs.cpp",LINE_NUMBER);
}
void Xport::ListLogs()
{
QString sql;
RDSqlQuery *q;
RDLog *log;
QString service_name="";
QString log_name="";
QString trackable;
//
// Get Options
//
xport_post->getValue("SERVICE_NAME",&service_name);
xport_post->getValue("LOG_NAME",&log_name);
xport_post->getValue("TRACKABLE",&trackable);
//
// Generate Log List
//
sql="select NAME from LOGS";
if((!service_name.isEmpty())||(!log_name.isEmpty())||(trackable=="1")) {
sql+=" where";
if(!log_name.isEmpty()) {
sql+=" (NAME=\""+RDEscapeString(log_name)+"\")&&";
}
if(!service_name.isEmpty()) {
sql+=" (SERVICE=\""+RDEscapeString(service_name)+"\")&&";
}
if(trackable=="1") {
sql+=" (SCHEDULED_TRACKS>0)&&";
}
sql=sql.left(sql.length()-2);
}
sql+=" order by NAME";
q=new RDSqlQuery(sql);
//
// Process Request
//
printf("Content-type: application/xml\n");
printf("Status: 200\n\n");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
printf("<logList>\n");
while(q->next()) {
log=new RDLog(q->value(0).toString());
printf("%s",(const char *)log->xml());
delete log;
}
printf("</logList>\n");
delete q;
Exit(0);
}
void Xport::ListLog()
{
RDLog *log;
QString name="";
//
// Get Options
//
xport_post->getValue("NAME",&name);
//
// Verify that log exists
//
log=new RDLog(name);
if(!log->exists()) {
delete log;
XmlExit("No such log",404,"logs.cpp",LINE_NUMBER);
}
//
// Generate Log Listing
//
RDLogEvent *log_event=log->createLogEvent();
log_event->load(true);
//
// Process Request
//
printf("Content-type: application/xml\n");
printf("Status: 200\n\n");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
printf("%s\n",(const char *)log_event->xml());
Exit(0);
}
void Xport::SaveLog()
{
//
// Verify User Perms
//
if((!xport_user->addtoLog())||(!xport_user->removefromLog())||(!xport_user->arrangeLog())) {
XmlExit("No user privilege",404,"logs.cpp",LINE_NUMBER);
}
QString log_name;
QString service_name;
QString description;
QDate purge_date;
bool auto_refresh;
QDate start_date;
QDate end_date;
int line_quantity;
//
// Header Data
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("SERVICE_NAME",&service_name)) {
XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("DESCRIPTION",&description)) {
XmlExit("Missing DESCRIPTION",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("PURGE_DATE",&purge_date)) {
XmlExit("Missing PURGE_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("AUTO_REFRESH",&auto_refresh)) {
XmlExit("Missing AUTO_REFRESH",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("START_DATE",&start_date)) {
XmlExit("Missing START_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("END_DATE",&end_date)) {
XmlExit("Missing END_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("LINE_QUANTITY",&line_quantity)) {
XmlExit("Missing LINE_QUANTITY",400,"logs.cpp",LINE_NUMBER);
}
//
// Logline Data
//
RDLogEvent *logevt=new RDLogEvent(RDLog::tableName(log_name));
for(int i=0;i<line_quantity;i++) {
logevt->insert(i,1);
RDLogLine *ll=logevt->logLine(i);
QString line=QString().sprintf("LINE%d",i);
QString str;
int integer1;
int integer2;
QDateTime datetime;
QTime time;
bool state;
bool ok=false;
if(!xport_post->getValue(line+"_ID",&integer1,&ok)) {
XmlExit("Missing "+line+"_ID",400,"logs.cpp",LINE_NUMBER);
}
if(!ok) {
XmlExit("Invalid "+line+"_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setId(integer1);
if(!xport_post->getValue(line+"_TYPE",&integer1)) {
XmlExit("Missing "+line+"_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setType((RDLogLine::Type)integer1);
if(!xport_post->getValue(line+"_CART_NUMBER",&integer1)) {
XmlExit("Missing "+line+"_CART_NUMBER",400,"logs.cpp",LINE_NUMBER);
}
ll->setCartNumber(integer1);
if(!xport_post->getValue(line+"_TIME_TYPE",&integer2)) {
XmlExit("Missing "+line+"_TIME_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setTimeType((RDLogLine::TimeType)integer2);
if(!xport_post->getValue(line+"_START_TIME",&integer1)) {
XmlExit("Missing "+line+"_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
if(ll->timeType()==RDLogLine::Hard) {
ll->setStartTime(RDLogLine::Logged,QTime().addMSecs(integer1));
}
else {
ll->setStartTime(RDLogLine::Predicted,QTime().addMSecs(integer1));
}
if(!xport_post->getValue(line+"_GRACE_TIME",&integer1)) {
XmlExit("Missing "+line+"_GRACE_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setGraceTime(integer1);
if(!xport_post->getValue(line+"_TRANS_TYPE",&str)) {
XmlExit("Missing "+line+"_TRANS_TYPE",400,"logs.cpp",LINE_NUMBER);
}
integer1=-1;
if(str.lower()=="play") {
integer1=RDLogLine::Play;
}
if(str.lower()=="segue") {
integer1=RDLogLine::Segue;
}
if(str.lower()=="stop") {
integer1=RDLogLine::Stop;
}
if(integer1<0) {
XmlExit("Invalid transition type in "+line+"_TRANS_TYPE",400,
"logs.cpp",LINE_NUMBER);
}
ll->setTransType((RDLogLine::TransType)integer1);
if(!xport_post->getValue(line+"_START_POINT",&integer1)) {
XmlExit("Missing "+line+"_START_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setStartPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_END_POINT",&integer1)) {
XmlExit("Missing "+line+"_END_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setEndPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_SEGUE_START_POINT",&integer1)) {
XmlExit("Missing "+line+"_SEGUE_START_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setSegueStartPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_SEGUE_END_POINT",&integer1)) {
XmlExit("Missing "+line+"_SEGUE_END_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setSegueEndPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEUP_POINT",&integer1)) {
XmlExit("Missing "+line+"_FADEUP_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadeupPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEUP_GAIN",&integer1)) {
XmlExit("Missing "+line+"_FADEUP_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadeupGain(integer1);
if(!xport_post->getValue(line+"_FADEDOWN_POINT",&integer1)) {
XmlExit("Missing "+line+"_FADEDOWN_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadedownPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEDOWN_GAIN",&integer1)) {
XmlExit("Missing "+line+"_FADEDOWN_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadedownGain(integer1);
if(!xport_post->getValue(line+"_DUCK_UP_GAIN",&integer1)) {
XmlExit("Missing "+line+"_DUCK_UP_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setDuckUpGain(integer1);
if(!xport_post->getValue(line+"_DUCK_DOWN_GAIN",&integer1)) {
XmlExit("Missing "+line+"_DUCK_DOWN_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setDuckDownGain(integer1);
if(!xport_post->getValue(line+"_COMMENT",&str)) {
XmlExit("Missing "+line+"_COMMENT",400,"logs.cpp",LINE_NUMBER);
}
ll->setMarkerComment(str);
if(!xport_post->getValue(line+"_LABEL",&str)) {
XmlExit("Missing "+line+"_LABEL",400,"logs.cpp",LINE_NUMBER);
}
ll->setMarkerLabel(str);
if(!xport_post->getValue(line+"_ORIGIN_USER",&str)) {
XmlExit("Missing "+line+"_ORIGIN_USER",400,"logs.cpp",LINE_NUMBER);
}
ll->setOriginUser(str);
if(!xport_post->getValue(line+"_ORIGIN_DATETIME",&datetime)) {
XmlExit("Missing "+line+"_ORIGIN_DATETIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setOriginDateTime(datetime);
if(!xport_post->getValue(line+"_EVENT_LENGTH",&integer1)) {
XmlExit("Missing "+line+"_EVENT_LENGTH",400,"logs.cpp",LINE_NUMBER);
}
ll->setEventLength(integer1);
if(!xport_post->getValue(line+"_LINK_EVENT_NAME",&str)) {
XmlExit("Missing "+line+"_LINK_EVENT_NAME",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEventName(str);
if(!xport_post->getValue(line+"_LINK_START_TIME",&integer1)) {
XmlExit("Missing "+line+"_LINK_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkStartTime(QTime().addMSecs(integer1));
if(!xport_post->getValue(line+"_LINK_LENGTH",&integer1)) {
XmlExit("Missing "+line+"_LINK_LENGTH",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkLength(integer1);
if(!xport_post->getValue(line+"_LINK_START_SLOP",&integer1)) {
XmlExit("Missing "+line+"_LINK_START_SLOP",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkStartSlop(integer1);
if(!xport_post->getValue(line+"_LINK_END_SLOP",&integer1)) {
XmlExit("Missing "+line+"_LINK_END_SLOP",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEndSlop(integer1);
if(!xport_post->getValue(line+"_LINK_ID",&integer1)) {
XmlExit("Missing "+line+"_LINK_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkId(integer1);
if(!xport_post->getValue(line+"_LINK_EMBEDDED",&state)) {
XmlExit("Missing "+line+"_LINK_EMBEDDED",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEmbedded(state);
if(!xport_post->getValue(line+"_EXT_START_TIME",&time)) {
XmlExit("Missing "+line+"_EXT_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtStartTime(time);
if(!xport_post->getValue(line+"_EXT_CART_NAME",&str)) {
XmlExit("Missing "+line+"_EXT_CART_NAME",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtCartName(str);
if(!xport_post->getValue(line+"_EXT_DATA",&str)) {
XmlExit("Missing "+line+"_EXT_DATA",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtData(str);
if(!xport_post->getValue(line+"_EXT_EVENT_ID",&str)) {
XmlExit("Missing "+line+"_EXT_EVENT_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtEventId(str);
if(!xport_post->getValue(line+"_EXT_ANNC_TYPE",&str)) {
XmlExit("Missing "+line+"_EXT_ANNC_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtAnncType(str);
}
RDLog *log=new RDLog(log_name);
if(!log->exists()) {
XmlExit("No such log",404,"logs.cpp",LINE_NUMBER);
}
log->setService(service_name);
log->setDescription(description);
log->setPurgeDate(purge_date);
log->setAutoRefresh(auto_refresh);
log->setStartDate(start_date);
log->setEndDate(end_date);
log->setModifiedDatetime(QDateTime::currentDateTime());
logevt->save();
XmlExit(QString().sprintf("OK Saved %d events",logevt->size()),
200,"logs.cpp",LINE_NUMBER);
}
| NBassan/rivendell | web/rdxport/logs.cpp | C++ | gpl-2.0 | 13,675 |
/***************************************************************************
Copyright (C) 2003-2009 Robby Stephenson <[email protected]>
***************************************************************************/
/***************************************************************************
* *
* 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) version 3 or any later version *
* accepted by the membership of KDE e.V. (or its successor approved *
* by the membership of KDE e.V.), which shall act as a proxy *
* defined in Section 14 of version 3 of the license. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
// The layout borrows heavily from kmsearchpatternedit.cpp in kmail
// which is authored by Marc Mutz <[email protected]> under the GPL
#include "filterdialog.h"
#include "tellico_kernel.h"
#include "document.h"
#include "collection.h"
#include "fieldcompletion.h"
#include "gui/filterrulewidgetlister.h"
#include "gui/filterrulewidget.h"
#include "tellico_debug.h"
#include <KLocalizedString>
#include <KHelpClient>
#include <QGroupBox>
#include <QRadioButton>
#include <QButtonGroup>
#include <QLabel>
#include <QApplication>
#include <QFrame>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QDialogButtonBox>
using Tellico::FilterDialog;
namespace {
static const int FILTER_MIN_WIDTH = 600;
}
// modal dialog so I don't have to worry about updating stuff
// don't show apply button if not saving, i.e. just modifying existing filter
FilterDialog::FilterDialog(Mode mode_, QWidget* parent_)
: QDialog(parent_), m_filter(nullptr), m_mode(mode_), m_saveFilter(nullptr) {
setModal(true);
setWindowTitle(mode_ == CreateFilter ? i18n("Advanced Filter") : i18n("Modify Filter"));
QVBoxLayout* topLayout = new QVBoxLayout();
setLayout(topLayout);
QDialogButtonBox* buttonBox;
if(mode_ == CreateFilter) {
buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply);
} else {
buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
}
m_okButton = buttonBox->button(QDialogButtonBox::Ok);
m_applyButton = buttonBox->button(QDialogButtonBox::Apply);
connect(m_okButton, &QAbstractButton::clicked, this, &FilterDialog::slotOk);
if(m_applyButton) {
connect(m_applyButton, &QAbstractButton::clicked, this, &FilterDialog::slotApply);
}
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(buttonBox, &QDialogButtonBox::helpRequested, this, &FilterDialog::slotHelp);
QGroupBox* m_matchGroup = new QGroupBox(i18n("Filter Criteria"), this);
QVBoxLayout* vlay = new QVBoxLayout(m_matchGroup);
topLayout->addWidget(m_matchGroup);
m_matchGroup->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
m_matchAll = new QRadioButton(i18n("Match a&ll of the following"), m_matchGroup);
m_matchAny = new QRadioButton(i18n("Match an&y of the following"), m_matchGroup);
m_matchAll->setChecked(true);
vlay->addWidget(m_matchAll);
vlay->addWidget(m_matchAny);
QButtonGroup* bg = new QButtonGroup(m_matchGroup);
bg->addButton(m_matchAll);
bg->addButton(m_matchAny);
#if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0))
void (QButtonGroup::* buttonClicked)(int) = &QButtonGroup::buttonClicked;
connect(bg, buttonClicked, this, &FilterDialog::slotFilterChanged);
#else
connect(bg, &QButtonGroup::idClicked, this, &FilterDialog::slotFilterChanged);
#endif
m_ruleLister = new FilterRuleWidgetLister(m_matchGroup);
connect(m_ruleLister, &KWidgetLister::widgetRemoved, this, &FilterDialog::slotShrink);
connect(m_ruleLister, &FilterRuleWidgetLister::signalModified, this, &FilterDialog::slotFilterChanged);
m_ruleLister->setFocus();
vlay->addWidget(m_ruleLister);
QHBoxLayout* blay = new QHBoxLayout();
topLayout->addLayout(blay);
QLabel* lab = new QLabel(i18n("Filter name:"), this);
blay->addWidget(lab);
m_filterName = new QLineEdit(this);
blay->addWidget(m_filterName);
connect(m_filterName, &QLineEdit::textChanged, this, &FilterDialog::slotFilterChanged);
// only when creating a new filter can it be saved
if(m_mode == CreateFilter) {
m_saveFilter = new QPushButton(QIcon::fromTheme(QStringLiteral("view-filter")), i18n("&Save Filter"), this);
blay->addWidget(m_saveFilter);
m_saveFilter->setEnabled(false);
connect(m_saveFilter, &QAbstractButton::clicked, this, &FilterDialog::slotSaveFilter);
m_applyButton->setEnabled(false);
}
m_okButton->setEnabled(false); // disable at start
buttonBox->button(QDialogButtonBox::Cancel)->setDefault(true);
setMinimumWidth(qMax(minimumWidth(), FILTER_MIN_WIDTH));
topLayout->addWidget(buttonBox);
}
Tellico::FilterPtr FilterDialog::currentFilter(bool alwaysCreateNew_) {
FilterPtr newFilter(new Filter(Filter::MatchAny));
if(m_matchAll->isChecked()) {
newFilter->setMatch(Filter::MatchAll);
} else {
newFilter->setMatch(Filter::MatchAny);
}
foreach(QWidget* widget, m_ruleLister->widgetList()) {
FilterRuleWidget* rw = static_cast<FilterRuleWidget*>(widget);
FilterRule* rule = rw->rule();
if(rule && !rule->isEmpty()) {
newFilter->append(rule);
} else {
delete rule;
}
}
newFilter->setName(m_filterName->text());
if(!m_filter || !alwaysCreateNew_) {
m_filter = newFilter;
}
return newFilter;
}
void FilterDialog::setFilter(Tellico::FilterPtr filter_) {
if(!filter_) {
slotClear();
return;
}
if(filter_->op() == Filter::MatchAll) {
m_matchAll->setChecked(true);
} else {
m_matchAny->setChecked(true);
}
m_ruleLister->setFilter(filter_);
m_filterName->setText(filter_->name());
m_filter = filter_;
}
void FilterDialog::slotOk() {
slotApply();
accept();
}
void FilterDialog::slotApply() {
emit signalUpdateFilter(currentFilter());
}
void FilterDialog::slotHelp() {
KHelpClient::invokeHelp(QStringLiteral("filter-dialog"));
}
void FilterDialog::slotClear() {
// myDebug();
m_matchAll->setChecked(true);
m_ruleLister->reset();
m_filterName->clear();
}
void FilterDialog::slotShrink() {
updateGeometry();
QApplication::sendPostedEvents();
resize(width(), sizeHint().height());
}
void FilterDialog::slotFilterChanged() {
const bool hadFilter = m_filter && !m_filter->isEmpty();
const bool emptyFilter = currentFilter(true)->isEmpty();
// an empty filter can be ok if the filter was originally not empty
const bool enableOk = !currentFilter()->isEmpty() || hadFilter;
if(m_saveFilter) {
m_saveFilter->setEnabled(!m_filterName->text().isEmpty() && !emptyFilter);
if(m_applyButton) {
m_applyButton->setEnabled(!emptyFilter);
}
}
if(m_applyButton) {
m_applyButton->setEnabled(enableOk);
}
m_okButton->setEnabled(enableOk);
m_okButton->setDefault(enableOk);
}
void FilterDialog::slotSaveFilter() {
// non-op if editing an existing filter
if(m_mode != CreateFilter) {
return;
}
// in this case, currentFilter() either creates a new filter or
// updates the current one. If creating a new one, then I want to copy it
const bool wasEmpty = !m_filter;
FilterPtr filter(new Filter(*currentFilter()));
if(wasEmpty) {
m_filter = filter;
}
// this keeps the saving completely decoupled from the filter setting in the detailed view
if(filter->isEmpty()) {
m_filter = FilterPtr();
return;
}
Kernel::self()->addFilter(filter);
}
| KDE/tellico | src/filterdialog.cpp | C++ | gpl-2.0 | 8,620 |
<?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC ([email protected])
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @Language Tiếng Việt
* @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/)
* @Createdate Mar 04, 2010, 03:22:00 PM
*/
if (!defined('NV_ADMIN') or !defined('NV_MAINFILE')) {
die('Stop!!!');
}
$lang_translator['author'] = 'VINADES.,JSC ([email protected])';
$lang_translator['createdate'] = '04/03/2010, 15:22';
$lang_translator['copyright'] = '@Copyright (C) 2012 VINADES.,JSC. All rights reserved';
$lang_translator['info'] = '';
$lang_translator['langtype'] = 'lang_module';
$lang_module['is_suspend0'] = 'Hoạt động';
$lang_module['is_suspend1'] = 'Bị đình chỉ vào “%1$s” bởi “%2$s” với lý do “%3$s”';
$lang_module['is_suspend2'] = 'Bị đình chỉ';
$lang_module['last_login0'] = 'Chưa bao giờ';
$lang_module['login'] = 'Tên tài khoản';
$lang_module['email'] = 'Email';
$lang_module['full_name'] = 'Tên gọi trên site';
$lang_module['name'] = 'Tên gọi trên site';
$lang_module['sig'] = 'Chữ ký';
$lang_module['editor'] = 'Trình soạn thảo';
$lang_module['lev'] = 'Quyền hạn';
$lang_module['position'] = 'Chức danh';
$lang_module['regtime'] = 'Ngày tham gia';
$lang_module['is_suspend'] = 'Tình trạng hiện tại';
$lang_module['last_login'] = 'Lần đăng nhập gần đây';
$lang_module['last_ip'] = 'Bằng IP';
$lang_module['browser'] = 'Bằng trình duyệt';
$lang_module['os'] = 'Bằng hệ điều hành';
$lang_module['admin_info_title1'] = 'Thông tin tài khoản: %s';
$lang_module['admin_info_title2'] = 'Thông tin tài khoản: %s (là bạn)';
$lang_module['menulist'] = 'Danh sách Quản trị';
$lang_module['menuadd'] = 'Thêm Quản trị';
$lang_module['main'] = 'Danh sách Quản trị website';
$lang_module['nv_admin_edit'] = 'Sửa thông tin Quản trị website';
$lang_module['nv_admin_add'] = 'Thêm Quản trị website';
$lang_module['nv_admin_del'] = 'Xóa Quản trị website';
$lang_module['username_noactive'] = 'Lỗi: tài khoản: %s chưa được kích hoạt, bạn cần kích hoạt tài khoản này trước khi thêm vào quản trị site';
$lang_module['full_name_incorrect'] = 'Bạn chưa khai báo tên gọi của người quản trị này';
$lang_module['position_incorrect'] = 'Bạn chưa khai báo chức danh của người quản trị này';
$lang_module['nv_admin_add_info'] = 'Để tạo một tài khoản Quản trị website mới, bạn cần khai báo đầy đủ vào các ô trống dưới đây. Bạn chỉ có quyền tạo tài khoản Quản trị dưới cấp của mình';
$lang_module['if_level3_selected'] = 'Hãy đánh dấu tích vào những module mà bạn cho phép quản lý';
$lang_module['login_info'] = 'Bạn cần nhập tên thành viên, nếu chưa có thành viên bạn cần tạo thành viên trước.';
$lang_module['nv_admin_add_result'] = 'Thông tin về Quản trị website mới';
$lang_module['nv_admin_add_title'] = 'Hệ thống đã tạo thành công tài khoản Quản trị website mới với những thông tin dưới đây';
$lang_module['nv_admin_modules'] = 'Quản lý các module';
$lang_module['admin_account_info'] = 'Thông tin tài khoản Quản trị website %s';
$lang_module['nv_admin_add_download'] = 'Tải về';
$lang_module['nv_admin_add_sendmail'] = 'Gửi thông báo';
$lang_module['nv_admin_login_address'] = 'URL trang quản lý website';
$lang_module['nv_admin_edit_info'] = 'Thay đổi thông tin tài khoản “<strong>%s</strong>”';
$lang_module['show_mail'] = 'Hiển thị email';
$lang_module['sig_info'] = 'Chữ ký được chèn vào cuối mỗi bài trả lời, thư... được gửi đi từ tài khoản Quản trị “<strong>%s</strong>”. Chỉ chấp nhận dạng text đơn thuần';
$lang_module['not_use'] = 'Không sử dụng';
$lang_module['nv_admin_edit_result'] = 'Thay đổi thông tin tài khoản Quản trị: %s';
$lang_module['nv_admin_edit_result_title'] = 'Những thay đổi vừa được thực hiện đối với tài khoản Quản trị %s';
$lang_module['show_mail0'] = 'Không hiển thị';
$lang_module['show_mail1'] = 'Hiển thị';
$lang_module['field'] = 'tiêu chí';
$lang_module['old_value'] = 'Cũ';
$lang_module['new_value'] = 'Mới';
$lang_module['chg_is_suspend0'] = 'Tình trạng hiện tại: Đang bị đình chỉ. Để Khôi phục hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây';
$lang_module['chg_is_suspend1'] = 'Tình trạng hiện tại: Đang hoạt động. Để Đình chỉ hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây';
$lang_module['chg_is_suspend2'] = 'Khôi phục/Đình chỉ hoạt động';
$lang_module['nv_admin_chg_suspend'] = 'Thay đổi trạng thái hoạt động của tài khoản Quản trị “<strong>%s</strong>”';
$lang_module['position_info'] = 'Chức danh dùng trong các hoạt động đối ngoại như trao đổi thư từ, viết lời bình...';
$lang_module['susp_reason_empty'] = 'Bạn chưa khai báo lý do đình chỉ hoạt động của tài khoản Quản trị “<strong>%s</strong>”';
$lang_module['suspend_info_empty'] = 'Tài khoản quản trị “<strong>%s</strong>” chưa bị đình chỉ hoạt động lần nào';
$lang_module['suspend_info_yes'] = 'Danh sách các lần đình chỉ hoạt động của tài khoản quản trị “<strong>%s</strong>”';
$lang_module['suspend_start'] = 'Bắt đầu';
$lang_module['suspend_end'] = 'Kết thúc';
$lang_module['suspend_reason'] = 'Lý do đình chỉ';
$lang_module['suspend_info'] = 'Vào: %1$s<br />Bởi: %2$s';
$lang_module['suspend0'] = 'Khôi phục hoạt động';
$lang_module['suspend1'] = 'Đình chỉ hoạt động';
$lang_module['clean_history'] = 'Xóa lịch sử';
$lang_module['suspend_sendmail'] = 'Gửi thông báo';
$lang_module['suspend_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị đình chỉ hoạt động vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s';
$lang_module['suspend_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã hoạt động trở lại vào %2$s.<br />Trước đó tài khoản này đã bị đình chỉ hoạt động vì lý do: %3$s';
$lang_module['suspend_sendmail_title'] = 'Thông báo từ website %s';
$lang_module['delete_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %3$s';
$lang_module['delete_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s';
$lang_module['delete_sendmail_title'] = 'Thông báo từ website %s';
$lang_module['delete_sendmail_info'] = 'Bạn thực sự muốn xóa tài khoản quản trị “<strong>%s</strong>”? Hãy điền các thông tin vào các ô trống dưới đây để khẳng định thao tác này';
$lang_module['admin_del_sendmail'] = 'Gửi thông báo';
$lang_module['admin_del_reason'] = 'Lý do xóa';
$lang_module['allow_files_type'] = 'Các kiểu file được phép tải lên';
$lang_module['allow_modify_files'] = 'Được phép sửa, xóa files';
$lang_module['allow_create_subdirectories'] = 'Được phép tạo thư mục';
$lang_module['allow_modify_subdirectories'] = 'Được phép đổi tên, xóa thư mục';
$lang_module['admin_login_incorrect'] = 'Tài khoản “<strong>%s</strong>” đã có trong danh sách quản trị. Hãy sử dụng một tài khoản khác';
$lang_module['config'] = 'Cấu hình';
$lang_module['funcs'] = 'Chức năng';
$lang_module['checkall'] = 'Chọn tất cả';
$lang_module['uncheckall'] = 'Bỏ chọn tất cả';
$lang_module['ip_version'] = 'Loại IP';
$lang_module['adminip'] = 'Quản lý IP truy cập khu vực quản trị';
$lang_module['adminip_ip'] = 'Ip';
$lang_module['adminip_timeban'] = 'Thời gian bắt đầu';
$lang_module['adminip_timeendban'] = 'Thời gian kết thúc';
$lang_module['adminip_add'] = 'Thêm địa chỉ IP';
$lang_module['adminip_address'] = 'Địa chỉ';
$lang_module['adminip_begintime'] = 'Thời gian bắt đầu';
$lang_module['adminip_endtime'] = 'Thời gian kết thúc';
$lang_module['adminip_notice'] = 'Ghi chú';
$lang_module['save'] = 'Lưu thay đổi';
$lang_module['adminip_mask_select'] = 'Hãy chọn';
$lang_module['adminip_nolimit'] = 'Vô thời hạn';
$lang_module['adminip_del_success'] = 'Đã xóa thành công !';
$lang_module['adminip_delete_confirm'] = 'Bạn có chắc muốn xóa ip này ra khỏi danh sách?';
$lang_module['adminip_mask'] = 'Mask IP';
$lang_module['adminip_edit'] = 'Sửa địa chỉ IP';
$lang_module['adminip_delete'] = 'Xóa';
$lang_module['adminip_error_ip'] = 'Hãy nhập Ip được truy cập khu vực quản trị ';
$lang_module['adminip_error_validip'] = 'Lỗi: Bạn cần nhập IP đúng chuẩn';
$lang_module['title_username'] = 'Quản lý tài khoản tường lửa khu vực admin';
$lang_module['admfirewall'] = 'Kiểm tra tường lửa cho khu vực admin';
$lang_module['block_admin_ip'] = 'Kiểm tra IP khi truy cập khu vực admin';
$lang_module['username_add'] = 'Thêm tài khoản';
$lang_module['username_edit'] = 'Sửa tài khoản';
$lang_module['nicknam_delete_confirm'] = 'Bạn có chắc muốn xóa tài khoản này ra khỏi danh sách?';
$lang_module['passwordsincorrect'] = 'Mật khẩu bạn nhập hai lần không giống nhau.';
$lang_module['nochangepass'] = 'Nếu không thay đổi mật khẩu bạn không nhập hai trường mật khẩu';
$lang_module['rule_user'] = 'Tài khoản chỉ dùng các ký tự a-zA-Z0-9_-';
$lang_module['rule_pass'] = 'Mật khẩu chỉ dùng các ký tự a-zA-Z0-9_-';
$lang_module['spadmin_add_admin'] = 'Cho phép người điều hành chung tạo và thay đổi quyền hạn người điều hành modules';
$lang_module['authors_detail_main'] = 'Hiển thị chi tiết các thông tin tài khoản của người quản trị';
$lang_module['admin_check_pass_time'] = 'Thời gian kiểm tra lại mật khẩu, nếu admin không sử dụng trình duyệt';
$lang_module['add_user'] = 'Chỉ định thành viên';
$lang_module['add_select'] = 'Chọn';
$lang_module['add_error_choose'] = 'Lỗi: Bạn chưa chọn thành viên được chỉ định làm quản trị';
$lang_module['add_error_exist'] = 'Lỗi: Thành viên này đã là quản trị';
$lang_module['add_error_notexist'] = 'Lỗi: Thành viên này không tồn tại';
$lang_module['add_error_diff'] = 'Xảy ra lỗi không xác định';
$lang_module['action_account'] = 'Tài khoản thành viên';
$lang_module['action_account_nochange'] = 'Giữ nguyên tài khoản thành viên';
$lang_module['action_account_suspend'] = 'Khóa tài khoản thành viên';
$lang_module['action_account_del'] = 'Xóa tài khoản thành viên';
$lang_module['module_admin'] = 'Phân quyền hệ thống';
$lang_module['users'] = 'Tài khoản';
$lang_module['number'] = 'STT';
$lang_module['module'] = 'Tên module';
$lang_module['custom_title'] = 'Tiêu đề';
$lang_module['main_module'] = 'Module trang chính';
$lang_module['themeadmin'] = 'Giao diện người quản trị';
$lang_module['theme_default'] = 'Mặc định theo cấu hình site';
$lang_module['2step_manager'] = 'Quản lý xác thực hai bước';
$lang_module['2step_code_off'] = 'Xác thực hai bước bằng ứng dụng đang tắt';
$lang_module['2step_code_on'] = 'Xác thực hai bước bằng ứng dụng đang bật';
$lang_module['2step_oauth'] = 'Xác thực hai bước bằng Oauth';
$lang_module['2step_oauth_gate'] = 'Cổng Oauth';
$lang_module['2step_oauth_email'] = 'Email sử dụng';
$lang_module['2step_oauth_empty'] = 'Chưa có tài khoản xác thực nào';
$lang_module['2step_add_google'] = 'Thêm tài khoản Google';
$lang_module['2step_add_facebook'] = 'Thêm tài khoản Facebook';
$lang_module['2step_delete_all'] = 'Gỡ tất cả';
$lang_module['2step_error_oauth_exists'] = 'Tài khoản này đã có trong danh sách xác thực';
$lang_module['2step_addtime'] = 'Thêm lúc';
| NukeVietCMS/nukeviet | includes/language/vi/admin_authors.php | PHP | gpl-2.0 | 12,863 |
/* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, [email protected]
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifndef LMP_KSPACE_H
#define LMP_KSPACE_H
#include "pointers.h" // IWYU pragma: export
#ifdef FFT_SINGLE
typedef float FFT_SCALAR;
#define MPI_FFT_SCALAR MPI_FLOAT
#else
typedef double FFT_SCALAR;
#define MPI_FFT_SCALAR MPI_DOUBLE
#endif
namespace LAMMPS_NS {
class KSpace : protected Pointers {
friend class ThrOMP;
friend class FixOMP;
public:
double energy; // accumulated energies
double energy_1,energy_6;
double virial[6]; // accumulated virial
double *eatom,**vatom; // accumulated per-atom energy/virial
double e2group; // accumulated group-group energy
double f2group[3]; // accumulated group-group force
int triclinic_support; // 1 if supports triclinic geometries
int ewaldflag; // 1 if a Ewald solver
int pppmflag; // 1 if a PPPM solver
int msmflag; // 1 if a MSM solver
int dispersionflag; // 1 if a LJ/dispersion solver
int tip4pflag; // 1 if a TIP4P solver
int dipoleflag; // 1 if a dipole solver
int spinflag; // 1 if a spin solver
int differentiation_flag;
int neighrequest_flag; // used to avoid obsolete construction
// of neighbor lists
int mixflag; // 1 if geometric mixing rules are enforced
// for LJ coefficients
int slabflag;
int scalar_pressure_flag; // 1 if using MSM fast scalar pressure
double slab_volfactor;
int warn_nonneutral; // 0 = error if non-neutral system
// 1 = warn once if non-neutral system
// 2 = warn, but already warned
int warn_nocharge; // 0 = already warned
// 1 = warn if zero charge
int order,order_6,order_allocated;
double accuracy; // accuracy of KSpace solver (force units)
double accuracy_absolute; // user-specified accuracy in force units
double accuracy_relative; // user-specified dimensionless accuracy
// accurary = acc_rel * two_charge_force
double accuracy_real_6; // real space accuracy for
// dispersion solver (force units)
double accuracy_kspace_6; // reciprocal space accuracy for
// dispersion solver (force units)
int auto_disp_flag; // use automatic parameter generation for pppm/disp
double two_charge_force; // force in user units of two point
// charges separated by 1 Angstrom
double g_ewald,g_ewald_6;
int nx_pppm,ny_pppm,nz_pppm; // global FFT grid for Coulombics
int nx_pppm_6,ny_pppm_6,nz_pppm_6; // global FFT grid for dispersion
int nx_msm_max,ny_msm_max,nz_msm_max;
int group_group_enable; // 1 if style supports group/group calculation
// KOKKOS host/device flag and data masks
ExecutionSpace execution_space;
unsigned int datamask_read,datamask_modify;
int copymode;
int compute_flag; // 0 if skip compute()
int fftbench; // 0 if skip FFT timing
int collective_flag; // 1 if use MPI collectives for FFT/remap
int stagger_flag; // 1 if using staggered PPPM grids
double splittol; // tolerance for when to truncate splitting
KSpace(class LAMMPS *);
virtual ~KSpace();
void two_charge();
void triclinic_check();
void modify_params(int, char **);
void *extract(const char *);
void compute_dummy(int, int);
// triclinic
void x2lamdaT(double *, double *);
void lamda2xT(double *, double *);
void lamda2xvector(double *, double *);
void kspacebbox(double, double *);
// public so can be called by commands that change charge
void qsum_qsq(int warning_flag = 1);
// general child-class methods
virtual void settings(int, char **) {};
virtual void init() = 0;
virtual void setup() = 0;
virtual void setup_grid() {};
virtual void compute(int, int) = 0;
virtual void compute_group_group(int, int, int) {};
virtual void pack_forward(int, FFT_SCALAR *, int, int *) {};
virtual void unpack_forward(int, FFT_SCALAR *, int, int *) {};
virtual void pack_reverse(int, FFT_SCALAR *, int, int *) {};
virtual void unpack_reverse(int, FFT_SCALAR *, int, int *) {};
virtual int timing(int, double &, double &) {return 0;}
virtual int timing_1d(int, double &) {return 0;}
virtual int timing_3d(int, double &) {return 0;}
virtual int modify_param(int, char **) {return 0;}
virtual double memory_usage() {return 0.0;}
/* ----------------------------------------------------------------------
compute gamma for MSM and pair styles
see Eq 4 from Parallel Computing 35 (2009) 164-177
------------------------------------------------------------------------- */
double gamma(const double &rho) const
{
if (rho <= 1.0) {
const int split_order = order/2;
const double rho2 = rho*rho;
double g = gcons[split_order][0];
double rho_n = rho2;
for (int n = 1; n <= split_order; n++) {
g += gcons[split_order][n]*rho_n;
rho_n *= rho2;
}
return g;
} else return (1.0/rho);
}
/* ----------------------------------------------------------------------
compute the derivative of gamma for MSM and pair styles
see Eq 4 from Parallel Computing 35 (2009) 164-177
------------------------------------------------------------------------- */
double dgamma(const double &rho) const
{
if (rho <= 1.0) {
const int split_order = order/2;
const double rho2 = rho*rho;
double dg = dgcons[split_order][0]*rho;
double rho_n = rho*rho2;
for (int n = 1; n < split_order; n++) {
dg += dgcons[split_order][n]*rho_n;
rho_n *= rho2;
}
return dg;
} else return (-1.0/rho/rho);
}
double **get_gcons() { return gcons; }
double **get_dgcons() { return dgcons; }
protected:
int gridflag,gridflag_6;
int gewaldflag,gewaldflag_6;
int minorder,overlap_allowed;
int adjust_cutoff_flag;
int suffix_flag; // suffix compatibility flag
bigint natoms_original;
double scale,qqrd2e;
double qsum,qsqsum,q2;
double **gcons,**dgcons; // accumulated per-atom energy/virial
int evflag,evflag_atom;
int eflag_either,eflag_global,eflag_atom;
int vflag_either,vflag_global,vflag_atom;
int maxeatom,maxvatom;
int kewaldflag; // 1 if kspace range set for Ewald sum
int kx_ewald,ky_ewald,kz_ewald; // kspace settings for Ewald sum
void pair_check();
void ev_init(int eflag, int vflag, int alloc = 1) {
if (eflag||vflag) ev_setup(eflag, vflag, alloc);
else evflag = eflag_either = eflag_global = eflag_atom = vflag_either = vflag_global = vflag_atom = 0;
}
void ev_setup(int, int, int alloc = 1);
double estimate_table_accuracy(double, double);
};
}
#endif
/* ERROR/WARNING messages:
E: KSpace style does not yet support triclinic geometries
The specified kspace style does not allow for non-orthogonal
simulation boxes.
E: KSpace solver requires a pair style
No pair style is defined.
E: KSpace style is incompatible with Pair style
Setting a kspace style requires that a pair style with matching
long-range Coulombic or dispersion components be used.
W: Using kspace solver on system with no charge
Self-explanatory.
E: System is not charge neutral, net charge = %g
The total charge on all atoms on the system is not 0.0.
For some KSpace solvers this is an error.
W: System is not charge neutral, net charge = %g
The total charge on all atoms on the system is not 0.0.
For some KSpace solvers this is only a warning.
W: For better accuracy use 'pair_modify table 0'
The user-specified force accuracy cannot be achieved unless the table
feature is disabled by using 'pair_modify table 0'.
E: Illegal ... command
Self-explanatory. Check the input script syntax and compare to the
documentation for the command. You can use -echo screen as a
command-line option when running LAMMPS to see the offending line.
E: Bad kspace_modify slab parameter
Kspace_modify value for the slab/volume keyword must be >= 2.0.
E: Kspace_modify mesh parameter must be all zero or all positive
Valid kspace mesh parameters are >0. The code will try to auto-detect
suitable values when all three mesh sizes are set to zero (the default).
E: Kspace_modify mesh/disp parameter must be all zero or all positive
Valid kspace mesh/disp parameters are >0. The code will try to auto-detect
suitable values when all three mesh sizes are set to zero [and]
the required accuracy via {force/disp/real} as well as
{force/disp/kspace} is set.
W: Kspace_modify slab param < 2.0 may cause unphysical behavior
The kspace_modify slab parameter should be larger to insure periodic
grids padded with empty space do not overlap.
E: Bad kspace_modify kmax/ewald parameter
Kspace_modify values for the kmax/ewald keyword must be integers > 0
E: Kspace_modify eigtol must be smaller than one
Self-explanatory.
*/
| pdebuyl/lammps | src/kspace.h | C | gpl-2.0 | 9,875 |
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
#include <cstddef>
#include <string>
#include <vector>
#include <wx/chartype.h>
#include <wx/defs.h>
#include <wx/dynarray.h>
#include <wx/event.h>
#include <wx/frame.h>
#include <wx/gdicmn.h>
#include <wx/list.h>
#include <wx/menu.h>
#include <wx/menuitem.h>
#include <wx/msgdlg.h>
#include <wx/object.h>
#include <wx/panel.h>
#include <wx/rtti.h>
#include <wx/sizer.h>
#include <wx/statusbr.h>
#include <wx/string.h>
#include <wx/textdlg.h>
#include <wx/toplevel.h>
#include <wx/translation.h>
#include <wx/window.h>
#include <wx/windowid.h>
#include <wx/aui/auibar.h>
#include <wx/aui/auibook.h>
#include <wx/aui/framemanager.h>
#include "Common/CommonTypes.h"
#include "Common/FileUtil.h"
#include "Common/IniFile.h"
#include "Common/MathUtil.h"
#include "Common/StringUtil.h"
#include "Common/Logging/ConsoleListener.h"
#include "Core/ConfigManager.h"
#include "DolphinWX/Frame.h"
#include "DolphinWX/Globals.h"
#include "DolphinWX/LogConfigWindow.h"
#include "DolphinWX/LogWindow.h"
#include "DolphinWX/WxUtils.h"
#include "DolphinWX/Debugger/CodeWindow.h"
// ------------
// Aui events
void CFrame::OnManagerResize(wxAuiManagerEvent& event)
{
if (!g_pCodeWindow && m_LogWindow &&
m_Mgr->GetPane("Pane 1").IsShown() &&
!m_Mgr->GetPane("Pane 1").IsFloating())
{
m_LogWindow->x = m_Mgr->GetPane("Pane 1").rect.GetWidth();
m_LogWindow->y = m_Mgr->GetPane("Pane 1").rect.GetHeight();
m_LogWindow->winpos = m_Mgr->GetPane("Pane 1").dock_direction;
}
event.Skip();
}
void CFrame::OnPaneClose(wxAuiManagerEvent& event)
{
event.Veto();
wxAuiNotebook * nb = (wxAuiNotebook*)event.pane->window;
if (!nb) return;
if (!g_pCodeWindow)
{
if (nb->GetPage(0)->GetId() == IDM_LOGWINDOW ||
nb->GetPage(0)->GetId() == IDM_LOGCONFIGWINDOW)
{
SConfig::GetInstance().m_InterfaceLogWindow = false;
SConfig::GetInstance().m_InterfaceLogConfigWindow = false;
ToggleLogWindow(false);
ToggleLogConfigWindow(false);
}
}
else
{
if (GetNotebookCount() == 1)
{
wxMessageBox(_("At least one pane must remain open."),
_("Notice"), wxOK, this);
}
else if (nb->GetPageCount() != 0 && !nb->GetPageText(0).IsSameAs("<>"))
{
wxMessageBox(_("You can't close panes that have pages in them."),
_("Notice"), wxOK, this);
}
else
{
// Detach and delete the empty notebook
event.pane->DestroyOnClose(true);
m_Mgr->ClosePane(*event.pane);
}
}
m_Mgr->Update();
}
void CFrame::ToggleLogWindow(bool bShow)
{
if (!m_LogWindow)
return;
GetMenuBar()->FindItem(IDM_LOGWINDOW)->Check(bShow);
if (bShow)
{
// Create a new log window if it doesn't exist.
if (!m_LogWindow)
{
m_LogWindow = new CLogWindow(this, IDM_LOGWINDOW);
}
m_LogWindow->Enable();
DoAddPage(m_LogWindow,
g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[0] : 0,
g_pCodeWindow ? bFloatWindow[0] : false);
}
else
{
// Hiding the log window, so disable it and remove it.
m_LogWindow->Disable();
DoRemovePage(m_LogWindow, true);
}
// Hide or Show the pane
if (!g_pCodeWindow)
TogglePane();
}
void CFrame::ToggleLogConfigWindow(bool bShow)
{
GetMenuBar()->FindItem(IDM_LOGCONFIGWINDOW)->Check(bShow);
if (bShow)
{
if (!m_LogConfigWindow)
m_LogConfigWindow = new LogConfigWindow(this, m_LogWindow, IDM_LOGCONFIGWINDOW);
const int nbIndex = IDM_LOGCONFIGWINDOW - IDM_LOGWINDOW;
DoAddPage(m_LogConfigWindow,
g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[nbIndex] : 0,
g_pCodeWindow ? bFloatWindow[nbIndex] : false);
}
else
{
DoRemovePage(m_LogConfigWindow, false);
m_LogConfigWindow = nullptr;
}
// Hide or Show the pane
if (!g_pCodeWindow)
TogglePane();
}
void CFrame::OnToggleWindow(wxCommandEvent& event)
{
bool bShow = GetMenuBar()->IsChecked(event.GetId());
switch (event.GetId())
{
case IDM_LOGWINDOW:
if (!g_pCodeWindow)
SConfig::GetInstance().m_InterfaceLogWindow = bShow;
ToggleLogWindow(bShow);
break;
case IDM_LOGCONFIGWINDOW:
if (!g_pCodeWindow)
SConfig::GetInstance().m_InterfaceLogConfigWindow = bShow;
ToggleLogConfigWindow(bShow);
break;
case IDM_REGISTERWINDOW:
g_pCodeWindow->ToggleRegisterWindow(bShow);
break;
case IDM_WATCHWINDOW:
g_pCodeWindow->ToggleWatchWindow(bShow);
break;
case IDM_BREAKPOINTWINDOW:
g_pCodeWindow->ToggleBreakPointWindow(bShow);
break;
case IDM_MEMORYWINDOW:
g_pCodeWindow->ToggleMemoryWindow(bShow);
break;
case IDM_JITWINDOW:
g_pCodeWindow->ToggleJitWindow(bShow);
break;
case IDM_SOUNDWINDOW:
g_pCodeWindow->ToggleSoundWindow(bShow);
break;
case IDM_VIDEOWINDOW:
g_pCodeWindow->ToggleVideoWindow(bShow);
break;
}
}
// Notebooks
// ---------------------
void CFrame::ClosePages()
{
ToggleLogWindow(false);
ToggleLogConfigWindow(false);
if (g_pCodeWindow)
{
g_pCodeWindow->ToggleCodeWindow(false);
g_pCodeWindow->ToggleRegisterWindow(false);
g_pCodeWindow->ToggleWatchWindow(false);
g_pCodeWindow->ToggleBreakPointWindow(false);
g_pCodeWindow->ToggleMemoryWindow(false);
g_pCodeWindow->ToggleJitWindow(false);
g_pCodeWindow->ToggleSoundWindow(false);
g_pCodeWindow->ToggleVideoWindow(false);
}
}
void CFrame::OnNotebookPageChanged(wxAuiNotebookEvent& event)
{
event.Skip();
if (!g_pCodeWindow)
return;
// Remove the blank page if any
AddRemoveBlankPage();
// Update the notebook affiliation
for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++)
{
if (GetNotebookAffiliation(i) >= 0)
g_pCodeWindow->iNbAffiliation[i - IDM_LOGWINDOW] = GetNotebookAffiliation(i);
}
}
void CFrame::OnNotebookPageClose(wxAuiNotebookEvent& event)
{
// Override event
event.Veto();
wxAuiNotebook* Ctrl = (wxAuiNotebook*)event.GetEventObject();
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGWINDOW)
ToggleLogWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGCONFIGWINDOW)
ToggleLogConfigWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_REGISTERWINDOW)
g_pCodeWindow->ToggleRegisterWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_WATCHWINDOW)
g_pCodeWindow->ToggleWatchWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_BREAKPOINTWINDOW)
g_pCodeWindow->ToggleBreakPointWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_JITWINDOW)
g_pCodeWindow->ToggleJitWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_MEMORYWINDOW)
g_pCodeWindow->ToggleMemoryWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_SOUNDWINDOW)
g_pCodeWindow->ToggleSoundWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_VIDEOWINDOW)
g_pCodeWindow->ToggleVideoWindow(false);
}
void CFrame::OnFloatingPageClosed(wxCloseEvent& event)
{
ToggleFloatWindow(event.GetId() - IDM_LOGWINDOW_PARENT + IDM_FLOAT_LOGWINDOW);
}
void CFrame::OnFloatingPageSize(wxSizeEvent& event)
{
event.Skip();
}
void CFrame::OnFloatWindow(wxCommandEvent& event)
{
ToggleFloatWindow(event.GetId());
}
void CFrame::ToggleFloatWindow(int Id)
{
wxWindowID WinId = Id - IDM_FLOAT_LOGWINDOW + IDM_LOGWINDOW;
if (GetNotebookPageFromId(WinId))
{
DoFloatNotebookPage(WinId);
bFloatWindow[WinId - IDM_LOGWINDOW] = true;
}
else
{
if (FindWindowById(WinId))
DoUnfloatPage(WinId - IDM_LOGWINDOW + IDM_LOGWINDOW_PARENT);
bFloatWindow[WinId - IDM_LOGWINDOW] = false;
}
}
void CFrame::DoFloatNotebookPage(wxWindowID Id)
{
wxPanel *Win = (wxPanel*)FindWindowById(Id);
if (!Win) return;
for (int i = 0; i < GetNotebookCount(); i++)
{
wxAuiNotebook *nb = GetNotebookFromId(i);
if (nb->GetPageIndex(Win) != wxNOT_FOUND)
{
nb->RemovePage(nb->GetPageIndex(Win));
// Create the parent frame and reparent the window
CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW,
Win->GetName(), Win);
if (nb->GetPageCount() == 0)
AddRemoveBlankPage();
}
}
}
void CFrame::DoUnfloatPage(int Id)
{
wxFrame * Win = (wxFrame*)FindWindowById(Id);
if (!Win) return;
wxWindow * Child = Win->GetChildren().Item(0)->GetData();
Child->Reparent(this);
DoAddPage(Child, g_pCodeWindow->iNbAffiliation[Child->GetId() - IDM_LOGWINDOW], false);
Win->Destroy();
}
void CFrame::OnTab(wxAuiNotebookEvent& event)
{
event.Skip();
if (!g_pCodeWindow) return;
// Create the popup menu
wxMenu* MenuPopup = new wxMenu;
wxMenuItem* Item = new wxMenuItem(MenuPopup, wxID_ANY, _("Select floating windows"));
MenuPopup->Append(Item);
Item->Enable(false);
MenuPopup->Append(new wxMenuItem(MenuPopup));
for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++)
{
wxWindow *Win = FindWindowById(i);
if (Win && Win->IsEnabled())
{
Item = new wxMenuItem(MenuPopup, i + IDM_FLOAT_LOGWINDOW - IDM_LOGWINDOW,
Win->GetName(), "", wxITEM_CHECK);
MenuPopup->Append(Item);
Item->Check(!!FindWindowById(i + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW));
}
}
// Line up our menu with the cursor
wxPoint Pt = ::wxGetMousePosition();
Pt = ScreenToClient(Pt);
// Show
PopupMenu(MenuPopup, Pt);
}
void CFrame::OnAllowNotebookDnD(wxAuiNotebookEvent& event)
{
event.Skip();
event.Allow();
}
void CFrame::ShowResizePane()
{
if (!m_LogWindow) return;
// Make sure the size is sane
if (m_LogWindow->x > GetClientRect().GetWidth())
m_LogWindow->x = GetClientRect().GetWidth() / 2;
if (m_LogWindow->y > GetClientRect().GetHeight())
m_LogWindow->y = GetClientRect().GetHeight() / 2;
wxAuiPaneInfo &pane = m_Mgr->GetPane("Pane 1");
// Hide first otherwise a resize doesn't work
pane.Hide();
m_Mgr->Update();
pane.BestSize(m_LogWindow->x, m_LogWindow->y)
.MinSize(m_LogWindow->x, m_LogWindow->y)
.Direction(m_LogWindow->winpos).Show();
m_Mgr->Update();
// Reset the minimum size of the pane
pane.MinSize(-1, -1);
m_Mgr->Update();
}
void CFrame::TogglePane()
{
// Get the first notebook
wxAuiNotebook * NB = nullptr;
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
}
if (NB)
{
if (NB->GetPageCount() == 0)
{
m_Mgr->GetPane("Pane 1").Hide();
m_Mgr->Update();
}
else
{
ShowResizePane();
}
}
}
void CFrame::DoRemovePage(wxWindow *Win, bool bHide)
{
if (!Win) return;
wxWindow *Parent = FindWindowById(Win->GetId() +
IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW);
if (Parent)
{
if (bHide)
{
Win->Hide();
Win->Reparent(this);
}
else
{
Win->Destroy();
}
Parent->Destroy();
}
else
{
for (int i = 0; i < GetNotebookCount(); i++)
{
int PageIndex = GetNotebookFromId(i)->GetPageIndex(Win);
if (PageIndex != wxNOT_FOUND)
{
GetNotebookFromId(i)->RemovePage(PageIndex);
if (bHide)
{
Win->Hide();
Win->Reparent(this);
}
else
{
Win->Destroy();
}
}
}
}
if (g_pCodeWindow)
AddRemoveBlankPage();
}
void CFrame::DoAddPage(wxWindow *Win, int i, bool Float)
{
if (!Win) return;
// Ensure accessor remains within valid bounds.
if (i < 0 || i > GetNotebookCount()-1)
i = 0;
// The page was already previously added, no need to add it again.
if (Win && GetNotebookFromId(i)->GetPageIndex(Win) != wxNOT_FOUND)
return;
if (!Float)
GetNotebookFromId(i)->AddPage(Win, Win->GetName(), true);
else
CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW,
Win->GetName(), Win);
}
void CFrame::PopulateSavedPerspectives()
{
// If the perspective submenu hasn't been created yet, return
if (!m_SavedPerspectives) return;
// Delete all saved perspective menu items
while (m_SavedPerspectives->GetMenuItemCount() != 0)
{
// Delete the first menu item in the list (while there are menu items)
m_SavedPerspectives->Delete(m_SavedPerspectives->FindItemByPosition(0));
}
if (Perspectives.size() > 0)
{
for (u32 i = 0; i < Perspectives.size(); i++)
{
wxMenuItem* mItem = new wxMenuItem(m_SavedPerspectives, IDM_PERSPECTIVES_0 + i,
StrToWxStr(Perspectives[i].Name), "", wxITEM_CHECK);
m_SavedPerspectives->Append(mItem);
if (i == ActivePerspective)
{
mItem->Check(true);
}
}
}
}
void CFrame::OnPerspectiveMenu(wxCommandEvent& event)
{
ClearStatusBar();
switch (event.GetId())
{
case IDM_SAVE_PERSPECTIVE:
if (Perspectives.size() == 0)
{
wxMessageBox(_("Please create a perspective before saving"),
_("Notice"), wxOK, this);
return;
}
SaveIniPerspectives();
GetStatusBar()->SetStatusText(StrToWxStr(std::string
("Saved " + Perspectives[ActivePerspective].Name)), 0);
break;
case IDM_PERSPECTIVES_ADD_PANE:
AddPane();
break;
case IDM_EDIT_PERSPECTIVES:
m_bEdit = event.IsChecked();
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
break;
case IDM_ADD_PERSPECTIVE:
{
wxTextEntryDialog dlg(this,
_("Enter a name for the new perspective:"),
_("Create new perspective"));
wxString DefaultValue = wxString::Format(_("Perspective %d"), (int)(Perspectives.size() + 1));
dlg.SetValue(DefaultValue);
int Return = 0;
bool DlgOk = false;
while (!DlgOk)
{
Return = dlg.ShowModal();
if (Return == wxID_CANCEL)
{
return;
}
else if (dlg.GetValue().Find(",") != -1)
{
wxMessageBox(_("The name cannot contain the character ','"),
_("Notice"), wxOK, this);
wxString Str = dlg.GetValue();
Str.Replace(",", "", true);
dlg.SetValue(Str);
}
else if (dlg.GetValue().IsSameAs(""))
{
wxMessageBox(_("The name cannot be empty"),
_("Notice"), wxOK, this);
dlg.SetValue(DefaultValue);
}
else
{
DlgOk = true;
}
}
SPerspectives Tmp;
Tmp.Name = WxStrToStr(dlg.GetValue());
Tmp.Perspective = m_Mgr->SavePerspective();
ActivePerspective = (u32)Perspectives.size();
Perspectives.push_back(Tmp);
UpdateCurrentPerspective();
PopulateSavedPerspectives();
}
break;
case IDM_TAB_SPLIT:
m_bTabSplit = event.IsChecked();
ToggleNotebookStyle(m_bTabSplit, wxAUI_NB_TAB_SPLIT);
break;
case IDM_NO_DOCKING:
m_bNoDocking = event.IsChecked();
TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING);
break;
}
}
void CFrame::TogglePaneStyle(bool On, int EventId)
{
wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes();
for (u32 i = 0; i < AllPanes.GetCount(); ++i)
{
wxAuiPaneInfo& Pane = AllPanes[i];
if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
// Default
Pane.CloseButton(true);
Pane.MaximizeButton(true);
Pane.MinimizeButton(true);
Pane.PinButton(true);
Pane.Show();
switch (EventId)
{
case IDM_EDIT_PERSPECTIVES:
Pane.CaptionVisible(On);
Pane.Movable(On);
Pane.Floatable(On);
Pane.Dockable(On);
break;
}
Pane.Dockable(!m_bNoDocking);
}
}
m_Mgr->Update();
}
void CFrame::ToggleNotebookStyle(bool On, long Style)
{
wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes();
for (int i = 0, Count = (int)AllPanes.GetCount(); i < Count; ++i)
{
wxAuiPaneInfo& Pane = AllPanes[i];
if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
wxAuiNotebook* NB = (wxAuiNotebook*)Pane.window;
if (On)
NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() | Style);
else
NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() &~ Style);
NB->Refresh();
}
}
}
void CFrame::OnSelectPerspective(wxCommandEvent& event)
{
u32 _Selection = event.GetId() - IDM_PERSPECTIVES_0;
if (Perspectives.size() <= _Selection) _Selection = 0;
ActivePerspective = _Selection;
DoLoadPerspective();
}
void CFrame::SetPaneSize()
{
if (Perspectives.size() <= ActivePerspective)
return;
int iClientX = GetSize().GetX();
int iClientY = GetSize().GetY();
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar)))
{
if (!m_Mgr->GetAllPanes()[i].IsOk())
return;
if (Perspectives[ActivePerspective].Width.size() <= j ||
Perspectives[ActivePerspective].Height.size() <= j)
continue;
// Width and height of the active perspective
u32 W = Perspectives[ActivePerspective].Width[j],
H = Perspectives[ActivePerspective].Height[j];
// Check limits
MathUtil::Clamp<u32>(&W, 5, 95);
MathUtil::Clamp<u32>(&H, 5, 95);
// Convert percentages to pixel lengths
W = (W * iClientX) / 100;
H = (H * iClientY) / 100;
m_Mgr->GetAllPanes()[i].BestSize(W,H).MinSize(W,H);
j++;
}
}
m_Mgr->Update();
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar)))
{
m_Mgr->GetAllPanes()[i].MinSize(-1,-1);
}
}
}
void CFrame::ReloadPanes()
{
// Close all pages
ClosePages();
CloseAllNotebooks();
// Create new panes with notebooks
for (u32 i = 0; i < Perspectives[ActivePerspective].Width.size() - 1; i++)
{
wxString PaneName = wxString::Format("Pane %i", i + 1);
m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo().Hide()
.CaptionVisible(m_bEdit).Dockable(!m_bNoDocking).Position(i)
.Name(PaneName).Caption(PaneName));
}
// Perspectives
m_Mgr->LoadPerspective(Perspectives[ActivePerspective].Perspective, false);
// Restore settings
TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING);
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
// Load GUI settings
g_pCodeWindow->Load();
// Open notebook pages
AddRemoveBlankPage();
g_pCodeWindow->OpenPages();
// Repopulate perspectives
PopulateSavedPerspectives();
}
void CFrame::DoLoadPerspective()
{
ReloadPanes();
// Restore the exact window sizes, which LoadPerspective doesn't always do
SetPaneSize();
m_Mgr->Update();
}
// Update the local perspectives array
void CFrame::LoadIniPerspectives()
{
Perspectives.clear();
std::vector<std::string> VPerspectives;
std::string _Perspectives;
IniFile ini;
ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives");
perspectives->Get("Perspectives", &_Perspectives, "Perspective 1");
perspectives->Get("Active", &ActivePerspective, 0);
SplitString(_Perspectives, ',', VPerspectives);
for (auto& VPerspective : VPerspectives)
{
SPerspectives Tmp;
std::string _Section, _Perspective, _Widths, _Heights;
std::vector<std::string> _SWidth, _SHeight;
Tmp.Name = VPerspective;
// Don't save a blank perspective
if (Tmp.Name.empty())
{
continue;
}
_Section = StringFromFormat("P - %s", Tmp.Name.c_str());
IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section);
perspec_section->Get("Perspective", &_Perspective,
"layout2|"
"name=Pane 0;caption=Pane 0;state=768;dir=5;prop=100000;|"
"name=Pane 1;caption=Pane 1;state=31458108;dir=4;prop=100000;|"
"dock_size(5,0,0)=22|dock_size(4,0,0)=333|");
perspec_section->Get("Width", &_Widths, "70,25");
perspec_section->Get("Height", &_Heights, "80,80");
Tmp.Perspective = StrToWxStr(_Perspective);
SplitString(_Widths, ',', _SWidth);
SplitString(_Heights, ',', _SHeight);
for (auto& Width : _SWidth)
{
int _Tmp;
if (TryParse(Width, &_Tmp))
Tmp.Width.push_back(_Tmp);
}
for (auto& Height : _SHeight)
{
int _Tmp;
if (TryParse(Height, &_Tmp))
Tmp.Height.push_back(_Tmp);
}
Perspectives.push_back(Tmp);
}
}
void CFrame::UpdateCurrentPerspective()
{
SPerspectives *current = &Perspectives[ActivePerspective];
current->Perspective = m_Mgr->SavePerspective();
// Get client size
int iClientX = GetSize().GetX(), iClientY = GetSize().GetY();
current->Width.clear();
current->Height.clear();
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->
IsKindOf(CLASSINFO(wxAuiToolBar)))
{
// Save width and height as a percentage of the client width and height
current->Width.push_back(
(m_Mgr->GetAllPanes()[i].window->GetClientSize().GetX() * 100) /
iClientX);
current->Height.push_back(
(m_Mgr->GetAllPanes()[i].window->GetClientSize().GetY() * 100) /
iClientY);
}
}
}
void CFrame::SaveIniPerspectives()
{
if (Perspectives.size() == 0) return;
if (ActivePerspective >= Perspectives.size()) ActivePerspective = 0;
// Turn off edit before saving
TogglePaneStyle(false, IDM_EDIT_PERSPECTIVES);
UpdateCurrentPerspective();
IniFile ini;
ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
// Save perspective names
std::string STmp = "";
for (auto& Perspective : Perspectives)
{
STmp += Perspective.Name + ",";
}
STmp = STmp.substr(0, STmp.length()-1);
IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives");
perspectives->Set("Perspectives", STmp);
perspectives->Set("Active", ActivePerspective);
// Save the perspectives
for (auto& Perspective : Perspectives)
{
std::string _Section = "P - " + Perspective.Name;
IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section);
perspec_section->Set("Perspective", WxStrToStr(Perspective.Perspective));
std::string SWidth = "", SHeight = "";
for (u32 j = 0; j < Perspective.Width.size(); j++)
{
SWidth += StringFromFormat("%i,", Perspective.Width[j]);
SHeight += StringFromFormat("%i,", Perspective.Height[j]);
}
// Remove the ending ","
SWidth = SWidth.substr(0, SWidth.length()-1);
SHeight = SHeight.substr(0, SHeight.length()-1);
perspec_section->Set("Width", SWidth);
perspec_section->Set("Height", SHeight);
}
ini.Save(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
// Save notebook affiliations
g_pCodeWindow->Save();
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
}
void CFrame::AddPane()
{
int PaneNum = GetNotebookCount() + 1;
wxString PaneName = wxString::Format("Pane %i", PaneNum);
m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo()
.CaptionVisible(m_bEdit).Dockable(!m_bNoDocking)
.Name(PaneName).Caption(PaneName)
.Position(GetNotebookCount()));
AddRemoveBlankPage();
m_Mgr->Update();
}
wxWindow * CFrame::GetNotebookPageFromId(wxWindowID Id)
{
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 j = 0; j < NB->GetPageCount(); j++)
{
if (NB->GetPage(j)->GetId() == Id)
return NB->GetPage(j);
}
}
return nullptr;
}
wxFrame* CFrame::CreateParentFrame(wxWindowID Id, const wxString& Title, wxWindow* Child)
{
wxFrame* Frame = new wxFrame(this, Id, Title);
Child->Reparent(Frame);
wxBoxSizer* m_MainSizer = new wxBoxSizer(wxHORIZONTAL);
m_MainSizer->Add(Child, 1, wxEXPAND);
Frame->Bind(wxEVT_CLOSE_WINDOW, &CFrame::OnFloatingPageClosed, this);
// Main sizer
Frame->SetSizer(m_MainSizer);
// Minimum frame size
Frame->SetMinSize(wxSize(200, 200));
Frame->Show();
return Frame;
}
wxAuiNotebook* CFrame::CreateEmptyNotebook()
{
const long NOTEBOOK_STYLE = wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT |
wxAUI_NB_TAB_EXTERNAL_MOVE | wxAUI_NB_SCROLL_BUTTONS |
wxAUI_NB_WINDOWLIST_BUTTON | wxNO_BORDER;
wxAuiNotebook* NB = new wxAuiNotebook(this, wxID_ANY,
wxDefaultPosition, wxDefaultSize, NOTEBOOK_STYLE);
return NB;
}
void CFrame::AddRemoveBlankPage()
{
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 j = 0; j < NB->GetPageCount(); j++)
{
if (NB->GetPageText(j).IsSameAs("<>") && NB->GetPageCount() > 1)
NB->DeletePage(j);
}
if (NB->GetPageCount() == 0)
NB->AddPage(new wxPanel(this, wxID_ANY), "<>", true);
}
}
int CFrame::GetNotebookAffiliation(wxWindowID Id)
{
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 k = 0; k < NB->GetPageCount(); k++)
{
if (NB->GetPage(k)->GetId() == Id)
return j;
}
j++;
}
return -1;
}
// Close all panes with notebooks
void CFrame::CloseAllNotebooks()
{
wxAuiPaneInfoArray AllPanes = m_Mgr->GetAllPanes();
for (u32 i = 0; i < AllPanes.GetCount(); i++)
{
if (AllPanes[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
AllPanes[i].DestroyOnClose(true);
m_Mgr->ClosePane(AllPanes[i]);
}
}
}
int CFrame::GetNotebookCount()
{
int Ret = 0;
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
Ret++;
}
return Ret;
}
wxAuiNotebook * CFrame::GetNotebookFromId(u32 NBId)
{
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
if (j == NBId)
return (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
j++;
}
return nullptr;
}
| Asmodean-/dolphin | Source/Core/DolphinWX/FrameAui.cpp | C++ | gpl-2.0 | 25,156 |
/*****************************************************************************
* Free42 -- an HP-42S calculator simulator
* Copyright (C) 2004-2016 Thomas Okken
*
* 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/.
*****************************************************************************/
#include <stdlib.h>
#include "core_commands2.h"
#include "core_commands3.h"
#include "core_commands4.h"
#include "core_display.h"
#include "core_helpers.h"
#include "core_linalg1.h"
#include "core_sto_rcl.h"
#include "core_variables.h"
/********************************************************/
/* Implementations of HP-42S built-in functions, part 4 */
/********************************************************/
int docmd_insr(arg_struct *arg) {
vartype *m, *newx;
vartype_realmatrix *rm;
vartype_complexmatrix *cm;
int4 rows, columns, i;
int err, refcount;
int interactive;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
interactive = matedit_mode == 2 || matedit_mode == 3;
if (interactive) {
err = docmd_stoel(NULL);
if (err != ERR_NONE)
return err;
}
if (m->type == TYPE_REALMATRIX) {
rm = (vartype_realmatrix *) m;
rows = rm->rows;
columns = rm->columns;
refcount = rm->array->refcount;
if (interactive) {
newx = new_real(0);
if (newx == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
} else {
cm = (vartype_complexmatrix *) m;
rows = cm->rows;
columns = cm->columns;
refcount = cm->array->refcount;
if (interactive) {
newx = new_complex(0, 0);
if (newx == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
}
if (matedit_i >= rows)
matedit_i = rows - 1;
if (matedit_j >= columns)
matedit_j = columns - 1;
if (refcount == 1) {
/* We have this array to ourselves so we can modify it in place */
err = dimension_array_ref(m, rows + 1, columns);
if (err != ERR_NONE) {
if (interactive)
free_vartype(newx);
return err;
}
rows++;
if (m->type == TYPE_REALMATRIX) {
for (i = rows * columns - 1; i >= (matedit_i + 1) * columns; i--) {
rm->array->is_string[i] = rm->array->is_string[i - columns];
rm->array->data[i] = rm->array->data[i - columns];
}
for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) {
rm->array->is_string[i] = 0;
rm->array->data[i] = 0;
}
} else {
for (i = 2 * rows * columns - 1;
i >= 2 * (matedit_i + 1) * columns; i--)
cm->array->data[i] = cm->array->data[i - 2 * columns];
for (i = 2 * matedit_i * columns;
i < 2 * (matedit_i + 1) * columns; i++)
cm->array->data[i] = 0;
}
} else {
/* We're sharing this array. I don't use disentangle() because it
* does not deal with resizing. */
int4 newsize = (rows + 1) * columns;
if (m->type == TYPE_REALMATRIX) {
realmatrix_data *array = (realmatrix_data *)
malloc(sizeof(realmatrix_data));
if (array == NULL) {
if (interactive)
free_vartype(newx);
return ERR_INSUFFICIENT_MEMORY;
}
array->data = (phloat *) malloc(newsize * sizeof(phloat));
if (array->data == NULL) {
if (interactive)
free_vartype(newx);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
array->is_string = (char *) malloc(newsize);
if (array->is_string == NULL) {
if (interactive)
free_vartype(newx);
free(array->data);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
for (i = 0; i < matedit_i * columns; i++) {
array->is_string[i] = rm->array->is_string[i];
array->data[i] = rm->array->data[i];
}
for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) {
array->is_string[i] = 0;
array->data[i] = 0;
}
for (i = (matedit_i + 1) * columns; i < newsize; i++) {
array->is_string[i] = rm->array->is_string[i - columns];
array->data[i] = rm->array->data[i - columns];
}
array->refcount = 1;
rm->array->refcount--;
rm->array = array;
rm->rows++;
} else {
complexmatrix_data *array = (complexmatrix_data *)
malloc(sizeof(complexmatrix_data));
if (array == NULL) {
if (interactive)
free_vartype(newx);
return ERR_INSUFFICIENT_MEMORY;
}
array->data = (phloat *) malloc(2 * newsize * sizeof(phloat));
if (array->data == NULL) {
if (interactive)
free_vartype(newx);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
for (i = 0; i < 2 * matedit_i * columns; i++)
array->data[i] = cm->array->data[i];
for (i = 2 * matedit_i * columns;
i < 2 * (matedit_i + 1) * columns; i++)
array->data[i] = 0;
for (i = 2 * (matedit_i + 1) * columns; i < 2 * newsize; i++)
array->data[i] = cm->array->data[i - 2 * columns];
array->refcount = 1;
cm->array->refcount--;
cm->array = array;
cm->rows++;
}
}
if (interactive) {
free_vartype(reg_x);
reg_x = newx;
}
mode_disable_stack_lift = true;
return ERR_NONE;
}
static void invrt_completion(int error, vartype *res) {
if (error == ERR_NONE)
unary_result(res);
}
int docmd_invrt(arg_struct *arg) {
if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX)
return ERR_INVALID_TYPE;
else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return linalg_inv(reg_x, invrt_completion);
}
int docmd_j_add(arg_struct *arg) {
int4 rows, columns;
int4 oldi = matedit_i;
int4 oldj = matedit_j;
int err = matedit_get_dim(&rows, &columns);
if (err != ERR_NONE)
return err;
if (++matedit_j >= columns) {
flags.f.matrix_edge_wrap = 1;
matedit_j = 0;
if (++matedit_i >= rows) {
flags.f.matrix_end_wrap = 1;
if (flags.f.grow) {
if (matedit_mode == 2)
err = dimension_array_ref(matedit_x, rows + 1, columns);
else
err = dimension_array(matedit_name, matedit_length,
rows + 1, columns);
if (err != ERR_NONE) {
matedit_i = oldi;
matedit_j = oldj;
return err;
}
matedit_i = rows;
} else
matedit_i = 0;
} else
flags.f.matrix_end_wrap = 0;
} else {
flags.f.matrix_edge_wrap = 0;
flags.f.matrix_end_wrap = 0;
}
return ERR_NONE;
}
int docmd_j_sub(arg_struct *arg) {
int4 rows, columns;
int err = matedit_get_dim(&rows, &columns);
if (err != ERR_NONE)
return err;
if (--matedit_j < 0) {
flags.f.matrix_edge_wrap = 1;
matedit_j = columns - 1;
if (--matedit_i < 0) {
flags.f.matrix_end_wrap = 1;
matedit_i = rows - 1;
} else
flags.f.matrix_end_wrap = 0;
} else {
flags.f.matrix_edge_wrap = 0;
flags.f.matrix_end_wrap = 0;
}
return ERR_NONE;
}
static int mappable_ln_1_x(phloat x, phloat *y) {
if (x <= -1)
return ERR_INVALID_DATA;
*y = log1p(x);
return ERR_NONE;
}
int docmd_ln_1_x(arg_struct *arg) {
if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_REALMATRIX) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_ln_1_x, NULL);
if (err == ERR_NONE)
unary_result(v);
return err;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_old(arg_struct *arg) {
return docmd_rclel(NULL);
}
int docmd_posa(arg_struct *arg) {
int pos = -1;
vartype *v;
if (reg_x->type == TYPE_REAL) {
phloat x = ((vartype_real *) reg_x)->x;
char c;
int i;
if (x < 0)
x = -x;
if (x >= 256)
return ERR_INVALID_DATA;
c = to_char(x);
for (i = 0; i < reg_alpha_length; i++)
if (reg_alpha[i] == c) {
pos = i;
break;
}
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
if (s->length != 0) {
int i, j;
for (i = 0; i < reg_alpha_length - s->length; i++) {
for (j = 0; j < s->length; j++)
if (reg_alpha[i + j] != s->text[j])
goto notfound;
pos = i;
break;
notfound:;
}
}
} else
return ERR_INVALID_TYPE;
v = new_real(pos);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
}
int docmd_putm(arg_struct *arg) {
vartype *m;
int4 i, j;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Shouldn't happen, but could, as long as I don't
* implement matrix locking
*/
return ERR_INVALID_TYPE;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX)
return ERR_INVALID_TYPE;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *src, *dst;
if (reg_x->type == TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
src = (vartype_realmatrix *) reg_x;
dst = (vartype_realmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->is_string[n2] = src->array->is_string[n1];
dst->array->data[n2] = src->array->data[n1];
}
return ERR_NONE;
} else if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *src = (vartype_realmatrix *) reg_x;
vartype_complexmatrix *dst = (vartype_complexmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
for (i = 0; i < src->rows * src->columns; i++)
if (src->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->data[n2 * 2] = src->array->data[n1];
dst->array->data[n2 * 2 + 1] = 0;
}
return ERR_NONE;
} else {
vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *dst = (vartype_complexmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->data[n2 * 2] = src->array->data[n1 * 2];
dst->array->data[n2 * 2 + 1] = src->array->data[n1 * 2 + 1];
}
return ERR_NONE;
}
}
int docmd_rclel(arg_struct *arg) {
vartype *m, *v;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
int4 n = matedit_i * rm->columns + matedit_j;
if (rm->array->is_string[n])
v = new_string(phloat_text(rm->array->data[n]),
phloat_length(rm->array->data[n]));
else
v = new_real(rm->array->data[n]);
} else if (m->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
int4 n = matedit_i * cm->columns + matedit_j;
v = new_complex(cm->array->data[2 * n],
cm->array->data[2 * n + 1]);
} else
return ERR_INVALID_TYPE;
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
recall_result(v);
return ERR_NONE;
}
int docmd_rclij(arg_struct *arg) {
vartype *i, *j;
if (matedit_mode == 0)
return ERR_NONEXISTENT;
i = new_real(matedit_i + 1);
j = new_real(matedit_j + 1);
if (i == NULL || j == NULL) {
free_vartype(i);
free_vartype(j);
return ERR_INSUFFICIENT_MEMORY;
}
recall_two_results(j, i);
return ERR_NONE;
}
int docmd_rnrm(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype *v;
vartype_realmatrix *rm = (vartype_realmatrix *) reg_x;
int4 size = rm->rows * rm->columns;
int4 i, j;
phloat max = 0;
for (i = 0; i < size; i++)
if (rm->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
for (i = 0; i < rm->rows; i++) {
phloat nrm = 0;
for (j = 0; j < rm->columns; j++) {
phloat x = rm->array->data[i * rm->columns + j];
if (x >= 0)
nrm += x;
else
nrm -= x;
}
if (p_isinf(nrm)) {
if (flags.f.range_error_ignore)
max = POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
break;
}
if (nrm > max)
max = nrm;
}
v = new_real(max);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype *v;
vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x;
int4 i, j;
phloat max = 0;
for (i = 0; i < cm->rows; i++) {
phloat nrm = 0;
for (j = 0; j < cm->columns; j++) {
phloat re = cm->array->data[2 * (i * cm->columns + j)];
phloat im = cm->array->data[2 * (i * cm->columns + j) + 1];
nrm += hypot(re, im);
}
if (p_isinf(nrm)) {
if (flags.f.range_error_ignore)
max = POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
break;
}
if (nrm > max)
max = nrm;
}
v = new_real(max);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_rsum(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) reg_x;
vartype_realmatrix *res;
int4 size = rm->rows * rm->columns;
int4 i, j;
for (i = 0; i < size; i++)
if (rm->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
res = (vartype_realmatrix *) new_realmatrix(rm->rows, 1);
if (res == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rm->rows; i++) {
phloat sum = 0;
int inf;
for (j = 0; j < rm->columns; j++)
sum += rm->array->data[i * rm->columns + j];
if ((inf = p_isinf(sum)) != 0) {
if (flags.f.range_error_ignore)
sum = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
res->array->data[i] = sum;
}
unary_result((vartype *) res);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *res;
int4 i, j;
res = (vartype_complexmatrix *) new_complexmatrix(cm->rows, 1);
if (res == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < cm->rows; i++) {
phloat sum_re = 0, sum_im = 0;
int inf;
for (j = 0; j < cm->columns; j++) {
sum_re += cm->array->data[2 * (i * cm->columns + j)];
sum_im += cm->array->data[2 * (i * cm->columns + j) + 1];
}
if ((inf = p_isinf(sum_re)) != 0) {
if (flags.f.range_error_ignore)
sum_re = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
if ((inf = p_isinf(sum_im)) != 0) {
if (flags.f.range_error_ignore)
sum_im = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
res->array->data[2 * i] = sum_re;
res->array->data[2 * i + 1] = sum_im;
}
unary_result((vartype *) res);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_swap_r(arg_struct *arg) {
vartype *m;
phloat xx, yy;
int4 x, y, i;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Should not happen, but could, as long as I don't implement
* matrix locking. */
return ERR_INVALID_TYPE;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
xx = ((vartype_real *) reg_x)->x;
if (xx <= -2147483648.0 || xx >= 2147483648.0)
return ERR_DIMENSION_ERROR;
x = to_int4(xx);
if (x == 0)
return ERR_DIMENSION_ERROR;
if (x < 0)
x = -x;
x--;
yy = ((vartype_real *) reg_y)->x;
if (yy <= -2147483648.0 || yy >= 2147483648.0)
return ERR_DIMENSION_ERROR;
y = to_int4(yy);
if (y == 0)
return ERR_DIMENSION_ERROR;
if (y < 0)
y = -y;
y--;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
if (x > rm->rows || y > rm->rows)
return ERR_DIMENSION_ERROR;
else if (x == y)
return ERR_NONE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rm->columns; i++) {
int4 n1 = x * rm->columns + i;
int4 n2 = y * rm->columns + i;
char tempc = rm->array->is_string[n1];
phloat tempds = rm->array->data[n1];
rm->array->is_string[n1] = rm->array->is_string[n2];
rm->array->data[n1] = rm->array->data[n2];
rm->array->is_string[n2] = tempc;
rm->array->data[n2] = tempds;
}
return ERR_NONE;
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
if (x > cm->rows || y > cm->rows)
return ERR_DIMENSION_ERROR;
else if (x == y)
return ERR_NONE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < 2 * cm->columns; i++) {
int4 n1 = x * 2 * cm->columns + i;
int4 n2 = y * 2 * cm->columns + i;
phloat tempd = cm->array->data[n1];
cm->array->data[n1] = cm->array->data[n2];
cm->array->data[n2] = tempd;
}
return ERR_NONE;
}
}
static int mappable_sinh_r(phloat x, phloat *y) {
int inf;
*y = sinh(x);
if ((inf = p_isinf(*y)) != 0) {
if (flags.f.range_error_ignore)
*y = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
static int mappable_sinh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) {
phloat sinhxre, coshxre;
phloat sinxim, cosxim;
int inf;
sinhxre = sinh(xre);
coshxre = cosh(xre);
sincos(xim, &sinxim, &cosxim);
*yre = sinhxre * cosxim;
if ((inf = p_isinf(*yre)) != 0) {
if (flags.f.range_error_ignore)
*yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
*yim = coshxre * sinxim;
if ((inf = p_isinf(*yim)) != 0) {
if (flags.f.range_error_ignore)
*yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
int docmd_sinh(arg_struct *arg) {
if (reg_x->type != TYPE_STRING) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_sinh_r, mappable_sinh_c);
if (err == ERR_NONE)
unary_result(v);
return err;
} else
return ERR_ALPHA_DATA_IS_INVALID;
}
int docmd_stoel(arg_struct *arg) {
vartype *m;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Should not happen, but could, as long as I don't implement
* matrix locking.
*/
return ERR_INVALID_TYPE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
int4 n = matedit_i * rm->columns + matedit_j;
if (reg_x->type == TYPE_REAL) {
rm->array->is_string[n] = 0;
rm->array->data[n] = ((vartype_real *) reg_x)->x;
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
int i;
rm->array->is_string[n] = 1;
phloat_length(rm->array->data[n]) = s->length;
for (i = 0; i < s->length; i++)
phloat_text(rm->array->data[n])[i] = s->text[i];
return ERR_NONE;
} else
return ERR_INVALID_TYPE;
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
int4 n = matedit_i * cm->columns + matedit_j;
if (reg_x->type == TYPE_REAL) {
cm->array->data[2 * n] = ((vartype_real *) reg_x)->x;
cm->array->data[2 * n + 1] = 0;
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEX) {
vartype_complex *c = (vartype_complex *) reg_x;
cm->array->data[2 * n] = c->re;
cm->array->data[2 * n + 1] = c->im;
return ERR_NONE;
} else
return ERR_INVALID_TYPE;
}
}
int docmd_stoij(arg_struct *arg) {
vartype *m;
phloat x, y;
int4 i, j;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
x = ((vartype_real *) reg_x)->x;
if (x <= -2147483648.0 || x >= 2147483648.0)
return ERR_DIMENSION_ERROR;
j = to_int4(x);
if (j < 0)
j = -j;
y = ((vartype_real *) reg_y)->x;
if (y <= -2147483648.0 || y >= 2147483648.0)
return ERR_DIMENSION_ERROR;
i = to_int4(y);
if (i < 0)
i = -i;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
if (i == 0 || i > rm->rows || j == 0 || j > rm->columns)
return ERR_DIMENSION_ERROR;
} else if (m->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
if (i == 0 || i > cm->rows || j == 0 || j > cm->columns)
return ERR_DIMENSION_ERROR;
} else
/* Should not happen, but could, as long as I don't implement
* matrix locking. */
return ERR_INVALID_TYPE;
matedit_i = i - 1;
matedit_j = j - 1;
return ERR_NONE;
}
static int mappable_tanh_r(phloat x, phloat *y) {
*y = tanh(x);
return ERR_NONE;
}
static int mappable_tanh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) {
phloat sinhxre, coshxre;
phloat sinxim, cosxim;
phloat re_sinh, re_cosh, im_sinh, im_cosh, abs_cosh;
int inf;
sinhxre = sinh(xre);
coshxre = cosh(xre);
sincos(xim, &sinxim, &cosxim);
re_sinh = sinhxre * cosxim;
im_sinh = coshxre * sinxim;
re_cosh = coshxre * cosxim;
im_cosh = sinhxre * sinxim;
abs_cosh = hypot(re_cosh, im_cosh);
if (abs_cosh == 0) {
if (flags.f.range_error_ignore) {
*yre = re_sinh * im_sinh + re_cosh * im_cosh > 0 ? POS_HUGE_PHLOAT
: NEG_HUGE_PHLOAT;
*yim = im_sinh * re_cosh - re_sinh * im_cosh > 0 ? POS_HUGE_PHLOAT
: NEG_HUGE_PHLOAT;
} else
return ERR_OUT_OF_RANGE;
}
*yre = (re_sinh * re_cosh + im_sinh * im_cosh) / abs_cosh / abs_cosh;
if ((inf = p_isinf(*yre)) != 0) {
if (flags.f.range_error_ignore)
*yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
*yim = (im_sinh * re_cosh - re_sinh * im_cosh) / abs_cosh / abs_cosh;
if ((inf = p_isinf(*yim)) != 0) {
if (flags.f.range_error_ignore)
*yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
int docmd_tanh(arg_struct *arg) {
if (reg_x->type != TYPE_STRING) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_tanh_r, mappable_tanh_c);
if (err == ERR_NONE)
unary_result(v);
return err;
} else
return ERR_ALPHA_DATA_IS_INVALID;
}
int docmd_trans(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *src = (vartype_realmatrix *) reg_x;
vartype_realmatrix *dst;
int4 rows = src->rows;
int4 columns = src->columns;
int4 i, j;
dst = (vartype_realmatrix *) new_realmatrix(columns, rows);
if (dst == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
int4 n1 = i * columns + j;
int4 n2 = j * rows + i;
dst->array->is_string[n2] = src->array->is_string[n1];
dst->array->data[n2] = src->array->data[n1];
}
unary_result((vartype *) dst);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *dst;
int4 rows = src->rows;
int4 columns = src->columns;
int4 i, j;
dst = (vartype_complexmatrix *) new_complexmatrix(columns, rows);
if (dst == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
int4 n1 = 2 * (i * columns + j);
int4 n2 = 2 * (j * rows + i);
dst->array->data[n2] = src->array->data[n1];
dst->array->data[n2 + 1] = src->array->data[n1 + 1];
}
unary_result((vartype *) dst);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_wrap(arg_struct *arg) {
flags.f.grow = 0;
return ERR_NONE;
}
int docmd_x_swap(arg_struct *arg) {
vartype *v;
int err = generic_rcl(arg, &v);
if (err != ERR_NONE)
return err;
err = generic_sto(arg, 0);
if (err != ERR_NONE)
free_vartype(v);
else {
free_vartype(reg_x);
reg_x = v;
if (flags.f.trace_print && flags.f.printer_exists)
docmd_prx(NULL);
}
return err;
}
#define DIR_LEFT 0
#define DIR_RIGHT 1
#define DIR_UP 2
#define DIR_DOWN 3
static int matedit_move(int direction) {
vartype *m, *v;
vartype_realmatrix *rm;
vartype_complexmatrix *cm;
int4 rows, columns, new_i, new_j, old_n, new_n;
int edge_flag = 0;
int end_flag = 0;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
rm = (vartype_realmatrix *) m;
rows = rm->rows;
columns = rm->columns;
} else if (m->type == TYPE_COMPLEXMATRIX) {
cm = (vartype_complexmatrix *) m;
rows = cm->rows;
columns = cm->columns;
} else
return ERR_INVALID_TYPE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
new_i = matedit_i;
new_j = matedit_j;
switch (direction) {
case DIR_LEFT:
if (--new_j < 0) {
edge_flag = 1;
new_j = columns - 1;
if (--new_i < 0) {
end_flag = 1;
new_i = rows - 1;
}
}
break;
case DIR_RIGHT:
if (++new_j >= columns) {
edge_flag = 1;
new_j = 0;
if (++new_i >= rows) {
end_flag = 1;
if (flags.f.grow) {
int err;
if (matedit_mode == 2)
err = dimension_array_ref(matedit_x,
rows + 1, columns);
else
err = dimension_array(matedit_name, matedit_length,
rows + 1, columns);
if (err != ERR_NONE)
return err;
new_i = rows++;
} else
new_i = 0;
}
}
break;
case DIR_UP:
if (--new_i < 0) {
edge_flag = 1;
new_i = rows - 1;
if (--new_j < 0) {
end_flag = 1;
new_j = columns - 1;
}
}
break;
case DIR_DOWN:
if (++new_i >= rows) {
edge_flag = 1;
new_i = 0;
if (++new_j >= columns) {
end_flag = 1;
new_j = 0;
}
}
break;
}
old_n = matedit_i * columns + matedit_j;
new_n = new_i * columns + new_j;
if (m->type == TYPE_REALMATRIX) {
if (old_n != new_n) {
if (rm->array->is_string[new_n])
v = new_string(phloat_text(rm->array->data[new_n]),
phloat_length(rm->array->data[new_n]));
else
v = new_real(rm->array->data[new_n]);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
if (reg_x->type == TYPE_REAL) {
rm->array->is_string[old_n] = 0;
rm->array->data[old_n] = ((vartype_real *) reg_x)->x;
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
int i;
rm->array->is_string[old_n] = 1;
phloat_length(rm->array->data[old_n]) = s->length;
for (i = 0; i < s->length; i++)
phloat_text(rm->array->data[old_n])[i] = s->text[i];
} else {
free_vartype(v);
return ERR_INVALID_TYPE;
}
} else /* m->type == TYPE_COMPLEXMATRIX */ {
if (old_n != new_n) {
v = new_complex(cm->array->data[2 * new_n],
cm->array->data[2 * new_n + 1]);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
if (reg_x->type == TYPE_REAL) {
cm->array->data[2 * old_n] = ((vartype_real *) reg_x)->x;
cm->array->data[2 * old_n + 1] = 0;
} else if (reg_x->type == TYPE_COMPLEX) {
vartype_complex *c = (vartype_complex *) reg_x;
cm->array->data[2 * old_n] = c->re;
cm->array->data[2 * old_n + 1] = c->im;
} else {
free_vartype(v);
return ERR_INVALID_TYPE;
}
}
matedit_i = new_i;
matedit_j = new_j;
flags.f.matrix_edge_wrap = edge_flag;
flags.f.matrix_end_wrap = end_flag;
if (old_n != new_n) {
free_vartype(reg_x);
reg_x = v;
}
mode_disable_stack_lift = true;
if (flags.f.trace_print && flags.f.printer_enable)
docmd_prx(NULL);
return ERR_NONE;
}
int docmd_left(arg_struct *arg) {
return matedit_move(DIR_LEFT);
}
int docmd_up(arg_struct *arg) {
return matedit_move(DIR_UP);
}
int docmd_down(arg_struct *arg) {
return matedit_move(DIR_DOWN);
}
int docmd_right(arg_struct *arg) {
return matedit_move(DIR_RIGHT);
}
int docmd_percent_ch(arg_struct *arg) {
phloat x, y, r;
int inf;
vartype *v;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
x = ((vartype_real *) reg_x)->x;
y = ((vartype_real *) reg_y)->x;
if (y == 0)
return ERR_DIVIDE_BY_0;
r = (x - y) / y * 100;
if ((inf = p_isinf(r)) != 0) {
if (flags.f.range_error_ignore)
r = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
v = new_real(r);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
/* Binary function, but unary result, like % */
unary_result(v);
return ERR_NONE;
}
static vartype *matx_v;
static void matx_completion(int error, vartype *res) {
if (error != ERR_NONE) {
free_vartype(matx_v);
return;
}
store_var("MATX", 4, res);
matedit_prev_appmenu = MENU_MATRIX_SIMQ;
set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1);
/* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX]
* commands can only be invoked from the SIMQ menu; the SIMQ menu
* has no exit callback, so leaving it never fails.
*/
set_appmenu_exitcallback(1);
if (res->type == TYPE_REALMATRIX) {
vartype_realmatrix *m = (vartype_realmatrix *) res;
vartype_real *v = (vartype_real *) matx_v;
v->x = m->array->data[0];
} else {
vartype_complexmatrix *m = (vartype_complexmatrix *) res;
vartype_complex *v = (vartype_complex *) matx_v;
v->re = m->array->data[0];
v->im = m->array->data[1];
}
free_vartype(reg_x);
reg_x = matx_v;
matedit_mode = 3;
matedit_length = 4;
matedit_name[0] = 'M';
matedit_name[1] = 'A';
matedit_name[2] = 'T';
matedit_name[3] = 'X';
matedit_i = 0;
matedit_j = 0;
}
static int matabx(int which) {
vartype *mat, *v;
switch (which) {
case 0:
mat = recall_var("MATA", 4);
break;
case 1:
mat = recall_var("MATB", 4);
break;
case 2: {
vartype *mata, *matb;
mata = recall_var("MATA", 4);
if (mata == NULL)
return ERR_NONEXISTENT;
if (mata->type != TYPE_REALMATRIX
&& mata->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
matb = recall_var("MATB", 4);
if (matb == NULL)
return ERR_NONEXISTENT;
if (matb->type != TYPE_REALMATRIX
&& matb->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
if (mata->type == TYPE_REALMATRIX && matb->type == TYPE_REALMATRIX)
matx_v = new_real(0);
else
matx_v = new_complex(0, 0);
if (matx_v == NULL)
return ERR_INSUFFICIENT_MEMORY;
return linalg_div(matb, mata, matx_completion);
}
}
if (mat->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) mat;
if (rm->array->is_string[0])
v = new_string(phloat_text(rm->array->data[0]),
phloat_length(rm->array->data[0]));
else
v = new_real(rm->array->data[0]);
} else {
vartype_complexmatrix *cm = (vartype_complexmatrix *) mat;
v = new_complex(cm->array->data[0], cm->array->data[1]);
}
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
matedit_prev_appmenu = MENU_MATRIX_SIMQ;
set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1);
/* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX]
* commands can only be invoked from the SIMQ menu; the SIMQ menu
* has no exit callback, so leaving it never fails.
*/
set_appmenu_exitcallback(1);
free_vartype(reg_x);
reg_x = v;
matedit_mode = 3;
matedit_length = 4;
matedit_name[0] = 'M';
matedit_name[1] = 'A';
matedit_name[2] = 'T';
matedit_name[3] = which == 0 ? 'A' : 'B';
matedit_i = 0;
matedit_j = 0;
return ERR_NONE;
}
int docmd_mata(arg_struct *arg) {
return matabx(0);
}
int docmd_matb(arg_struct *arg) {
return matabx(1);
}
int docmd_matx(arg_struct *arg) {
return matabx(2);
}
int docmd_simq(arg_struct *arg) {
vartype *m, *mata, *matb, *matx;
int4 dim;
int err;
if (arg->type != ARGTYPE_NUM)
return ERR_INVALID_TYPE;
dim = arg->val.num;
if (dim <= 0)
return ERR_DIMENSION_ERROR;
m = recall_var("MATA", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
mata = dup_vartype(m);
if (mata == NULL)
return ERR_INSUFFICIENT_MEMORY;
err = dimension_array_ref(mata, dim, dim);
if (err != ERR_NONE)
goto abort_and_free_a;
} else {
mata = new_realmatrix(dim, dim);
if (mata == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
m = recall_var("MATB", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
matb = dup_vartype(m);
if (matb == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a;
}
err = dimension_array_ref(matb, dim, 1);
if (err != ERR_NONE)
goto abort_and_free_a_b;
} else {
matb = new_realmatrix(dim, 1);
if (matb == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a;
}
}
m = recall_var("MATX", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
matx = dup_vartype(m);
if (matx == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a_b;
}
err = dimension_array_ref(matx, dim, 1);
if (err != ERR_NONE)
goto abort_and_free_a_b_x;
} else {
matx = new_realmatrix(dim, 1);
if (matx == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a_b;
}
}
err = set_menu_return_err(MENULEVEL_APP, MENU_MATRIX_SIMQ);
if (err != ERR_NONE) {
/* Didn't work; we're stuck in the matrix editor
* waiting for the user to put something valid into X.
* (Then again, how can anyone issue the SIMQ command if
* they're in the matrix editor? SIMQ has the 'hidden'
* command property. Oh, well, better safe than sorry...)
*/
abort_and_free_a_b_x:
free_vartype(matx);
abort_and_free_a_b:
free_vartype(matb);
abort_and_free_a:
free_vartype(mata);
return err;
}
store_var("MATX", 4, matx);
store_var("MATB", 4, matb);
store_var("MATA", 4, mata);
return ERR_NONE;
}
static int max_min_helper(int do_max) {
vartype *m;
vartype_realmatrix *rm;
phloat max_or_min_value = do_max ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
int4 i, max_or_min_index = 0;
vartype *new_x, *new_y;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX)
return ERR_INVALID_TYPE;
rm = (vartype_realmatrix *) m;
for (i = matedit_i; i < rm->rows; i++) {
int4 index = i * rm->columns + matedit_j;
phloat e;
if (rm->array->is_string[index])
return ERR_ALPHA_DATA_IS_INVALID;
e = rm->array->data[index];
if (do_max ? e >= max_or_min_value : e <= max_or_min_value) {
max_or_min_value = e;
max_or_min_index = i;
}
}
new_x = new_real(max_or_min_value);
if (new_x == NULL)
return ERR_INSUFFICIENT_MEMORY;
new_y = new_real(max_or_min_index + 1);
if (new_y == NULL) {
free_vartype(new_x);
return ERR_INSUFFICIENT_MEMORY;
}
recall_two_results(new_x, new_y);
return ERR_NONE;
}
int docmd_max(arg_struct *arg) {
return max_min_helper(1);
}
int docmd_min(arg_struct *arg) {
return max_min_helper(0);
}
int docmd_find(arg_struct *arg) {
vartype *m;
if (reg_x->type == TYPE_REALMATRIX || reg_x->type == TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm;
int4 i, j, p = 0;
if (reg_x->type == TYPE_COMPLEX)
return ERR_NO;
rm = (vartype_realmatrix *) m;
if (reg_x->type == TYPE_REAL) {
phloat d = ((vartype_real *) reg_x)->x;
for (i = 0; i < rm->rows; i++)
for (j = 0; j < rm->columns; j++)
if (!rm->array->is_string[p] && rm->array->data[p] == d) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p++;
} else /* reg_x->type == TYPE_STRING */ {
vartype_string *s = (vartype_string *) reg_x;
for (i = 0; i < rm->rows; i++)
for (j = 0; j < rm->columns; j++)
if (rm->array->is_string[p]
&& string_equals(s->text, s->length,
phloat_text(rm->array->data[p]),
phloat_length(rm->array->data[p]))) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p++;
}
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm;
int4 i, j, p = 0;
phloat re, im;
if (reg_x->type != TYPE_COMPLEX)
return ERR_NO;
cm = (vartype_complexmatrix *) m;
re = ((vartype_complex *) reg_x)->re;
im = ((vartype_complex *) reg_x)->im;
for (i = 0; i < cm->rows; i++)
for (j = 0; j < cm->columns; j++)
if (cm->array->data[p] == re && cm->array->data[p + 1] == im) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p += 2;
}
return ERR_NO;
}
int docmd_xrom(arg_struct *arg) {
return ERR_NONEXISTENT;
}
| axd1967/free42s | common/core_commands4.cc | C++ | gpl-2.0 | 48,956 |
/*
* mpc8610-pcm.h - ALSA PCM interface for the Freescale MPC8610 SoC
*
* 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 _MPC8610_PCM_H
#define _MPC8610_PCM_H
struct ccsr_dma {
u8 res0[0x100];
struct ccsr_dma_channel {
__be32 mr; /* Mode register */
__be32 sr; /* Status register */
__be32 eclndar; /* Current link descriptor extended addr reg */
__be32 clndar; /* Current link descriptor address register */
__be32 satr; /* Source attributes register */
__be32 sar; /* Source address register */
__be32 datr; /* Destination attributes register */
__be32 dar; /* Destination address register */
__be32 bcr; /* Byte count register */
__be32 enlndar; /* Next link descriptor extended address reg */
__be32 nlndar; /* Next link descriptor address register */
u8 res1[4];
__be32 eclsdar; /* Current list descriptor extended addr reg */
__be32 clsdar; /* Current list descriptor address register */
__be32 enlsdar; /* Next list descriptor extended address reg */
__be32 nlsdar; /* Next list descriptor address register */
__be32 ssr; /* Source stride register */
__be32 dsr; /* Destination stride register */
u8 res2[0x38];
} channel[4];
__be32 dgsr;
};
#define CCSR_DMA_MR_BWC_DISABLED 0x0F000000
#define CCSR_DMA_MR_BWC_SHIFT 24
#define CCSR_DMA_MR_BWC_MASK 0x0F000000
#define CCSR_DMA_MR_BWC(x) \
((ilog2(x) << CCSR_DMA_MR_BWC_SHIFT) & CCSR_DMA_MR_BWC_MASK)
#define CCSR_DMA_MR_EMP_EN 0x00200000
#define CCSR_DMA_MR_EMS_EN 0x00040000
#define CCSR_DMA_MR_DAHTS_MASK 0x00030000
#define CCSR_DMA_MR_DAHTS_1 0x00000000
#define CCSR_DMA_MR_DAHTS_2 0x00010000
#define CCSR_DMA_MR_DAHTS_4 0x00020000
#define CCSR_DMA_MR_DAHTS_8 0x00030000
#define CCSR_DMA_MR_SAHTS_MASK 0x0000C000
#define CCSR_DMA_MR_SAHTS_1 0x00000000
#define CCSR_DMA_MR_SAHTS_2 0x00004000
#define CCSR_DMA_MR_SAHTS_4 0x00008000
#define CCSR_DMA_MR_SAHTS_8 0x0000C000
#define CCSR_DMA_MR_DAHE 0x00002000
#define CCSR_DMA_MR_SAHE 0x00001000
#define CCSR_DMA_MR_SRW 0x00000400
#define CCSR_DMA_MR_EOSIE 0x00000200
#define CCSR_DMA_MR_EOLNIE 0x00000100
#define CCSR_DMA_MR_EOLSIE 0x00000080
#define CCSR_DMA_MR_EIE 0x00000040
#define CCSR_DMA_MR_XFE 0x00000020
#define CCSR_DMA_MR_CDSM_SWSM 0x00000010
#define CCSR_DMA_MR_CA 0x00000008
#define CCSR_DMA_MR_CTM 0x00000004
#define CCSR_DMA_MR_CC 0x00000002
#define CCSR_DMA_MR_CS 0x00000001
#define CCSR_DMA_SR_TE 0x00000080
#define CCSR_DMA_SR_CH 0x00000020
#define CCSR_DMA_SR_PE 0x00000010
#define CCSR_DMA_SR_EOLNI 0x00000008
#define CCSR_DMA_SR_CB 0x00000004
#define CCSR_DMA_SR_EOSI 0x00000002
#define CCSR_DMA_SR_EOLSI 0x00000001
/* ECLNDAR takes bits 32-36 of the CLNDAR register */
static inline u32 CCSR_DMA_ECLNDAR_ADDR(u64 x)
{
return (x >> 32) & 0xf;
}
#define CCSR_DMA_CLNDAR_ADDR(x) ((x) & 0xFFFFFFFE)
#define CCSR_DMA_CLNDAR_EOSIE 0x00000008
/* SATR and DATR, combined */
#define CCSR_DMA_ATR_PBATMU 0x20000000
#define CCSR_DMA_ATR_TFLOWLVL_0 0x00000000
#define CCSR_DMA_ATR_TFLOWLVL_1 0x06000000
#define CCSR_DMA_ATR_TFLOWLVL_2 0x08000000
#define CCSR_DMA_ATR_TFLOWLVL_3 0x0C000000
#define CCSR_DMA_ATR_PCIORDER 0x02000000
#define CCSR_DMA_ATR_SME 0x01000000
#define CCSR_DMA_ATR_NOSNOOP 0x00040000
#define CCSR_DMA_ATR_SNOOP 0x00050000
#define CCSR_DMA_ATR_ESAD_MASK 0x0000000F
/**
* List Descriptor for extended chaining mode DMA operations.
*
* The CLSDAR register points to the first (in a linked-list) List
* Descriptor. Each object must be aligned on a 32-byte boundary. Each
* list descriptor points to a linked-list of link Descriptors.
*/
struct fsl_dma_list_descriptor {
__be64 next; /* Address of next list descriptor */
__be64 first_link; /* Address of first link descriptor */
__be32 source; /* Source stride */
__be32 dest; /* Destination stride */
u8 res[8]; /* Reserved */
} __attribute__ ((aligned(32), packed));
/**
* Link Descriptor for basic and extended chaining mode DMA operations.
*
* A Link Descriptor points to a single DMA buffer. Each link descriptor
* must be aligned on a 32-byte boundary.
*/
struct fsl_dma_link_descriptor {
__be32 source_attr; /* Programmed into SATR register */
__be32 source_addr; /* Programmed into SAR register */
__be32 dest_attr; /* Programmed into DATR register */
__be32 dest_addr; /* Programmed into DAR register */
__be64 next; /* Address of next link descriptor */
__be32 count; /* Byte count */
u8 res[4]; /* Reserved */
} __attribute__ ((aligned(32), packed));
<<<<<<< HEAD
=======
/* DMA information needed to create a snd_soc_dai object
*
* ssi_stx_phys: bus address of SSI STX register to use
* ssi_srx_phys: bus address of SSI SRX register to use
* dma[0]: points to the DMA channel to use for playback
* dma[1]: points to the DMA channel to use for capture
* dma_irq[0]: IRQ of the DMA channel to use for playback
* dma_irq[1]: IRQ of the DMA channel to use for capture
*/
struct fsl_dma_info {
dma_addr_t ssi_stx_phys;
dma_addr_t ssi_srx_phys;
struct ccsr_dma_channel __iomem *dma_channel[2];
unsigned int dma_irq[2];
};
extern struct snd_soc_platform fsl_soc_platform;
int fsl_dma_configure(struct fsl_dma_info *dma_info);
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
#endif
| Core2idiot/Kernel-Samsung-3.0...- | sound/soc/fsl/fsl_dma.h | C | gpl-2.0 | 5,573 |
ALTER TABLE db_version CHANGE COLUMN required_z0652_134_01_mangos_creature_model_info required_z0662_135_01_mangos_mangos_string bit;
DELETE FROM mangos_string WHERE entry BETWEEN 1149 AND 1151;
INSERT INTO mangos_string VALUES
(1149,' (Pool %u)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(1150,' (Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(1151,' (Pool %u Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DELETE FROM mangos_string WHERE entry in (515, 517, 1110, 1111, 1137);
INSERT INTO mangos_string VALUES
(515,'%d%s - |cffffffff|Hcreature:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CHAT (.list creature)
(517,'%d%s, Entry %d - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_MIXED_LIST_CHAT (.gobject near)
(1110,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CONSOLE
(1111,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_LIST_CONSOLE
(1137,'%d%s - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); -- LANG_GO_LIST_CHAT (.list object) | natedahl32/portalclassic | sql/archive/0.12.2/z0662_135_01_mangos_mangos_string.sql | SQL | gpl-2.0 | 1,248 |
/*
* HT Editor
* syssdl.h
*
* Copyright (C) 2004 Stefan Weyergraf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __SYSSDL_H__
#define __SYSSDL_H__
#ifdef __MACH__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#include "system/display.h"
#include "system/systhread.h"
extern SDL_Surface * gSDLScreen;
class SDLSystemDisplay: public SystemDisplay {
protected:
DisplayCharacteristics mSDLChar;
byte * mSDLFrameBuffer;
bool mChangingScreen;
SDL_Surface * mSDLClientScreen;
sys_mutex mRedrawMutex;
SDL_Cursor * mVisibleCursor;
SDL_Cursor * mInvisibleCursor;
uint bitsPerPixelToXBitmapPad(uint bitsPerPixel);
void dumpDisplayChar(const DisplayCharacteristics &chr);
public:
char * mTitle;
DisplayCharacteristics mSDLChartemp;
SDL_cond *mWaitcondition;
bool mChangeResRet;
uint32 mEventThreadID;
SDLSystemDisplay(const char *title, const DisplayCharacteristics &chr, int redraw_ms);
void finishMenu();
virtual void updateTitle();
virtual int toString(char *buf, int buflen) const;
void toggleFullScreen();
virtual void displayShow();
virtual void convertCharacteristicsToHost(DisplayCharacteristics &aHostChar, const DisplayCharacteristics &aClientChar);
virtual bool changeResolution(const DisplayCharacteristics &aCharacteristics);
virtual bool changeResolutionREAL(const DisplayCharacteristics &aCharacteristics);
virtual void getHostCharacteristics(Container &modes);
virtual void setMouseGrab(bool enable);
virtual void initCursor();
};
#endif
| tycho/pearpc | src/system/ui/sdl/syssdl.h | C | gpl-2.0 | 2,112 |
/***************************************************/
/*! \class BiQuad
\brief STK biquad (two-pole, two-zero) filter class.
This class implements a two-pole, two-zero digital filter.
Methods are provided for creating a resonance or notch in the
frequency response while maintaining a constant filter gain.
by Perry R. Cook and Gary P. Scavone, 1995-2012.
*/
/***************************************************/
#include "BiQuad.h"
#include <cmath>
namespace stk {
BiQuad :: BiQuad() : Filter()
{
b_.resize( 3, 0.0 );
a_.resize( 3, 0.0 );
b_[0] = 1.0;
a_[0] = 1.0;
inputs_.resize( 3, 1, 0.0 );
outputs_.resize( 3, 1, 0.0 );
Stk::addSampleRateAlert( this );
}
BiQuad :: ~BiQuad()
{
Stk::removeSampleRateAlert( this );
}
void BiQuad :: setCoefficients( StkFloat b0, StkFloat b1, StkFloat b2, StkFloat a1, StkFloat a2, bool clearState )
{
b_[0] = b0;
b_[1] = b1;
b_[2] = b2;
a_[1] = a1;
a_[2] = a2;
if ( clearState ) this->clear();
}
void BiQuad :: sampleRateChanged( StkFloat newRate, StkFloat oldRate )
{
if ( !ignoreSampleRateChange_ ) {
std::cerr << "BiQuad::sampleRateChanged: you may need to recompute filter coefficients!";
handleError( StkError::WARNING );
}
}
void BiQuad :: setResonance( StkFloat frequency, StkFloat radius, bool normalize )
{
#if defined(_STK_DEBUG_)
if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) {
std::cerr << "BiQuad::setResonance: frequency argument (" << frequency << ") is out of range!";
handleError( StkError::WARNING ); return;
}
if ( radius < 0.0 || radius >= 1.0 ) {
std::cerr << "BiQuad::setResonance: radius argument (" << radius << ") is out of range!";
handleError( StkError::WARNING ); return;
}
#endif
a_[2] = radius * radius;
a_[1] = -2.0 * radius * cos( TWO_PI * frequency / Stk::sampleRate() );
if ( normalize ) {
// Use zeros at +- 1 and normalize the filter peak gain.
b_[0] = 0.5 - 0.5 * a_[2];
b_[1] = 0.0;
b_[2] = -b_[0];
}
}
void BiQuad :: setNotch( StkFloat frequency, StkFloat radius )
{
#if defined(_STK_DEBUG_)
if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) {
std::cerr << "BiQuad::setNotch: frequency argument (" << frequency << ") is out of range!";
handleError( StkError::WARNING ); return;
}
if ( radius < 0.0 ) {
std::cerr << "BiQuad::setNotch: radius argument (" << radius << ") is negative!";
handleError( StkError::WARNING ); return;
}
#endif
// This method does not attempt to normalize the filter gain.
b_[2] = radius * radius;
b_[1] = (StkFloat) -2.0 * radius * cos( TWO_PI * (double) frequency / Stk::sampleRate() );
}
void BiQuad :: setEqualGainZeroes( void )
{
b_[0] = 1.0;
b_[1] = 0.0;
b_[2] = -1.0;
}
} // stk namespace
| TheAlphaNerd/theremax | include/stk/BiQuad.cpp | C++ | gpl-2.0 | 2,784 |
/*
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 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 "mpqfile.h"
#include <deque>
#include <cstdio>
#include "StormLib.h"
MPQFile::MPQFile(HANDLE mpq, const char* filename, bool warnNoExist /*= true*/) :
eof(false),
buffer(0),
pointer(0),
size(0)
{
HANDLE file;
if (!SFileOpenFileEx(mpq, filename, SFILE_OPEN_PATCHED_FILE, &file))
{
if (warnNoExist || GetLastError() != ERROR_FILE_NOT_FOUND)
fprintf(stderr, "Can't open %s, err=%u!\n", filename, GetLastError());
eof = true;
return;
}
DWORD hi = 0;
size = SFileGetFileSize(file, &hi);
if (hi)
{
fprintf(stderr, "Can't open %s, size[hi] = %u!\n", filename, uint32(hi));
SFileCloseFile(file);
eof = true;
return;
}
if (size <= 1)
{
fprintf(stderr, "Can't open %s, size = %u!\n", filename, uint32(size));
SFileCloseFile(file);
eof = true;
return;
}
DWORD read = 0;
buffer = new char[size];
if (!SFileReadFile(file, buffer, size, &read) || size != read)
{
fprintf(stderr, "Can't read %s, size=%u read=%u!\n", filename, uint32(size), uint32(read));
SFileCloseFile(file);
eof = true;
return;
}
SFileCloseFile(file);
}
size_t MPQFile::read(void* dest, size_t bytes)
{
if (eof) return 0;
size_t rpos = pointer + bytes;
if (rpos > size) {
bytes = size - pointer;
eof = true;
}
memcpy(dest, &(buffer[pointer]), bytes);
pointer = rpos;
return bytes;
}
void MPQFile::seek(int offset)
{
pointer = offset;
eof = (pointer >= size);
}
void MPQFile::seekRelative(int offset)
{
pointer += offset;
eof = (pointer >= size);
}
void MPQFile::close()
{
if (buffer) delete[] buffer;
buffer = 0;
eof = true;
}
| MistyWorld/MistyWorld_6xx | src/outils/vmap4_extracteur/mpqfile.cpp | C++ | gpl-2.0 | 2,513 |
<div><p><br/></p></div><div class="container">
<div class="row">
<div id="index" class="col-md-3">
<div >
<div class="panel panel-default">
<div class="panel-heading">Classes</div>
<div class="panel-body"><a href="/docs/api/BB_Frame"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Frame</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_RecPlayer"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">RecPlayer</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_Recording"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Recording</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_Session"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Session</span></span></a></div>
<div class="panel-body"><a href="/docs/api/_global_"><span class="indent" style="padding-left:0px;"><i class="icon-jsdoc icon-jsdoc-namespace"></i><span class="jsdoc-class-index">_global_</span></span></a></div>
</div>
</div>
</div>
<div id="content" class="col-md-9">
<pre class="prettyprint linenums">goog.provide('BB.Session');
goog.require('BB.Frame');
goog.require('BB.Recording');
/**
*
* @param {string} backendUrl
* @param {number=} fps
* @param {string=} title
* @param {string=} url
*
* @constructor
*/
BB.Session = function(backendUrl, fps, title, url) {
/** @type {string} */
this.backendUrl = backendUrl;
/** @type {number} */
this.fps = fps || 3;
/** @type {number} */
this.TICK_MILLI = 1000 / this.fps;
/** @type {string} */
this.title = title || BB.Session.getPageTitle();
/** @type {string} */
this.url = url || BB.Session.getPageUrl();
/** @type {Array.<BB.Frame>} */
this.frames = [];
/** @type {boolean} */
this.active = false;
/** @type {number} Pointer to setTimeout */
this.timer;
/** @type {boolean} */
this.clicked = false;
this.init();
};
/**
* @private
*/
BB.Session.prototype.init = function(){
var self = this;
document.addEventListener('mousemove', function(e) {
BB.Session.mouse.x = e.clientX || e.pageX;
BB.Session.mouse.y = e.clientY || e.pageY;
}, false);
document.addEventListener('click', function(e) {
self.clicked = true;
}, false);
};
/**
* Start recording a session
*/
BB.Session.prototype.start = function(){
if (!this.active) {
this.active = true;
this.tick();
}
};
/**
* Stop recording a session
*/
BB.Session.prototype.stop = function(){
clearTimeout(this.timer);
this.active = false;
};
/**
* Captures the current frame
*
* @private
*/
BB.Session.prototype.tick = function(){
if (this.active) {
var frame = new BB.Frame(
BB.Frame.getCurrentWin(),
BB.Frame.getCurrentScroll(),
BB.Frame.getCurrentMouse(),
this.clicked
);
this.frames.push(frame);
this.timer = setTimeout(this.tick.bind(this), this.TICK_MILLI);
this.clicked = false;
}
};
/**
* Send recording to backend server
*/
BB.Session.prototype.upload = function(){
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('recording=' + this.toString());
};
/**
*
* @returns {string}
*/
BB.Session.getPageTitle = function() {
var el = document.getElementsByTagName('title');
var title = 'Untitled document';
if (el.length > 0) {
title = el[0].textContent;
}
return title;
};
/**
*
* @returns {string}
*/
BB.Session.getPageUrl = function(){
return window.location.href;
};
/**
*
* @returns {string}
*/
BB.Session.prototype.toString = function(){
return JSON.stringify(
new BB.Recording(this.title, this.url, BB.Frame.getClientRes(), this.fps, this.frames)
);
};
/**
*
* @type {BB.mouse}
*/
BB.Session.mouse = {
x: 0,
y: 0
};
</div>
</div>
</div>
<script type="text/javascript">
prettyPrint();
var i = 1;
$('#source-code li').each(function() {
$(this).attr({ id: 'line' + (i++) });
});
</script>
</div></div> | formigone/big-brother-js | promo-site/application/views/scripts/docs/src/BB_Session_js.php | PHP | gpl-2.0 | 4,500 |
import urllib2
import appuifw, e32
from key_codes import *
class Drinker(object):
def __init__(self):
self.id = 0
self.name = ""
self.prom = 0.0
self.idle = ""
self.drinks = 0
def get_drinker_list():
data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n")
drinkers = []
for data_row in data:
if data_row == '': continue
fields = data_row.split('|')
drinker = Drinker()
drinker.id = int(fields[0])
drinker.name = fields[1]
drinker.drinks = int(fields[2])
drinker.prom = float(fields[3])
drinker.idle = fields[4]
drinkers.append(drinker)
return drinkers
def get_listbox_items(drinkers):
items = []
for drinker in drinkers:
items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle)))
return items
appuifw.app.title = u"Alkoholilaskuri"
app_lock = e32.Ao_lock()
#Define the exit function
def quit():
app_lock.signal()
appuifw.app.exit_key_handler = quit
drinkers = get_drinker_list()
items = get_listbox_items(drinkers)
#Define a function that is called when an item is selected
def handle_selection():
selected_drinker = drinkers[lb.current()]
urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id))
appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info')
new_drinkers = get_drinker_list()
items = get_listbox_items(new_drinkers)
lb.set_list(items, lb.current())
#Create an instance of Listbox and set it as the application's body
lb = appuifw.Listbox(items, handle_selection)
appuifw.app.body = lb
app_lock.wait()
| deggis/drinkcounter | clients/s60-python/client.py | Python | gpl-2.0 | 1,757 |
package com.mikesantiago.mariofighter;
import static com.mikesantiago.mariofighter.GlobalVariables.PPM;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.mikesantiago.mariofighter.assets.Animation;
public class PlayerOne
{
public enum Direction
{
LEFT, RIGHT, STOP
}
private BodyDef playerBodyDef;
private Body playerBody;
private PolygonShape playerShape;
private FixtureDef playerFixtureDef;
private Fixture playerFixture;
private boolean isMoving = false;
private Direction currentDirection = Direction.RIGHT;
private Animation animationRight;
private Animation animationLeft;
public boolean getMoving(){return isMoving;}
public Direction getCurrentDirection(){return currentDirection;}
public PlayerOne(World worldToCreateIn)
{
playerBodyDef = new BodyDef();
playerBodyDef.type = BodyType.DynamicBody;
playerBodyDef.position.set(new Vector2(32f / PPM, 256f / PPM));
playerBody = worldToCreateIn.createBody(playerBodyDef);
playerShape = new PolygonShape();
playerShape.setAsBox((32f / 2) / PPM, (36f / 2) / PPM);
playerFixtureDef = new FixtureDef();
playerFixtureDef.shape = playerShape;
playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT;
playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT;
playerFixture = playerBody.createFixture(playerFixtureDef);
playerFixture.setUserData("body");
//create foot sensor
{
playerShape.setAsBox(2 / PPM, 2 / PPM, new Vector2(0, -32 / PPM), 0);
playerFixtureDef.shape = playerShape;
playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT;
playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT;
playerFixtureDef.isSensor = true;
playerBody.createFixture(playerFixtureDef).setUserData("FOOT");
}
CreateAnimation();
System.out.println("Player 1 created!");
}
private void CreateAnimation()
{
float updateInterval = 1 / 20f;
Texture tex = GlobalVariables.manager.GetTexture("mario");
TextureRegion[] sprites = TextureRegion.split(tex, 16, 28)[0];
if(animationRight == null)
animationRight = new Animation();
animationRight.setFrames(sprites, updateInterval);
if(animationLeft == null)
animationLeft = new Animation();
TextureRegion[] leftSprites = TextureRegion.split(tex, 16, 28)[0];
for(TextureRegion tr : leftSprites)
tr.flip(true, false);
animationLeft.setFrames(leftSprites, updateInterval);
sprWidth = sprites[0].getRegionWidth();
sprHeight = sprites[0].getRegionHeight();
}
private int sprWidth, sprHeight;
public void update(float dt)
{
if(this.isMoving)
{
animationRight.update(dt);
animationLeft.update(dt);
}
}
public void render(SpriteBatch sb)
{
if(!sb.isDrawing())
sb.begin();
sb.setProjectionMatrix(GlobalVariables.maincamera.combined);
if(this.isMoving)
{
if(this.currentDirection == Direction.RIGHT)
{
sb.draw(animationRight.getFrame(),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
else if(this.currentDirection == Direction.LEFT)
{
sb.draw(animationLeft.getFrame(),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
}
else
{
if(this.currentDirection == Direction.RIGHT)
{
sb.draw(animationRight.getFrame(0),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
else if(this.currentDirection == Direction.LEFT)
{
sb.draw(animationLeft.getFrame(0),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
}
if(sb.isDrawing())
sb.end();
}
public void setMoving(boolean a){this.isMoving = a;}
public void setCurrentDirection(Direction a){currentDirection = a;}
public BodyDef getPlayerBodyDef() {
return playerBodyDef;
}
public void setPlayerBodyDef(BodyDef playerBodyDef) {
this.playerBodyDef = playerBodyDef;
}
public Body getPlayerBody() {
return playerBody;
}
public void setPlayerBody(Body playerBody) {
this.playerBody = playerBody;
}
public PolygonShape getPlayerShape() {
return playerShape;
}
public void setPlayerShape(PolygonShape playerShape) {
this.playerShape = playerShape;
}
public FixtureDef getPlayerFixtureDef() {
return playerFixtureDef;
}
public void setPlayerFixtureDef(FixtureDef playerFixtureDef) {
this.playerFixtureDef = playerFixtureDef;
}
public Fixture getPlayerFixture() {
return playerFixture;
}
public void setPlayerFixture(Fixture playerFixture) {
this.playerFixture = playerFixture;
}
}
| Luigifan/MarioFighter | core/src/com/mikesantiago/mariofighter/PlayerOne.java | Java | gpl-2.0 | 5,195 |
#include "exec/def-helper.h"
#ifdef CONFIG_TCG_PLUGIN
DEF_HELPER_FLAGS_4(tcg_plugin_pre_tb, 0, void, i64, i64, i64, i64)
#endif
DEF_HELPER_2(exception, noreturn, env, i32)
DEF_HELPER_3(exception_cause, noreturn, env, i32, i32)
DEF_HELPER_4(exception_cause_vaddr, noreturn, env, i32, i32, i32)
DEF_HELPER_3(debug_exception, noreturn, env, i32, i32)
DEF_HELPER_FLAGS_1(nsa, TCG_CALL_NO_RWG_SE, i32, i32)
DEF_HELPER_FLAGS_1(nsau, TCG_CALL_NO_RWG_SE, i32, i32)
DEF_HELPER_2(wsr_windowbase, void, env, i32)
DEF_HELPER_4(entry, void, env, i32, i32, i32)
DEF_HELPER_2(retw, i32, env, i32)
DEF_HELPER_2(rotw, void, env, i32)
DEF_HELPER_3(window_check, void, env, i32, i32)
DEF_HELPER_1(restore_owb, void, env)
DEF_HELPER_2(movsp, void, env, i32)
DEF_HELPER_2(wsr_lbeg, void, env, i32)
DEF_HELPER_2(wsr_lend, void, env, i32)
DEF_HELPER_1(simcall, void, env)
DEF_HELPER_1(dump_state, void, env)
DEF_HELPER_3(waiti, void, env, i32, i32)
DEF_HELPER_3(timer_irq, void, env, i32, i32)
DEF_HELPER_2(advance_ccount, void, env, i32)
DEF_HELPER_1(check_interrupts, void, env)
DEF_HELPER_3(check_atomctl, void, env, i32, i32)
DEF_HELPER_2(wsr_rasid, void, env, i32)
DEF_HELPER_FLAGS_3(rtlb0, TCG_CALL_NO_RWG_SE, i32, env, i32, i32)
DEF_HELPER_FLAGS_3(rtlb1, TCG_CALL_NO_RWG_SE, i32, env, i32, i32)
DEF_HELPER_3(itlb, void, env, i32, i32)
DEF_HELPER_3(ptlb, i32, env, i32, i32)
DEF_HELPER_4(wtlb, void, env, i32, i32, i32)
DEF_HELPER_2(wsr_ibreakenable, void, env, i32)
DEF_HELPER_3(wsr_ibreaka, void, env, i32, i32)
DEF_HELPER_3(wsr_dbreaka, void, env, i32, i32)
DEF_HELPER_3(wsr_dbreakc, void, env, i32, i32)
DEF_HELPER_2(wur_fcr, void, env, i32)
DEF_HELPER_FLAGS_1(abs_s, TCG_CALL_NO_RWG_SE, f32, f32)
DEF_HELPER_FLAGS_1(neg_s, TCG_CALL_NO_RWG_SE, f32, f32)
DEF_HELPER_3(add_s, f32, env, f32, f32)
DEF_HELPER_3(sub_s, f32, env, f32, f32)
DEF_HELPER_3(mul_s, f32, env, f32, f32)
DEF_HELPER_4(madd_s, f32, env, f32, f32, f32)
DEF_HELPER_4(msub_s, f32, env, f32, f32, f32)
DEF_HELPER_FLAGS_3(ftoi, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32)
DEF_HELPER_FLAGS_3(ftoui, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32)
DEF_HELPER_3(itof, f32, env, i32, i32)
DEF_HELPER_3(uitof, f32, env, i32, i32)
DEF_HELPER_4(un_s, void, env, i32, f32, f32)
DEF_HELPER_4(oeq_s, void, env, i32, f32, f32)
DEF_HELPER_4(ueq_s, void, env, i32, f32, f32)
DEF_HELPER_4(olt_s, void, env, i32, f32, f32)
DEF_HELPER_4(ult_s, void, env, i32, f32, f32)
DEF_HELPER_4(ole_s, void, env, i32, f32, f32)
DEF_HELPER_4(ule_s, void, env, i32, f32, f32)
#include "exec/def-helper.h"
| cedric-vincent/qemu | target-xtensa/helper.h | C | gpl-2.0 | 2,522 |
<?php
class Request {
public static function redirect($to) {
header('Location: ' . Config::get('url') . $to);
}
public static function path() {
return $_SERVER['REQUEST_URI'];
}
public static function method() {
$method = $_SERVER['REQUEST_METHOD'];
if($method === 'PUT') return 'put';
if($method === 'GET') return 'post';
if($method === 'GET') return 'get';
if($method === 'HEAD') return 'head';
if($method === 'DELETE') return 'delete';
if($method === 'OPTIONS') return 'options';
return false;
}
public static function isMethod($method) {
if(self::method() === $method) {
return true;
}
return false;
}
}
| thatasko/elsa | system/modules/Request.php | PHP | gpl-2.0 | 708 |
# show_off_web_app/services
| mikeckennedy/cookiecutter-course | src/ch8_sharing_your_template/show_off_web_app/show_off_web_app/services/readme.md | Markdown | gpl-2.0 | 33 |
/* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <media/rc-core.h>
#include <media/gpio-ir-recv.h>
#define GPIO_IR_DRIVER_NAME "gpio-rc-recv"
#define GPIO_IR_DEVICE_NAME "gpio_ir_recv"
struct gpio_rc_dev {
struct rc_dev *rcdev;
unsigned int gpio_nr;
bool active_low;
int can_sleep;
};
#ifdef CONFIG_OF
/*
* Translate OpenFirmware node properties into platform_data
*/
static int gpio_ir_recv_get_devtree_pdata(struct device *dev,
struct gpio_ir_recv_platform_data *pdata)
{
struct device_node *np = dev->of_node;
enum of_gpio_flags flags;
int gpio;
gpio = of_get_gpio_flags(np, 0, &flags);
if (gpio < 0) {
if (gpio != -EPROBE_DEFER)
dev_err(dev, "Failed to get gpio flags (%d)\n", gpio);
return gpio;
}
pdata->gpio_nr = gpio;
pdata->active_low = (flags & OF_GPIO_ACTIVE_LOW);
/* probe() takes care of map_name == NULL or allowed_protos == 0 */
pdata->map_name = of_get_property(np, "linux,rc-map-name", NULL);
pdata->allowed_protos = 0;
return 0;
}
static struct of_device_id gpio_ir_recv_of_match[] = {
{ .compatible = "gpio-ir-receiver", },
{ },
};
MODULE_DEVICE_TABLE(of, gpio_ir_recv_of_match);
#else /* !CONFIG_OF */
#define gpio_ir_recv_get_devtree_pdata(dev, pdata) (-ENOSYS)
#endif
static irqreturn_t gpio_ir_recv_irq(int irq, void *dev_id)
{
struct gpio_rc_dev *gpio_dev = dev_id;
unsigned int gval;
int rc = 0;
enum raw_event_type type = IR_SPACE;
if (gpio_dev->can_sleep)
gval = gpio_get_value_cansleep(gpio_dev->gpio_nr);
else
gval = gpio_get_value(gpio_dev->gpio_nr);
if (gval < 0)
goto err_get_value;
if (gpio_dev->active_low)
gval = !gval;
if (gval == 1)
type = IR_PULSE;
rc = ir_raw_event_store_edge(gpio_dev->rcdev, type);
if (rc < 0)
goto err_get_value;
ir_raw_event_handle(gpio_dev->rcdev);
err_get_value:
return IRQ_HANDLED;
}
static int gpio_ir_recv_probe(struct platform_device *pdev)
{
struct gpio_rc_dev *gpio_dev;
struct rc_dev *rcdev;
const struct gpio_ir_recv_platform_data *pdata =
pdev->dev.platform_data;
int rc;
if (pdev->dev.of_node) {
struct gpio_ir_recv_platform_data *dtpdata =
devm_kzalloc(&pdev->dev, sizeof(*dtpdata), GFP_KERNEL);
if (!dtpdata)
return -ENOMEM;
rc = gpio_ir_recv_get_devtree_pdata(&pdev->dev, dtpdata);
if (rc)
return rc;
pdata = dtpdata;
}
if (!pdata)
return -EINVAL;
if (pdata->gpio_nr < 0)
return -EINVAL;
gpio_dev = kzalloc(sizeof(struct gpio_rc_dev), GFP_KERNEL);
if (!gpio_dev)
return -ENOMEM;
rcdev = rc_allocate_device();
if (!rcdev) {
rc = -ENOMEM;
goto err_allocate_device;
}
rcdev->priv = gpio_dev;
rcdev->driver_type = RC_DRIVER_IR_RAW;
rcdev->input_name = GPIO_IR_DEVICE_NAME;
rcdev->input_phys = GPIO_IR_DEVICE_NAME "/input0";
rcdev->input_id.bustype = BUS_HOST;
rcdev->input_id.vendor = 0x0001;
rcdev->input_id.product = 0x0001;
rcdev->input_id.version = 0x0100;
rcdev->dev.parent = &pdev->dev;
rcdev->driver_name = GPIO_IR_DRIVER_NAME;
<<<<<<< HEAD
rcdev->map_name = RC_MAP_SAMSUNG_NECX;
=======
if (pdata->allowed_protos)
rcdev->allowed_protos = pdata->allowed_protos;
else
rcdev->allowed_protos = RC_BIT_ALL;
rcdev->map_name = pdata->map_name ?: RC_MAP_EMPTY;
>>>>>>> common/android-3.10.y
gpio_dev->rcdev = rcdev;
gpio_dev->gpio_nr = pdata->gpio_nr;
gpio_dev->active_low = pdata->active_low;
rc = gpio_request(pdata->gpio_nr, "gpio-ir-recv");
if (rc < 0)
goto err_gpio_request;
gpio_dev->can_sleep = gpio_cansleep(pdata->gpio_nr);
rc = gpio_direction_input(pdata->gpio_nr);
if (rc < 0)
goto err_gpio_direction_input;
rc = rc_register_device(rcdev);
if (rc < 0) {
dev_err(&pdev->dev, "failed to register rc device\n");
goto err_register_rc_device;
}
platform_set_drvdata(pdev, gpio_dev);
rc = request_any_context_irq(gpio_to_irq(pdata->gpio_nr),
gpio_ir_recv_irq,
IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
"gpio-ir-recv-irq", gpio_dev);
if (rc < 0)
goto err_request_irq;
device_init_wakeup(&pdev->dev, pdata->can_wakeup);
return 0;
err_request_irq:
platform_set_drvdata(pdev, NULL);
rc_unregister_device(rcdev);
rcdev = NULL;
err_register_rc_device:
err_gpio_direction_input:
gpio_free(pdata->gpio_nr);
err_gpio_request:
rc_free_device(rcdev);
err_allocate_device:
kfree(gpio_dev);
return rc;
}
static int gpio_ir_recv_remove(struct platform_device *pdev)
{
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
free_irq(gpio_to_irq(gpio_dev->gpio_nr), gpio_dev);
platform_set_drvdata(pdev, NULL);
rc_unregister_device(gpio_dev->rcdev);
gpio_free(gpio_dev->gpio_nr);
kfree(gpio_dev);
return 0;
}
#ifdef CONFIG_PM
static int gpio_ir_recv_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
if (device_may_wakeup(dev))
enable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr));
else
disable_irq(gpio_to_irq(gpio_dev->gpio_nr));
return 0;
}
static int gpio_ir_recv_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
if (device_may_wakeup(dev))
disable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr));
else
enable_irq(gpio_to_irq(gpio_dev->gpio_nr));
return 0;
}
static const struct dev_pm_ops gpio_ir_recv_pm_ops = {
.suspend = gpio_ir_recv_suspend,
.resume = gpio_ir_recv_resume,
};
#endif
static struct platform_driver gpio_ir_recv_driver = {
.probe = gpio_ir_recv_probe,
.remove = gpio_ir_recv_remove,
.driver = {
.name = GPIO_IR_DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(gpio_ir_recv_of_match),
#ifdef CONFIG_PM
.pm = &gpio_ir_recv_pm_ops,
#endif
},
};
module_platform_driver(gpio_ir_recv_driver);
MODULE_DESCRIPTION("GPIO IR Receiver driver");
MODULE_LICENSE("GPL v2");
| javelinanddart/android_kernel_3.10_ville | drivers/media/rc/gpio-ir-recv.c | C | gpl-2.0 | 6,544 |
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Sam
*/
package com.caucho.quercus.lib.spl;
import com.caucho.quercus.env.Value;
public interface OuterIterator
extends Iterator
{
public Value getInnerIterator();
}
| dlitz/resin | modules/quercus/src/com/caucho/quercus/lib/spl/OuterIterator.java | Java | gpl-2.0 | 1,187 |
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// This file is part of Libmoleculizer
//
// Copyright (C) 2001-2009 The Molecular Sciences Institute.
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// Moleculizer is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Moleculizer 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 Moleculizer; if not, write to the Free Software Foundation
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
//
// END HEADER
//
// Original Author:
// Larry Lok, Research Fellow, Molecular Sciences Institute, 2001
//
// Modifing Authors:
//
//
#ifndef FND_DUMPSTREAM_H
#define FND_DUMPSTREAM_H
#include <fstream>
#include <vector>
#include "utl/xcpt.hh"
#include "utl/autoVector.hh"
#include "fnd/dumpable.hh"
#include "fnd/dmpColumn.hh"
namespace fnd
{
class dumpStream :
public utl::autoVector<basicDmpColumn>
{
// Now that the output stream and everything else is passed to
// the dumpables through a dumpArg, these are here mainly to
// memory-manage the stream, to emphasize that this class is what
// corresponds to a .dmp file, and to facilitate the construction
// of dumpArg's through getOstream(), in particular.
std::string fileName;
std::ostream* pOs;
std::ofstream* pFileStream;
public:
// Use a genuine file path, "-" for std::cout, "+" for std::cerr.
dumpStream( const std::string& rFileName )
throw( utl::xcpt );
~dumpStream( void )
{
// This is null if the output stream not actually a file.
delete pFileStream;
}
std::ostream&
getOstream( void ) const
{
return *pOs;
}
// Returns the file name given at construction time, including
// the special cases.
const std::string&
getFileName( void ) const
{
return fileName;
}
// Initializes output stream and writes column headers.
void
init( void )
throw( utl::xcpt );
// Writes a line in the output file.
void
doDump( void );
};
}
#endif // FND_DUMPSTREAM_H
| ecell/libmoleculizer | src/libmoleculizer/fnd/dumpStream.hh | C++ | gpl-2.0 | 2,822 |
from config import config, ConfigSlider, ConfigSelection, ConfigYesNo, \
ConfigEnableDisable, ConfigSubsection, ConfigBoolean, ConfigSelectionNumber, ConfigNothing, NoSave
from enigma import eAVSwitch, getDesktop
from SystemInfo import SystemInfo
from os import path as os_path
class AVSwitch:
def setInput(self, input):
INPUT = { "ENCODER": 0, "SCART": 1, "AUX": 2 }
eAVSwitch.getInstance().setInput(INPUT[input])
def setColorFormat(self, value):
eAVSwitch.getInstance().setColorFormat(value)
def setAspectRatio(self, value):
eAVSwitch.getInstance().setAspectRatio(value)
def setSystem(self, value):
eAVSwitch.getInstance().setVideomode(value)
def getOutputAspect(self):
valstr = config.av.aspectratio.value
if valstr in ("4_3_letterbox", "4_3_panscan"): # 4:3
return (4,3)
elif valstr == "16_9": # auto ... 4:3 or 16:9
try:
aspect_str = open("/proc/stb/vmpeg/0/aspect", "r").read()
if aspect_str == "1": # 4:3
return (4,3)
except IOError:
pass
elif valstr in ("16_9_always", "16_9_letterbox"): # 16:9
pass
elif valstr in ("16_10_letterbox", "16_10_panscan"): # 16:10
return (16,10)
return (16,9)
def getFramebufferScale(self):
aspect = self.getOutputAspect()
fb_size = getDesktop(0).size()
return (aspect[0] * fb_size.height(), aspect[1] * fb_size.width())
def getAspectRatioSetting(self):
valstr = config.av.aspectratio.value
if valstr == "4_3_letterbox":
val = 0
elif valstr == "4_3_panscan":
val = 1
elif valstr == "16_9":
val = 2
elif valstr == "16_9_always":
val = 3
elif valstr == "16_10_letterbox":
val = 4
elif valstr == "16_10_panscan":
val = 5
elif valstr == "16_9_letterbox":
val = 6
return val
def setAspectWSS(self, aspect=None):
if not config.av.wss.value:
value = 2 # auto(4:3_off)
else:
value = 1 # auto
eAVSwitch.getInstance().setWSS(value)
def InitAVSwitch():
config.av = ConfigSubsection()
config.av.yuvenabled = ConfigBoolean(default=False)
colorformat_choices = {"cvbs": _("CVBS"), "rgb": _("RGB"), "svideo": _("S-Video")}
# when YUV is not enabled, don't let the user select it
if config.av.yuvenabled.value:
colorformat_choices["yuv"] = _("YPbPr")
# ikseong
config.av.colorformat = ConfigSelection(choices=colorformat_choices, default="cvbs")
config.av.aspectratio = ConfigSelection(choices={
"4_3_letterbox": _("4:3 Letterbox"),
"4_3_panscan": _("4:3 PanScan"),
"16_9": _("16:9"),
"16_9_always": _("16:9 always"),
"16_10_letterbox": _("16:10 Letterbox"),
"16_10_panscan": _("16:10 PanScan"),
"16_9_letterbox": _("16:9 Letterbox")},
default = "4_3_letterbox")
config.av.aspect = ConfigSelection(choices={
"4_3": _("4:3"),
"16_9": _("16:9"),
"16_10": _("16:10"),
"auto": _("Automatic")},
default = "auto")
config.av.policy_169 = ConfigSelection(choices={
# TRANSLATORS: (aspect ratio policy: black bars on top/bottom) in doubt, keep english term.
"letterbox": _("Letterbox"),
# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
"panscan": _("Pan&Scan"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
"scale": _("Just Scale")},
default = "letterbox")
config.av.policy_43 = ConfigSelection(choices={
# TRANSLATORS: (aspect ratio policy: black bars on left/right) in doubt, keep english term.
"pillarbox": _("Pillarbox"),
# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
"panscan": _("Pan&Scan"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, with stretching the left/right)
"nonlinear": _("Nonlinear"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
"scale": _("Just Scale")},
default = "pillarbox")
config.av.tvsystem = ConfigSelection(choices = {"pal": _("PAL"), "ntsc": _("NTSC"), "multinorm": _("multinorm")}, default="pal")
config.av.wss = ConfigEnableDisable(default = True)
config.av.defaultac3 = ConfigYesNo(default = False)
config.av.generalAC3delay = ConfigSelectionNumber(-1000, 1000, 25, default = 0)
config.av.generalPCMdelay = ConfigSelectionNumber(-1000, 1000, 25, default = 0)
config.av.vcrswitch = ConfigEnableDisable(default = False)
iAVSwitch = AVSwitch()
def setColorFormat(configElement):
map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3}
iAVSwitch.setColorFormat(map[configElement.value])
def setAspectRatio(configElement):
map = {"4_3_letterbox": 0, "4_3_panscan": 1, "16_9": 2, "16_9_always": 3, "16_10_letterbox": 4, "16_10_panscan": 5, "16_9_letterbox" : 6}
iAVSwitch.setAspectRatio(map[configElement.value])
def setSystem(configElement):
map = {"pal": 0, "ntsc": 1, "multinorm" : 2}
iAVSwitch.setSystem(map[configElement.value])
def setWSS(configElement):
iAVSwitch.setAspectWSS()
# this will call the "setup-val" initial
config.av.colorformat.addNotifier(setColorFormat)
config.av.aspectratio.addNotifier(setAspectRatio)
config.av.tvsystem.addNotifier(setSystem)
config.av.wss.addNotifier(setWSS)
iAVSwitch.setInput("ENCODER") # init on startup
SystemInfo["ScartSwitch"] = eAVSwitch.getInstance().haveScartSwitch()
try:
can_downmix = open("/proc/stb/audio/ac3_choices", "r").read()[:-1].find("downmix") != -1
except:
can_downmix = False
SystemInfo["CanDownmixAC3"] = can_downmix
if can_downmix:
def setAC3Downmix(configElement):
open("/proc/stb/audio/ac3", "w").write(configElement.value and "downmix" or "passthrough")
config.av.downmix_ac3 = ConfigYesNo(default = True)
config.av.downmix_ac3.addNotifier(setAC3Downmix)
try:
can_downmix_aac = open("/proc/stb/audio/aac_choices", "r").read()[:-1].find("downmix") != -1
except:
can_downmix_aac = False
SystemInfo["CanDownmixAAC"] = can_downmix_aac
if can_downmix_aac:
def setAACDownmix(configElement):
open("/proc/stb/audio/aac", "w").write(configElement.value and "downmix" or "passthrough")
config.av.downmix_aac = ConfigYesNo(default = True)
config.av.downmix_aac.addNotifier(setAACDownmix)
try:
can_osd_alpha = open("/proc/stb/video/alpha", "r") and True or False
except:
can_osd_alpha = False
SystemInfo["CanChangeOsdAlpha"] = can_osd_alpha
def setAlpha(config):
open("/proc/stb/video/alpha", "w").write(str(config.value))
if can_osd_alpha:
config.av.osd_alpha = ConfigSlider(default=255, limits=(0,255))
config.av.osd_alpha.addNotifier(setAlpha)
if os_path.exists("/proc/stb/vmpeg/0/pep_scaler_sharpness"):
def setScaler_sharpness(config):
myval = int(config.value)
try:
print "--> setting scaler_sharpness to: %0.8X" % myval
open("/proc/stb/vmpeg/0/pep_scaler_sharpness", "w").write("%0.8X" % myval)
open("/proc/stb/vmpeg/0/pep_apply", "w").write("1")
except IOError:
print "couldn't write pep_scaler_sharpness"
config.av.scaler_sharpness = ConfigSlider(default=13, limits=(0,26))
config.av.scaler_sharpness.addNotifier(setScaler_sharpness)
else:
config.av.scaler_sharpness = NoSave(ConfigNothing())
| eesatfan/vuplus-enigma2 | lib/python/Components/AVSwitch.py | Python | gpl-2.0 | 7,088 |
/*
* Network block device - make block devices work over TCP
*
* Note that you can not swap over this thing, yet. Seems to work but
* deadlocks sometimes - you can not swap over TCP in general.
*
* Copyright 1997-2000, 2008 Pavel Machek <[email protected]>
* Parts copyright 2001 Steven Whitehouse <[email protected]>
*
* This file is released under GPLv2 or later.
*
* (part of code stolen from loop.c)
*/
#include <linux/major.h>
#include <linux/blkdev.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/bio.h>
#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/ioctl.h>
#include <linux/mutex.h>
#include <linux/compiler.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/net.h>
#include <linux/kthread.h>
#include <asm/uaccess.h>
#include <asm/types.h>
#include <linux/nbd.h>
#define NBD_MAGIC 0x68797548
#ifdef NDEBUG
#define dprintk(flags, fmt...)
#else /* NDEBUG */
#define dprintk(flags, fmt...) do { \
if (debugflags & (flags)) printk(KERN_DEBUG fmt); \
} while (0)
#define DBG_IOCTL 0x0004
#define DBG_INIT 0x0010
#define DBG_EXIT 0x0020
#define DBG_BLKDEV 0x0100
#define DBG_RX 0x0200
#define DBG_TX 0x0400
static unsigned int debugflags;
#endif /* NDEBUG */
static unsigned int nbds_max = 16;
static struct nbd_device *nbd_dev;
static int max_part;
/*
* Use just one lock (or at most 1 per NIC). Two arguments for this:
* 1. Each NIC is essentially a synchronization point for all servers
* accessed through that NIC so there's no need to have more locks
* than NICs anyway.
* 2. More locks lead to more "Dirty cache line bouncing" which will slow
* down each lock to the point where they're actually slower than just
* a single lock.
* Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
*/
static DEFINE_SPINLOCK(nbd_lock);
#ifndef NDEBUG
static const char *ioctl_cmd_to_ascii(int cmd)
{
switch (cmd) {
case NBD_SET_SOCK: return "set-sock";
case NBD_SET_BLKSIZE: return "set-blksize";
case NBD_SET_SIZE: return "set-size";
case NBD_SET_TIMEOUT: return "set-timeout";
case NBD_SET_FLAGS: return "set-flags";
case NBD_DO_IT: return "do-it";
case NBD_CLEAR_SOCK: return "clear-sock";
case NBD_CLEAR_QUE: return "clear-que";
case NBD_PRINT_DEBUG: return "print-debug";
case NBD_SET_SIZE_BLOCKS: return "set-size-blocks";
case NBD_DISCONNECT: return "disconnect";
case BLKROSET: return "set-read-only";
case BLKFLSBUF: return "flush-buffer-cache";
}
return "unknown";
}
static const char *nbdcmd_to_ascii(int cmd)
{
switch (cmd) {
case NBD_CMD_READ: return "read";
case NBD_CMD_WRITE: return "write";
case NBD_CMD_DISC: return "disconnect";
case NBD_CMD_FLUSH: return "flush";
case NBD_CMD_TRIM: return "trim/discard";
}
return "invalid";
}
#endif /* NDEBUG */
static void nbd_end_request(struct request *req)
{
int error = req->errors ? -EIO : 0;
struct request_queue *q = req->q;
unsigned long flags;
dprintk(DBG_BLKDEV, "%s: request %p: %s\n", req->rq_disk->disk_name,
req, error ? "failed" : "done");
spin_lock_irqsave(q->queue_lock, flags);
__blk_end_request_all(req, error);
spin_unlock_irqrestore(q->queue_lock, flags);
}
static void sock_shutdown(struct nbd_device *nbd, int lock)
{
/* Forcibly shutdown the socket causing all listeners
* to error
*
* FIXME: This code is duplicated from sys_shutdown, but
* there should be a more generic interface rather than
* calling socket ops directly here */
if (lock)
mutex_lock(&nbd->tx_lock);
if (nbd->sock) {
dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
nbd->sock = NULL;
}
if (lock)
mutex_unlock(&nbd->tx_lock);
}
static void nbd_xmit_timeout(unsigned long arg)
{
struct task_struct *task = (struct task_struct *)arg;
printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
task->comm, task->pid);
force_sig(SIGKILL, task);
}
/*
* Send or receive packet.
*/
static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
int msg_flags)
{
struct socket *sock = nbd->sock;
int result;
struct msghdr msg;
struct kvec iov;
sigset_t blocked, oldset;
unsigned long pflags = current->flags;
if (unlikely(!sock)) {
dev_err(disk_to_dev(nbd->disk),
"Attempted %s on closed socket in sock_xmit\n",
(send ? "send" : "recv"));
return -EINVAL;
}
/* Allow interception of SIGKILL only
* Don't allow other signals to interrupt the transmission */
siginitsetinv(&blocked, sigmask(SIGKILL));
sigprocmask(SIG_SETMASK, &blocked, &oldset);
current->flags |= PF_MEMALLOC;
do {
sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
iov.iov_base = buf;
iov.iov_len = size;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = msg_flags | MSG_NOSIGNAL;
if (send) {
struct timer_list ti;
if (nbd->xmit_timeout) {
init_timer(&ti);
ti.function = nbd_xmit_timeout;
ti.data = (unsigned long)current;
ti.expires = jiffies + nbd->xmit_timeout;
add_timer(&ti);
}
result = kernel_sendmsg(sock, &msg, &iov, 1, size);
if (nbd->xmit_timeout)
del_timer_sync(&ti);
} else
result = kernel_recvmsg(sock, &msg, &iov, 1, size,
msg.msg_flags);
if (signal_pending(current)) {
siginfo_t info;
printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
task_pid_nr(current), current->comm,
dequeue_signal_lock(current, ¤t->blocked, &info));
result = -EINTR;
sock_shutdown(nbd, !send);
break;
}
if (result <= 0) {
if (result == 0)
result = -EPIPE; /* short read */
break;
}
size -= result;
buf += result;
} while (size > 0);
sigprocmask(SIG_SETMASK, &oldset, NULL);
tsk_restore_flags(current, pflags, PF_MEMALLOC);
return result;
}
static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
int flags)
{
int result;
void *kaddr = kmap(bvec->bv_page);
result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
bvec->bv_len, flags);
kunmap(bvec->bv_page);
return result;
}
/* always call with the tx_lock held */
static int nbd_send_req(struct nbd_device *nbd, struct request *req)
{
int result, flags;
struct nbd_request request;
unsigned long size = blk_rq_bytes(req);
request.magic = htonl(NBD_REQUEST_MAGIC);
request.type = htonl(nbd_cmd(req));
if (nbd_cmd(req) == NBD_CMD_FLUSH) {
/* Other values are reserved for FLUSH requests. */
request.from = 0;
request.len = 0;
} else {
request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
request.len = htonl(size);
}
memcpy(request.handle, &req, sizeof(req));
dprintk(DBG_TX, "%s: request %p: sending control (%s@%llu,%uB)\n",
nbd->disk->disk_name, req,
nbdcmd_to_ascii(nbd_cmd(req)),
(unsigned long long)blk_rq_pos(req) << 9,
blk_rq_bytes(req));
result = sock_xmit(nbd, 1, &request, sizeof(request),
(nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Send control failed (result %d)\n", result);
goto error_out;
}
if (nbd_cmd(req) == NBD_CMD_WRITE) {
struct req_iterator iter;
struct bio_vec bvec;
/*
* we are really probing at internals to determine
* whether to set MSG_MORE or not...
*/
rq_for_each_segment(bvec, req, iter) {
flags = 0;
if (!rq_iter_last(bvec, iter))
flags = MSG_MORE;
dprintk(DBG_TX, "%s: request %p: sending %d bytes data\n",
nbd->disk->disk_name, req, bvec.bv_len);
result = sock_send_bvec(nbd, &bvec, flags);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Send data failed (result %d)\n",
result);
goto error_out;
}
}
}
return 0;
error_out:
return -EIO;
}
static struct request *nbd_find_request(struct nbd_device *nbd,
struct request *xreq)
{
struct request *req, *tmp;
int err;
err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
if (unlikely(err))
goto out;
spin_lock(&nbd->queue_lock);
list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
if (req != xreq)
continue;
list_del_init(&req->queuelist);
spin_unlock(&nbd->queue_lock);
return req;
}
spin_unlock(&nbd->queue_lock);
err = -ENOENT;
out:
return ERR_PTR(err);
}
static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
{
int result;
void *kaddr = kmap(bvec->bv_page);
result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
MSG_WAITALL);
kunmap(bvec->bv_page);
return result;
}
/* NULL returned = something went wrong, inform userspace */
static struct request *nbd_read_stat(struct nbd_device *nbd)
{
int result;
struct nbd_reply reply;
struct request *req;
reply.magic = 0;
result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Receive control failed (result %d)\n", result);
goto harderror;
}
if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
(unsigned long)ntohl(reply.magic));
result = -EPROTO;
goto harderror;
}
req = nbd_find_request(nbd, *(struct request **)reply.handle);
if (IS_ERR(req)) {
result = PTR_ERR(req);
if (result != -ENOENT)
goto harderror;
dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
reply.handle);
result = -EBADR;
goto harderror;
}
if (ntohl(reply.error)) {
dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
ntohl(reply.error));
req->errors++;
return req;
}
dprintk(DBG_RX, "%s: request %p: got reply\n",
nbd->disk->disk_name, req);
if (nbd_cmd(req) == NBD_CMD_READ) {
struct req_iterator iter;
struct bio_vec bvec;
rq_for_each_segment(bvec, req, iter) {
result = sock_recv_bvec(nbd, &bvec);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
result);
req->errors++;
return req;
}
dprintk(DBG_RX, "%s: request %p: got %d bytes data\n",
nbd->disk->disk_name, req, bvec.bv_len);
}
}
return req;
harderror:
nbd->harderror = result;
return NULL;
}
static ssize_t pid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%ld\n",
(long) ((struct nbd_device *)disk->private_data)->pid);
}
static struct device_attribute pid_attr = {
.attr = { .name = "pid", .mode = S_IRUGO},
.show = pid_show,
};
static int nbd_do_it(struct nbd_device *nbd)
{
struct request *req;
int ret;
BUG_ON(nbd->magic != NBD_MAGIC);
sk_set_memalloc(nbd->sock->sk);
nbd->pid = task_pid_nr(current);
ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
nbd->pid = 0;
return ret;
}
while ((req = nbd_read_stat(nbd)) != NULL)
nbd_end_request(req);
device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
nbd->pid = 0;
return 0;
}
static void nbd_clear_que(struct nbd_device *nbd)
{
struct request *req;
BUG_ON(nbd->magic != NBD_MAGIC);
/*
* Because we have set nbd->sock to NULL under the tx_lock, all
* modifications to the list must have completed by now. For
* the same reason, the active_req must be NULL.
*
* As a consequence, we don't need to take the spin lock while
* purging the list here.
*/
BUG_ON(nbd->sock);
BUG_ON(nbd->active_req);
while (!list_empty(&nbd->queue_head)) {
req = list_entry(nbd->queue_head.next, struct request,
queuelist);
list_del_init(&req->queuelist);
req->errors++;
nbd_end_request(req);
}
while (!list_empty(&nbd->waiting_queue)) {
req = list_entry(nbd->waiting_queue.next, struct request,
queuelist);
list_del_init(&req->queuelist);
req->errors++;
nbd_end_request(req);
}
}
static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
{
if (req->cmd_type != REQ_TYPE_FS)
goto error_out;
nbd_cmd(req) = NBD_CMD_READ;
if (rq_data_dir(req) == WRITE) {
if ((req->cmd_flags & REQ_DISCARD)) {
WARN_ON(!(nbd->flags & NBD_FLAG_SEND_TRIM));
nbd_cmd(req) = NBD_CMD_TRIM;
} else
nbd_cmd(req) = NBD_CMD_WRITE;
if (nbd->flags & NBD_FLAG_READ_ONLY) {
dev_err(disk_to_dev(nbd->disk),
"Write on read-only\n");
goto error_out;
}
}
if (req->cmd_flags & REQ_FLUSH) {
BUG_ON(unlikely(blk_rq_sectors(req)));
nbd_cmd(req) = NBD_CMD_FLUSH;
}
req->errors = 0;
mutex_lock(&nbd->tx_lock);
if (unlikely(!nbd->sock)) {
mutex_unlock(&nbd->tx_lock);
dev_err(disk_to_dev(nbd->disk),
"Attempted send on closed socket\n");
goto error_out;
}
nbd->active_req = req;
if (nbd_send_req(nbd, req) != 0) {
dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
req->errors++;
nbd_end_request(req);
} else {
spin_lock(&nbd->queue_lock);
list_add_tail(&req->queuelist, &nbd->queue_head);
spin_unlock(&nbd->queue_lock);
}
nbd->active_req = NULL;
mutex_unlock(&nbd->tx_lock);
wake_up_all(&nbd->active_wq);
return;
error_out:
req->errors++;
nbd_end_request(req);
}
static int nbd_thread(void *data)
{
struct nbd_device *nbd = data;
struct request *req;
set_user_nice(current, MIN_NICE);
while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
/* wait for something to do */
wait_event_interruptible(nbd->waiting_wq,
kthread_should_stop() ||
!list_empty(&nbd->waiting_queue));
/* extract request */
if (list_empty(&nbd->waiting_queue))
continue;
spin_lock_irq(&nbd->queue_lock);
req = list_entry(nbd->waiting_queue.next, struct request,
queuelist);
list_del_init(&req->queuelist);
spin_unlock_irq(&nbd->queue_lock);
/* handle request */
nbd_handle_req(nbd, req);
}
return 0;
}
/*
* We always wait for result of write, for now. It would be nice to make it optional
* in future
* if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
* { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
*/
static void do_nbd_request(struct request_queue *q)
__releases(q->queue_lock) __acquires(q->queue_lock)
{
struct request *req;
while ((req = blk_fetch_request(q)) != NULL) {
struct nbd_device *nbd;
spin_unlock_irq(q->queue_lock);
dprintk(DBG_BLKDEV, "%s: request %p: dequeued (flags=%x)\n",
req->rq_disk->disk_name, req, req->cmd_type);
nbd = req->rq_disk->private_data;
BUG_ON(nbd->magic != NBD_MAGIC);
if (unlikely(!nbd->sock)) {
dev_err(disk_to_dev(nbd->disk),
"Attempted send on closed socket\n");
req->errors++;
nbd_end_request(req);
spin_lock_irq(q->queue_lock);
continue;
}
spin_lock_irq(&nbd->queue_lock);
list_add_tail(&req->queuelist, &nbd->waiting_queue);
spin_unlock_irq(&nbd->queue_lock);
wake_up(&nbd->waiting_wq);
spin_lock_irq(q->queue_lock);
}
}
/* Must be called with tx_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case NBD_DISCONNECT: {
struct request sreq;
dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
if (!nbd->sock)
return -EINVAL;
mutex_unlock(&nbd->tx_lock);
fsync_bdev(bdev);
mutex_lock(&nbd->tx_lock);
blk_rq_init(NULL, &sreq);
sreq.cmd_type = REQ_TYPE_SPECIAL;
nbd_cmd(&sreq) = NBD_CMD_DISC;
/* Check again after getting mutex back. */
if (!nbd->sock)
return -EINVAL;
nbd->disconnect = 1;
nbd_send_req(nbd, &sreq);
return 0;
}
case NBD_CLEAR_SOCK: {
struct socket *sock = nbd->sock;
nbd->sock = NULL;
nbd_clear_que(nbd);
BUG_ON(!list_empty(&nbd->queue_head));
BUG_ON(!list_empty(&nbd->waiting_queue));
kill_bdev(bdev);
if (sock)
sockfd_put(sock);
return 0;
}
case NBD_SET_SOCK: {
struct socket *sock;
int err;
if (nbd->sock)
return -EBUSY;
sock = sockfd_lookup(arg, &err);
if (sock) {
nbd->sock = sock;
if (max_part > 0)
bdev->bd_invalidated = 1;
nbd->disconnect = 0; /* we're connected now */
return 0;
}
return -EINVAL;
}
case NBD_SET_BLKSIZE:
nbd->blksize = arg;
nbd->bytesize &= ~(nbd->blksize-1);
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_SET_SIZE:
nbd->bytesize = arg & ~(nbd->blksize-1);
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_SET_TIMEOUT:
nbd->xmit_timeout = arg * HZ;
return 0;
case NBD_SET_FLAGS:
nbd->flags = arg;
return 0;
case NBD_SET_SIZE_BLOCKS:
nbd->bytesize = ((u64) arg) * nbd->blksize;
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_DO_IT: {
struct task_struct *thread;
struct socket *sock;
int error;
if (nbd->pid)
return -EBUSY;
if (!nbd->sock)
return -EINVAL;
mutex_unlock(&nbd->tx_lock);
if (nbd->flags & NBD_FLAG_READ_ONLY)
set_device_ro(bdev, true);
if (nbd->flags & NBD_FLAG_SEND_TRIM)
queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
nbd->disk->queue);
if (nbd->flags & NBD_FLAG_SEND_FLUSH)
blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
else
blk_queue_flush(nbd->disk->queue, 0);
thread = kthread_create(nbd_thread, nbd, "%s",
nbd->disk->disk_name);
if (IS_ERR(thread)) {
mutex_lock(&nbd->tx_lock);
return PTR_ERR(thread);
}
wake_up_process(thread);
error = nbd_do_it(nbd);
kthread_stop(thread);
mutex_lock(&nbd->tx_lock);
if (error)
return error;
sock_shutdown(nbd, 0);
sock = nbd->sock;
nbd->sock = NULL;
nbd_clear_que(nbd);
dev_warn(disk_to_dev(nbd->disk), "queue cleared\n");
kill_bdev(bdev);
queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
set_device_ro(bdev, false);
if (sock)
sockfd_put(sock);
nbd->flags = 0;
nbd->bytesize = 0;
bdev->bd_inode->i_size = 0;
set_capacity(nbd->disk, 0);
if (max_part > 0)
ioctl_by_bdev(bdev, BLKRRPART, 0);
if (nbd->disconnect) /* user requested, ignore socket errors */
return 0;
return nbd->harderror;
}
case NBD_CLEAR_QUE:
/*
* This is for compatibility only. The queue is always cleared
* by NBD_DO_IT or NBD_CLEAR_SOCK.
*/
return 0;
case NBD_PRINT_DEBUG:
dev_info(disk_to_dev(nbd->disk),
"next = %p, prev = %p, head = %p\n",
nbd->queue_head.next, nbd->queue_head.prev,
&nbd->queue_head);
return 0;
}
return -ENOTTY;
}
static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct nbd_device *nbd = bdev->bd_disk->private_data;
int error;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
BUG_ON(nbd->magic != NBD_MAGIC);
/* Anyone capable of this syscall can do *real bad* things */
dprintk(DBG_IOCTL, "%s: nbd_ioctl cmd=%s(0x%x) arg=%lu\n",
nbd->disk->disk_name, ioctl_cmd_to_ascii(cmd), cmd, arg);
mutex_lock(&nbd->tx_lock);
error = __nbd_ioctl(bdev, nbd, cmd, arg);
mutex_unlock(&nbd->tx_lock);
return error;
}
static const struct block_device_operations nbd_fops =
{
.owner = THIS_MODULE,
.ioctl = nbd_ioctl,
};
/*
* And here should be modules and kernel interface
* (Just smiley confuses emacs :-)
*/
static int __init nbd_init(void)
{
int err = -ENOMEM;
int i;
int part_shift;
BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
if (max_part < 0) {
printk(KERN_ERR "nbd: max_part must be >= 0\n");
return -EINVAL;
}
nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
if (!nbd_dev)
return -ENOMEM;
part_shift = 0;
if (max_part > 0) {
part_shift = fls(max_part);
/*
* Adjust max_part according to part_shift as it is exported
* to user space so that user can know the max number of
* partition kernel should be able to manage.
*
* Note that -1 is required because partition 0 is reserved
* for the whole disk.
*/
max_part = (1UL << part_shift) - 1;
}
if ((1UL << part_shift) > DISK_MAX_PARTS)
return -EINVAL;
if (nbds_max > 1UL << (MINORBITS - part_shift))
return -EINVAL;
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = alloc_disk(1 << part_shift);
if (!disk)
goto out;
nbd_dev[i].disk = disk;
/*
* The new linux 2.5 block layer implementation requires
* every gendisk to have its very own request_queue struct.
* These structs are big so we dynamically allocate them.
*/
disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
if (!disk->queue) {
put_disk(disk);
goto out;
}
/*
* Tell the block layer that we are not a rotational device
*/
queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
disk->queue->limits.discard_granularity = 512;
disk->queue->limits.max_discard_sectors = UINT_MAX;
disk->queue->limits.discard_zeroes_data = 0;
blk_queue_max_hw_sectors(disk->queue, 65536);
disk->queue->limits.max_sectors = 256;
}
if (register_blkdev(NBD_MAJOR, "nbd")) {
err = -EIO;
goto out;
}
printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
dprintk(DBG_INIT, "nbd: debugflags=0x%x\n", debugflags);
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = nbd_dev[i].disk;
nbd_dev[i].magic = NBD_MAGIC;
INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
spin_lock_init(&nbd_dev[i].queue_lock);
INIT_LIST_HEAD(&nbd_dev[i].queue_head);
mutex_init(&nbd_dev[i].tx_lock);
init_waitqueue_head(&nbd_dev[i].active_wq);
init_waitqueue_head(&nbd_dev[i].waiting_wq);
nbd_dev[i].blksize = 1024;
nbd_dev[i].bytesize = 0;
disk->major = NBD_MAJOR;
disk->first_minor = i << part_shift;
disk->fops = &nbd_fops;
disk->private_data = &nbd_dev[i];
sprintf(disk->disk_name, "nbd%d", i);
set_capacity(disk, 0);
add_disk(disk);
}
return 0;
out:
while (i--) {
blk_cleanup_queue(nbd_dev[i].disk->queue);
put_disk(nbd_dev[i].disk);
}
kfree(nbd_dev);
return err;
}
static void __exit nbd_cleanup(void)
{
int i;
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = nbd_dev[i].disk;
nbd_dev[i].magic = 0;
if (disk) {
del_gendisk(disk);
blk_cleanup_queue(disk->queue);
put_disk(disk);
}
}
unregister_blkdev(NBD_MAJOR, "nbd");
kfree(nbd_dev);
printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
}
module_init(nbd_init);
module_exit(nbd_cleanup);
MODULE_DESCRIPTION("Network Block Device");
MODULE_LICENSE("GPL");
module_param(nbds_max, int, 0444);
MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
module_param(max_part, int, 0444);
MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
#ifndef NDEBUG
module_param(debugflags, int, 0644);
MODULE_PARM_DESC(debugflags, "flags for controlling debug output");
#endif
| MatiasBjorling/lightnvm-moved-to-OpenChannelSSD-Linux | drivers/block/nbd.c | C | gpl-2.0 | 22,865 |
<?php
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
/**
* ContactsourcesFixture
*
*/
class ContactsourcesFixture extends TestFixture
{
/**
* Fields
*
* @var array
*/
public $fields = [
'id' => ['type' => 'integer', 'length' => 6, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
'name' => ['type' => 'string', 'length' => 45, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
],
'_options' => [
'engine' => 'InnoDB', 'collation' => 'utf8_hungarian_ci'
],
];
/**
* Records
*
* @var array
*/
public $records = [
[
'id' => 1,
'name' => 'Contactsoure 1'
],
[
'id' => 2,
'name' => 'Contactsoure 2'
],
];
}
| rrd108/sanga | tests/Fixture/ContactsourcesFixture.php | PHP | gpl-2.0 | 1,008 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Sat Aug 06 17:04:43 EDT 2005 -->
<TITLE>
Xalan-Java 2.7.0: Uses of Class org.apache.xpath.functions.FuncCurrent
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xpath/functions/FuncCurrent.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="FuncCurrent.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.xpath.functions.FuncCurrent</B></H2>
</CENTER>
No usage of org.apache.xpath.functions.FuncCurrent
<P>
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xpath/functions/FuncCurrent.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="FuncCurrent.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
Copyright © 2005 Apache XML Project. All Rights Reserved.
</BODY>
</HTML>
| MrStaticVoid/iriverter | lib/xalan-j_2_7_0/docs/apidocs/org/apache/xpath/functions/class-use/FuncCurrent.html | HTML | gpl-2.0 | 4,574 |
#ifndef UTILITIES_H
#define UTILITIES_H
#include "edge.h"
#include <cstring>
#include "resume.h"
#include <algorithm>
#include <vector>
#include "Hungarian.h"
#include "BipartiteGraph.h"
#include "Matrix.h"
using namespace std;
typedef vector<vector<string>> section;
#include "pair_section.h"
class PairSection;
typedef vector<string> line;
typedef vector<pair<int, PairSection>> evidence;
//class Resume;
namespace string_util {
char tolower(char in){
if(in<='Z' && in>='A')
return in-('Z'-'z');
return in;
}
string tolower(string s) {
string ret=s;
for(int i=0;i<s.length();i++) ret[i]=tolower(s[i]);
return ret;
}
// trim from start
std::string &Ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
std::string &Rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string strip(std::string s) {
return Ltrim(Rtrim(s));
}
bool IsPresent(vector<string> v, string s) {
for(int i=0;i<v.size();i++) if(v[i]==s) return true;
return false;
}
vector<string> BagOfWordsFromString(vector<string> stopwords, string teststr) {
vector<string> bag;
//string teststr("The quick brown fox:test1,test2'test3\"test4");
//teststr=string_util::tolower(teststr);
char *teststr_c_str = (char *)teststr.c_str();
char *token_c_str = strtok(teststr_c_str, DELIM);
while (token_c_str) {
if(!string_util::IsPresent(stopwords,string(token_c_str))) bag.push_back(string(token_c_str));
//printf ("Token: %s\n", p);
token_c_str = strtok(NULL, DELIM);
}
//cout<<"Line: "<<teststr<<" bag =";
//for(int i=0;i<bag.size();i++) cout<<bag[i]<<"_";
//cout<<endl;
//cin>>teststr;
//cin.get();
return bag;
}
}
namespace resume_util {
bool IsBegin(string s) {
int pos=s.find("CS0");
if(pos==0) return true;
return false;
}
bool IsSection(string s,string section) {
int pos=s.find(section);
int len = s.length();
//if(pos==0 ) return true;
if(pos==0 && pos<len && len-pos-section.length()<=10) return true;
return false;
}
bool IsSummary(string s) {
if(IsSection(s,"summary") || IsSection(s,"professional summary")
|| IsSection(s,"summary of qualifications"))
return true;
return false;
}
bool IsSkills(string s) {
if(IsSection(s,"skills") || IsSection(s,"technical skills") ||
IsSection(s,"business and technical skills"))
return true;
return false;
}
bool IsExperience(string s) {
if(IsSection(s,"experience") || IsSection(s,"project experience") ||
IsSection(s,"work experience") || IsSection(s,"professional experience") ||
IsSection(s,"recent experience"))
return true;
return false;
}
bool IsEducation(string s) {
if(IsSection(s,"education") )
return true;
return false;
}
bool IsResponsibilities(string s) {
if(IsSection(s,"responsibilities"))
return true;
return false;
}
bool IsEnvSection(string s,string section) {
int pos=s.find(section);
//cout<<s<<"\n"<<section<<"__"<<pos<<endl;
if(pos==0 ) return true;
return false;
}
bool IsEnvironment(string s) {
if(IsEnvSection(s,"environment:") ||
IsEnvSection(s,"environment :") ||
IsEnvSection(s,"tools and technologies:") ||
IsEnvSection(s,"tools and technologies :") ||
IsEnvSection(s,"tools & technolgies:") ||
IsEnvSection(s,"tools & technolgies :"))
return true;
return false;
}
}
namespace distance_util {
int Jaccard(line v1, line v2) {
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
line inter;
line uni;
set_intersection(v1.begin(),v1.end(),
v2.begin(),v2.end(),
back_inserter(inter));
set_union(v1.begin(),v1.end(),
v2.begin(),v2.end(),
back_inserter(uni));
float num=(float)(inter.size());
float denom=(float)(uni.size());
if(num == 0 || denom == 0) return 0;
return int((num/denom)*1000);
}
}
namespace matching_util {
//Credit: http://www.frc.ri.cmu.edu/~lantao/codes/hungarian.php
double MaxBipartiteMatching(const section& s1, const section & s2, vector<pair_line> &pl)
{
printf("ENTER\n");
size_t nrows = s1.size();
size_t ncols = s2.size();
//define a matrix
Matrix matrix;
matrix.resize(nrows);
for(unsigned int i=0; i<nrows; i++)
matrix[i].resize(ncols);
// generate
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++){
matrix[i][j].SetWeight(distance_util::Jaccard(s1[i],s2[j]));
}
BipartiteGraph bg(matrix);
Hungarian h(bg);
h.HungarianAlgo();
BipartiteGraph* result = h.GetBG();
Matrix result_matrix = *(result->GetMatrix());
double sum=0;
for(unsigned int i=0; i< result->GetNumAgents(); i++){
for(unsigned int j=0; j< result->GetNumTasks(); j++){
if(result->GetMatrix(i,j)->GetMatchedFlag()) {
pl.push_back(pair_line(i,j,result_matrix[i][j].GetWeight()));
sum += result_matrix[i][j].GetWeight();
}
}
}
printf("score= %f\n",sum);
return sum;
}
int SectionSimilarity(const section& s1, const section& s2, vector<pair_line> &pl) {
int nrow= s1.size();
int ncol= s2.size();
if(nrow <= ncol) {
return (int)MaxBipartiteMatching(s1,s2,pl);
} else {
double val = MaxBipartiteMatching(s2,s1,pl);
for(int i=0;i<pl.size();i++) {
int temp_u = pl[i].u;
pl[i].u = pl[i].v;
pl[i].v = temp_u;
}
return (int)val;
}
}
//Credit: http://stackoverflow.com/questions/10580982/c-sort-keeping-track-of-indices
template <typename T>
std::vector<size_t> ordered(std::vector<T> const& values) {
std::vector<size_t> indices(values.size());
for(int i=0;i<values.size();i++) indices[i] = i;
//iota(begin(indices), end(indices), static_cast<size_t>(0));
std::sort(
begin(indices), end(indices),
[&](size_t a, size_t b) { return values[a] > values[b]; }
);
return indices;
}
}
#endif
| sorrachai/FraudResumeDetection | utilities.h | C | gpl-2.0 | 6,297 |
/*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// G:\quake2\baseq2\models/monsters/boss3/rider
// This file generated by ModelGen - Do NOT Modify
#define FRAME_attak101 0
#define FRAME_attak102 1
#define FRAME_attak103 2
#define FRAME_attak104 3
#define FRAME_attak105 4
#define FRAME_attak106 5
#define FRAME_attak107 6
#define FRAME_attak108 7
#define FRAME_attak109 8
#define FRAME_attak110 9
#define FRAME_attak111 10
#define FRAME_attak112 11
#define FRAME_attak113 12
#define FRAME_attak114 13
#define FRAME_attak115 14
#define FRAME_attak116 15
#define FRAME_attak117 16
#define FRAME_attak118 17
#define FRAME_attak201 18
#define FRAME_attak202 19
#define FRAME_attak203 20
#define FRAME_attak204 21
#define FRAME_attak205 22
#define FRAME_attak206 23
#define FRAME_attak207 24
#define FRAME_attak208 25
#define FRAME_attak209 26
#define FRAME_attak210 27
#define FRAME_attak211 28
#define FRAME_attak212 29
#define FRAME_attak213 30
#define FRAME_death01 31
#define FRAME_death02 32
#define FRAME_death03 33
#define FRAME_death04 34
#define FRAME_death05 35
#define FRAME_death06 36
#define FRAME_death07 37
#define FRAME_death08 38
#define FRAME_death09 39
#define FRAME_death10 40
#define FRAME_death11 41
#define FRAME_death12 42
#define FRAME_death13 43
#define FRAME_death14 44
#define FRAME_death15 45
#define FRAME_death16 46
#define FRAME_death17 47
#define FRAME_death18 48
#define FRAME_death19 49
#define FRAME_death20 50
#define FRAME_death21 51
#define FRAME_death22 52
#define FRAME_death23 53
#define FRAME_death24 54
#define FRAME_death25 55
#define FRAME_death26 56
#define FRAME_death27 57
#define FRAME_death28 58
#define FRAME_death29 59
#define FRAME_death30 60
#define FRAME_death31 61
#define FRAME_death32 62
#define FRAME_death33 63
#define FRAME_death34 64
#define FRAME_death35 65
#define FRAME_death36 66
#define FRAME_death37 67
#define FRAME_death38 68
#define FRAME_death39 69
#define FRAME_death40 70
#define FRAME_death41 71
#define FRAME_death42 72
#define FRAME_death43 73
#define FRAME_death44 74
#define FRAME_death45 75
#define FRAME_death46 76
#define FRAME_death47 77
#define FRAME_death48 78
#define FRAME_death49 79
#define FRAME_death50 80
#define FRAME_pain101 81
#define FRAME_pain102 82
#define FRAME_pain103 83
#define FRAME_pain201 84
#define FRAME_pain202 85
#define FRAME_pain203 86
#define FRAME_pain301 87
#define FRAME_pain302 88
#define FRAME_pain303 89
#define FRAME_pain304 90
#define FRAME_pain305 91
#define FRAME_pain306 92
#define FRAME_pain307 93
#define FRAME_pain308 94
#define FRAME_pain309 95
#define FRAME_pain310 96
#define FRAME_pain311 97
#define FRAME_pain312 98
#define FRAME_pain313 99
#define FRAME_pain314 100
#define FRAME_pain315 101
#define FRAME_pain316 102
#define FRAME_pain317 103
#define FRAME_pain318 104
#define FRAME_pain319 105
#define FRAME_pain320 106
#define FRAME_pain321 107
#define FRAME_pain322 108
#define FRAME_pain323 109
#define FRAME_pain324 110
#define FRAME_pain325 111
#define FRAME_stand01 112
#define FRAME_stand02 113
#define FRAME_stand03 114
#define FRAME_stand04 115
#define FRAME_stand05 116
#define FRAME_stand06 117
#define FRAME_stand07 118
#define FRAME_stand08 119
#define FRAME_stand09 120
#define FRAME_stand10 121
#define FRAME_stand11 122
#define FRAME_stand12 123
#define FRAME_stand13 124
#define FRAME_stand14 125
#define FRAME_stand15 126
#define FRAME_stand16 127
#define FRAME_stand17 128
#define FRAME_stand18 129
#define FRAME_stand19 130
#define FRAME_stand20 131
#define FRAME_stand21 132
#define FRAME_stand22 133
#define FRAME_stand23 134
#define FRAME_stand24 135
#define FRAME_stand25 136
#define FRAME_stand26 137
#define FRAME_stand27 138
#define FRAME_stand28 139
#define FRAME_stand29 140
#define FRAME_stand30 141
#define FRAME_stand31 142
#define FRAME_stand32 143
#define FRAME_stand33 144
#define FRAME_stand34 145
#define FRAME_stand35 146
#define FRAME_stand36 147
#define FRAME_stand37 148
#define FRAME_stand38 149
#define FRAME_stand39 150
#define FRAME_stand40 151
#define FRAME_stand41 152
#define FRAME_stand42 153
#define FRAME_stand43 154
#define FRAME_stand44 155
#define FRAME_stand45 156
#define FRAME_stand46 157
#define FRAME_stand47 158
#define FRAME_stand48 159
#define FRAME_stand49 160
#define FRAME_stand50 161
#define FRAME_stand51 162
#define FRAME_walk01 163
#define FRAME_walk02 164
#define FRAME_walk03 165
#define FRAME_walk04 166
#define FRAME_walk05 167
#define FRAME_walk06 168
#define FRAME_walk07 169
#define FRAME_walk08 170
#define FRAME_walk09 171
#define FRAME_walk10 172
#define FRAME_walk11 173
#define FRAME_walk12 174
#define FRAME_walk13 175
#define FRAME_walk14 176
#define FRAME_walk15 177
#define FRAME_walk16 178
#define FRAME_walk17 179
#define FRAME_walk18 180
#define FRAME_walk19 181
#define FRAME_walk20 182
#define FRAME_walk21 183
#define FRAME_walk22 184
#define FRAME_walk23 185
#define FRAME_walk24 186
#define FRAME_walk25 187
#define FRAME_active01 188
#define FRAME_active02 189
#define FRAME_active03 190
#define FRAME_active04 191
#define FRAME_active05 192
#define FRAME_active06 193
#define FRAME_active07 194
#define FRAME_active08 195
#define FRAME_active09 196
#define FRAME_active10 197
#define FRAME_active11 198
#define FRAME_active12 199
#define FRAME_active13 200
#define FRAME_attak301 201
#define FRAME_attak302 202
#define FRAME_attak303 203
#define FRAME_attak304 204
#define FRAME_attak305 205
#define FRAME_attak306 206
#define FRAME_attak307 207
#define FRAME_attak308 208
#define FRAME_attak401 209
#define FRAME_attak402 210
#define FRAME_attak403 211
#define FRAME_attak404 212
#define FRAME_attak405 213
#define FRAME_attak406 214
#define FRAME_attak407 215
#define FRAME_attak408 216
#define FRAME_attak409 217
#define FRAME_attak410 218
#define FRAME_attak411 219
#define FRAME_attak412 220
#define FRAME_attak413 221
#define FRAME_attak414 222
#define FRAME_attak415 223
#define FRAME_attak416 224
#define FRAME_attak417 225
#define FRAME_attak418 226
#define FRAME_attak419 227
#define FRAME_attak420 228
#define FRAME_attak421 229
#define FRAME_attak422 230
#define FRAME_attak423 231
#define FRAME_attak424 232
#define FRAME_attak425 233
#define FRAME_attak426 234
#define FRAME_attak501 235
#define FRAME_attak502 236
#define FRAME_attak503 237
#define FRAME_attak504 238
#define FRAME_attak505 239
#define FRAME_attak506 240
#define FRAME_attak507 241
#define FRAME_attak508 242
#define FRAME_attak509 243
#define FRAME_attak510 244
#define FRAME_attak511 245
#define FRAME_attak512 246
#define FRAME_attak513 247
#define FRAME_attak514 248
#define FRAME_attak515 249
#define FRAME_attak516 250
#define FRAME_death201 251
#define FRAME_death202 252
#define FRAME_death203 253
#define FRAME_death204 254
#define FRAME_death205 255
#define FRAME_death206 256
#define FRAME_death207 257
#define FRAME_death208 258
#define FRAME_death209 259
#define FRAME_death210 260
#define FRAME_death211 261
#define FRAME_death212 262
#define FRAME_death213 263
#define FRAME_death214 264
#define FRAME_death215 265
#define FRAME_death216 266
#define FRAME_death217 267
#define FRAME_death218 268
#define FRAME_death219 269
#define FRAME_death220 270
#define FRAME_death221 271
#define FRAME_death222 272
#define FRAME_death223 273
#define FRAME_death224 274
#define FRAME_death225 275
#define FRAME_death226 276
#define FRAME_death227 277
#define FRAME_death228 278
#define FRAME_death229 279
#define FRAME_death230 280
#define FRAME_death231 281
#define FRAME_death232 282
#define FRAME_death233 283
#define FRAME_death234 284
#define FRAME_death235 285
#define FRAME_death236 286
#define FRAME_death237 287
#define FRAME_death238 288
#define FRAME_death239 289
#define FRAME_death240 290
#define FRAME_death241 291
#define FRAME_death242 292
#define FRAME_death243 293
#define FRAME_death244 294
#define FRAME_death245 295
#define FRAME_death246 296
#define FRAME_death247 297
#define FRAME_death248 298
#define FRAME_death249 299
#define FRAME_death250 300
#define FRAME_death251 301
#define FRAME_death252 302
#define FRAME_death253 303
#define FRAME_death254 304
#define FRAME_death255 305
#define FRAME_death256 306
#define FRAME_death257 307
#define FRAME_death258 308
#define FRAME_death259 309
#define FRAME_death260 310
#define FRAME_death261 311
#define FRAME_death262 312
#define FRAME_death263 313
#define FRAME_death264 314
#define FRAME_death265 315
#define FRAME_death266 316
#define FRAME_death267 317
#define FRAME_death268 318
#define FRAME_death269 319
#define FRAME_death270 320
#define FRAME_death271 321
#define FRAME_death272 322
#define FRAME_death273 323
#define FRAME_death274 324
#define FRAME_death275 325
#define FRAME_death276 326
#define FRAME_death277 327
#define FRAME_death278 328
#define FRAME_death279 329
#define FRAME_death280 330
#define FRAME_death281 331
#define FRAME_death282 332
#define FRAME_death283 333
#define FRAME_death284 334
#define FRAME_death285 335
#define FRAME_death286 336
#define FRAME_death287 337
#define FRAME_death288 338
#define FRAME_death289 339
#define FRAME_death290 340
#define FRAME_death291 341
#define FRAME_death292 342
#define FRAME_death293 343
#define FRAME_death294 344
#define FRAME_death295 345
#define FRAME_death301 346
#define FRAME_death302 347
#define FRAME_death303 348
#define FRAME_death304 349
#define FRAME_death305 350
#define FRAME_death306 351
#define FRAME_death307 352
#define FRAME_death308 353
#define FRAME_death309 354
#define FRAME_death310 355
#define FRAME_death311 356
#define FRAME_death312 357
#define FRAME_death313 358
#define FRAME_death314 359
#define FRAME_death315 360
#define FRAME_death316 361
#define FRAME_death317 362
#define FRAME_death318 363
#define FRAME_death319 364
#define FRAME_death320 365
#define FRAME_jump01 366
#define FRAME_jump02 367
#define FRAME_jump03 368
#define FRAME_jump04 369
#define FRAME_jump05 370
#define FRAME_jump06 371
#define FRAME_jump07 372
#define FRAME_jump08 373
#define FRAME_jump09 374
#define FRAME_jump10 375
#define FRAME_jump11 376
#define FRAME_jump12 377
#define FRAME_jump13 378
#define FRAME_pain401 379
#define FRAME_pain402 380
#define FRAME_pain403 381
#define FRAME_pain404 382
#define FRAME_pain501 383
#define FRAME_pain502 384
#define FRAME_pain503 385
#define FRAME_pain504 386
#define FRAME_pain601 387
#define FRAME_pain602 388
#define FRAME_pain603 389
#define FRAME_pain604 390
#define FRAME_pain605 391
#define FRAME_pain606 392
#define FRAME_pain607 393
#define FRAME_pain608 394
#define FRAME_pain609 395
#define FRAME_pain610 396
#define FRAME_pain611 397
#define FRAME_pain612 398
#define FRAME_pain613 399
#define FRAME_pain614 400
#define FRAME_pain615 401
#define FRAME_pain616 402
#define FRAME_pain617 403
#define FRAME_pain618 404
#define FRAME_pain619 405
#define FRAME_pain620 406
#define FRAME_pain621 407
#define FRAME_pain622 408
#define FRAME_pain623 409
#define FRAME_pain624 410
#define FRAME_pain625 411
#define FRAME_pain626 412
#define FRAME_pain627 413
#define FRAME_stand201 414
#define FRAME_stand202 415
#define FRAME_stand203 416
#define FRAME_stand204 417
#define FRAME_stand205 418
#define FRAME_stand206 419
#define FRAME_stand207 420
#define FRAME_stand208 421
#define FRAME_stand209 422
#define FRAME_stand210 423
#define FRAME_stand211 424
#define FRAME_stand212 425
#define FRAME_stand213 426
#define FRAME_stand214 427
#define FRAME_stand215 428
#define FRAME_stand216 429
#define FRAME_stand217 430
#define FRAME_stand218 431
#define FRAME_stand219 432
#define FRAME_stand220 433
#define FRAME_stand221 434
#define FRAME_stand222 435
#define FRAME_stand223 436
#define FRAME_stand224 437
#define FRAME_stand225 438
#define FRAME_stand226 439
#define FRAME_stand227 440
#define FRAME_stand228 441
#define FRAME_stand229 442
#define FRAME_stand230 443
#define FRAME_stand231 444
#define FRAME_stand232 445
#define FRAME_stand233 446
#define FRAME_stand234 447
#define FRAME_stand235 448
#define FRAME_stand236 449
#define FRAME_stand237 450
#define FRAME_stand238 451
#define FRAME_stand239 452
#define FRAME_stand240 453
#define FRAME_stand241 454
#define FRAME_stand242 455
#define FRAME_stand243 456
#define FRAME_stand244 457
#define FRAME_stand245 458
#define FRAME_stand246 459
#define FRAME_stand247 460
#define FRAME_stand248 461
#define FRAME_stand249 462
#define FRAME_stand250 463
#define FRAME_stand251 464
#define FRAME_stand252 465
#define FRAME_stand253 466
#define FRAME_stand254 467
#define FRAME_stand255 468
#define FRAME_stand256 469
#define FRAME_stand257 470
#define FRAME_stand258 471
#define FRAME_stand259 472
#define FRAME_stand260 473
#define FRAME_walk201 474
#define FRAME_walk202 475
#define FRAME_walk203 476
#define FRAME_walk204 477
#define FRAME_walk205 478
#define FRAME_walk206 479
#define FRAME_walk207 480
#define FRAME_walk208 481
#define FRAME_walk209 482
#define FRAME_walk210 483
#define FRAME_walk211 484
#define FRAME_walk212 485
#define FRAME_walk213 486
#define FRAME_walk214 487
#define FRAME_walk215 488
#define FRAME_walk216 489
#define FRAME_walk217 490
#define MODEL_SCALE 1.000000
| glampert/quake2-for-ps2 | src/game/m_boss32.h | C | gpl-2.0 | 13,748 |
<?php
// $Id$
/**
* @file
* general functions for mothership
*/
function mothership_id_safe($string, $vars = "default") {
// Replace with dashes anything that isn't A-Z, numbers, dashes, or underscores.
if($vars == "remove-numbers"){
$string = strtolower(preg_replace('/[^a-zA-Z_-]+/', '-', $string));
}else{
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
}
// change the "_" to "-"
$string = strtolower(str_replace('_', '-', $string));
// If the first character is not a-z, add 'n' in front.
if (function_exists('ctype_lower')) {
if (!ctype_lower($string{0})) { // Don't use ctype_alpha since its locale aware.
$string = 'id' . $string;
}
}
else {
preg_match('/[a-z]+/', $string{0}, $matches);
if (count($matches) == 0) {
$string = 'id' . $string;
}
}
return $string;
}
/*
getting some of the userprofile data into a single function
*/
function mothership_userprofile($user){
if ($user->uid) {
// global $user;
// $profile = profile_load_profile($user);
//$user->profile_name
//user picture
if ($user->picture) {
$userimage = '<img src="/' . $user->picture . '">';
print '<div class="profile-image">' . l($userimage, 'user/' . $user->uid, $options = array('html' => TRUE)) . '</div>';
}
print '<ul class="profile">';
print '<li class="profile-name">' . l($user->name, 'user/' . $user->uid . '') . '</li>';
print '<li class="profile-edit">' . l(t('edit'), 'user/' . $user->uid . '/edit') . '</li>';
print '<li class="profile-logout">' . l(t('Sign out'), 'logout') . '</li>';
print '</ul>';
}
}
/*
Quick & handy function for adding time ago
*/
function mothership_time_ago($timestamp,$granularity = 2, $langcode = NULL){
$difference = time() - $timestamp;
$text = format_interval($difference, $granularity, $langcode) ." ". t("ago");
return $text;
}
/*
return only the terms from a vocabulary in the node
*/
function return_terms_from_vocabulary($node, $vid){
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid');
// $vocabulary = taxonomy_vocabulary_load($vid);
// $content .='<div class="vocabulary">'.$vocabulary->name.'</div>';
$termslist = '';
if ($terms) {
$content .= '<span class="terms">';
foreach ($terms as $term) {
$termslist = $termslist . '<span class="term-icon-'. mothership_id_safe($term->name) .'">' . l($term->name, 'taxonomy/term/'.$term->tid) .'</span> | ';
}
//TODO make a better split option hardcoded is kinda sad ;)
$content.= trim ($termslist," |").'</span>';
}
return $content;
}
| aakb/sport-aarhus-events | sites/all/themes/mothership/template/template.functions.php | PHP | gpl-2.0 | 2,637 |
/* Source for:
* Cypress TrueTouch(TM) Standard Product I2C touchscreen driver.
* drivers/input/touchscreen/cyttsp-i2c.c
*
* Copyright (C) 2009, 2010 Cypress Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2, and only version 2, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Cypress reserves the right to make changes without further notice
* to the materials described herein. Cypress does not assume any
* liability arising out of the application described herein.
*
* Contact Cypress Semiconductor at www.cypress.com
*
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <mach/gpio.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/byteorder/generic.h>
#include <linux/bitops.h>
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif /* CONFIG_HAS_EARLYSUSPEND */
#include <linux/regulator/consumer.h>
#include <mach/vreg.h>
#include <linux/wakelock.h>
#include <linux/input/mt.h>
#define CYTTSP_DECLARE_GLOBALS
#include <linux/miscdevice.h>
#include <linux/cyttsp.h>
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
#include <linux/issp_defs.h>
#include <linux/issp_extern.h>
#endif
#include <linux/uaccess.h>
uint32_t cyttsp_tsdebug1;
module_param_named(tsdebug1, cyttsp_tsdebug1, uint, 0664);
#if defined(CONFIG_EF33_BOARD) || defined(CONFIG_EF34_BOARD)
#define FEATURE_TOUCH_KEY
#endif
/* -------------------------------------------------------------------- */
/* EF33S gpio & resolution & key area*/
/* -------------------------------------------------------------------- */
#define GPIO_TOUCH_RST 95
#define GPIO_TOUCH_CHG 61
#define GPIO_TOUCH_SDA 64
#define GPIO_TOUCH_SCL 65
#define GPIO_TOUCH_ID 93
#define IRQ_TOUCH_INT gpio_to_irq(GPIO_TOUCH_CHG)
/* -------------------------------------------------------------------- */
/* debug option */
/* -------------------------------------------------------------------- */
//#define TOUCH_DBG_ENABLE
#ifdef TOUCH_DBG_ENABLE
#define dbg(fmt, args...) printk("[TOUCH]" fmt, ##args)
#else
#define dbg(fmt, args...)
#endif
#define dbg_func_in() dbg("[FUNC_IN] %s\n", __func__)
#define dbg_func_out() dbg("[FUNC_OUT] %s\n", __func__)
#define dbg_line() dbg("[LINE] %d(%s)\n", __LINE__, __func__)
/* -------------------------------------------------------------------- */
#define FEATURE_SKY_PROCESS_CMD_KEY
#ifdef FEATURE_TOUCH_KEY
#define X_MAX 480
#define Y_MAX 800
#define NULL_KEY_AREA 840
#define MENU_KEY_MIN 40
#define MENU_KEY_MAX 140
#define HOME_KEY_MIN 210
#define HOME_KEY_MAX 280
#define BACK_KEY_MIN 360
#define BACK_KEY_MAX 460
#endif
#ifdef FEATURE_CYTTSP_HEARTBEAT
#define CYTTSP_HEARTBEAT_TIME 3
#endif
#define TOUCH_MAX_NUM 4 // 2
#define SENSOR_X 12
#define SENSOR_Y 20
#define MAX_NODE SENSOR_X*SENSOR_Y
#define CYTTSP_BASE_MIN 65
#define CYTTSP_BASE_MAX 135
#define CYTTSP_MUTEX_LOCK //ST_LIM
//----------------- Added --------------//
/* abs settings */
/* abs value offsets */
#define CY_NUM_ABS_VAL 5 /* number of abs values per setting */
#define CY_SIGNAL_OST 0
#define CY_MIN_OST 1
#define CY_MAX_OST 2
#define CY_FUZZ_OST 3
#define CY_FLAT_OST 4
/* axis signal offsets */
#define CY_NUM_ABS_SET 5 /* number of abs signal sets */
#define CY_ABS_X_OST 0
#define CY_ABS_Y_OST 1
#define CY_ABS_P_OST 2
#define CY_ABS_W_OST 3
#define CY_ABS_ID_OST 4
#define CY_IGNORE_VALUE 0xFFFF /* mark unused signals as ignore */
#define HI_TRACKID(reg) ((reg & 0xF0) >> 4)
#define LO_TRACKID(reg) ((reg & 0x0F) >> 0)
/* Touch structure */
struct cyttsp_trk{
bool tch;
int abs[CY_NUM_ABS_SET];
} ;
int prev_touches=0;
//----------------- --------------------------//
/* ****************************************************************************
* static value
* ************************************************************************** */
static struct cyttsp_gen3_xydata_t g_xy_data;
//static struct cyttsp_bootloader_data_t g_bl_data;
//static struct cyttsp_sysinfo_data_t g_sysinfo_data;
//static struct cyttsp_gen3_xydata_t g_wake_data;
static const struct i2c_device_id cyttsp_id[] = {
{ CYTTSP_I2C_NAME, 0 }, { }
};
/* CY TTSP I2C Driver private data */
struct cyttsp {
struct i2c_client *client;
struct input_dev *input;
struct work_struct work;
#ifdef FEATURE_CYTTSP_HEARTBEAT
struct work_struct work2;
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
//struct work_struct work3; // N1037 20120312 for ICS
struct delayed_work work3;
#endif
struct timer_list timer;
struct mutex mutex;
#ifdef CYTTSP_MUTEX_LOCK
struct mutex lock_mutex;
#endif
char phys[32];
struct cyttsp_platform_data *platform_data;
u8 num_prev_touch;
u16 active_track[CYTTSP_NUM_TRACK_ID];
u16 prev_st_touch[CYTTSP_NUM_ST_TOUCH_ID];
u16 prev_mt_touch[CYTTSP_NUM_MT_TOUCH_ID];
u16 prev_mt_pos[CYTTSP_NUM_MT_TOUCH_ID][2];
struct cyttsp_trk prv_trk[CYTTSP_NUM_TRACK_ID];
atomic_t irq_enabled;
struct early_suspend early_suspend;
};
#ifdef FEATURE_CYTTSP_HEARTBEAT
static int start_heartbeat_timer = false;
#endif
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
struct cyttsp *cyttsp_data = NULL;
#endif
/* To check touch chip */
static int Touch_Dbg_Enable =0;
//static u16 prev_mt_pos[CYTTSP_NUM_TRACK_ID][2];
static struct wake_lock touch_wake_lock;
typedef enum touch_status {
TOUCH_POWERON,
TOUCH_POWEROFF,
TOUCH_UPDATE
} touch_status;
typedef enum
{
BATTERY_PLUGGED_NONE = 0,
BATTERY_PLUGGED_AC = 1,
BATTERY_PLUGGED_USB = 2,
BATTERY_PLUGGED_SLEEP = 10
} CHARGER_MODE;
typedef enum touch_ioctl {
TOUCH_CHARGER_MODE = 701,
TOUCH_IOCTL_READ_LASTKEY = 1001,
TOUCH_IOCTL_DO_KEY,
TOUCH_IOCTL_RELEASE_KEY,
TOUCH_IOCTL_PRESS_TOUCH = 1007,
TOUCH_IOCTL_RELEASE_TOUCH,
TOUCH_IOCTL_SENSOR_X = 2005,
TOUCH_IOCTL_SENSOR_Y,
TOUCH_IOCTL_CHECK_BASE,
TOUCH_IOCTL_READ_IC_VERSION,
TOUCH_IOCTL_READ_FW_VERSION,
TOUCH_IOCTL_START_UPDATE,
TOUCH_IOCTL_SELF_TEST,
TOUCH_IOCTL_SET_COLOR
} touch_ioctl;
static int Touch_Status =TOUCH_POWERON;
static int Touch_ChagerMode = BATTERY_PLUGGED_NONE;
static unsigned char bBlack=false;
struct cyttsp *ts_temp;
#if defined(CONFIG_APACHE_BOARD)
struct delayed_work work_delay_firmware;
#endif
MODULE_DEVICE_TABLE(i2c, cyttsp_id);
/* ****************************************************************************
* Prototypes for static functions
* ************************************************************************** */
static void cyttsp_xy_worker(struct work_struct *work);
#ifdef FEATURE_CYTTSP_HEARTBEAT
static void cyttsp_check_heartbeat(struct work_struct *work2);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
void check_firmware_update(struct work_struct *work3);
#endif
static irqreturn_t cyttsp_irq(int irq, void *handle);
#if 0
static int cyttsp_inlist(u16 prev_track[], u8 curr_track_id, u8 *prev_loc, u8 num_touches);
static int cyttsp_next_avail_inlist(u16 curr_track[], u8 *new_loc, u8 num_touches);
#endif
#ifdef CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
static int cyttsp_putbl(struct cyttsp *ts, int show, int show_status, int show_version, int show_cid);
#endif// CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
static int __devinit cyttsp_probe(struct i2c_client *client, const struct i2c_device_id *id);
static int __devexit cyttsp_remove(struct i2c_client *client);
static int cyttsp_resume(struct i2c_client *client);
static int cyttsp_suspend(struct i2c_client *client, pm_message_t message);
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
static long ts_fops_ioctl(struct file *filp,unsigned int cmd, unsigned long arg);
static int ts_fops_open(struct inode *inode, struct file *filp);
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cyttsp_early_suspend(struct early_suspend *handler);
static void cyttsp_late_resume(struct early_suspend *handler);
#endif /* CONFIG_HAS_EARLYSUSPEND */
static int pantech_auto_check(u8*);
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
static int firmware_update_by_user(void);
static int firmware_version_check(void);
#endif
static int pantech_selftest_check(void);
void Change_Active_Distance(u8 value); //test
/* ****************************************************************************
*
* ************************************************************************** */
static struct i2c_driver cyttsp_driver = {
.driver = {
.name = CYTTSP_I2C_NAME,
.owner = THIS_MODULE,
},
.probe = cyttsp_probe,
.remove = __devexit_p(cyttsp_remove),
// .suspend = cyttsp_suspend,
// .resume = cyttsp_resume,
.id_table = cyttsp_id,
};
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen driver");
MODULE_AUTHOR("Cypress");
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
struct cyttsp *sky_process_cmd_ts=NULL;
static struct file_operations ts_fops = {
.owner = THIS_MODULE,
.open = ts_fops_open,
// .release = ts_fops_close,
.unlocked_ioctl = ts_fops_ioctl,
};
static struct miscdevice touch_event = {
.minor = MISC_DYNAMIC_MINOR,
.name = "touch_fops",
.fops = &ts_fops,
};
static int ts_fops_open(struct inode *inode, struct file *filp)
{
//filp->private_data = cyttsp_data;
return 0;
}
#if 1 //[BIH] ICS port... ioctl changed to unlocked_ioctl or compact_ioctl...
//static DEFINE_MUTEX(cyttsp_mutex);
static long ts_fops_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
#else
static int ts_fops_ioctl(struct inode *inode, struct file *filp,
unsigned int cmd, unsigned long arg)
#endif
{
void __user *argp = (void __user *)arg;
if(cyttsp_data ==NULL)
{
cyttsp_debug("Null Device\n");
return 0;
}
cyttsp_debug("cmd = %d, argp = 0x%x\n", cmd, (unsigned int)argp);
// printk("cmd = %d, argp = 0x%x\n", cmd, (unsigned int)argp);
// mutex_lock(&cyttsp_mutex);
switch (cmd)
{
case TOUCH_IOCTL_READ_LASTKEY:
break;
case TOUCH_IOCTL_DO_KEY:
if ( (int)argp == 0x20a )
input_report_key(cyttsp_data->input, 0xe3, 1);
else if ( (int)argp == 0x20b )
input_report_key(cyttsp_data->input, 0xe4, 1);
else
input_report_key(cyttsp_data->input, (int)argp, 1);
input_sync(cyttsp_data->input);
if((int)argp == KEY_9)
{
printk("Enable Touch Debug!!\n");
Touch_Dbg_Enable = true;
}
else if((int)argp == KEY_8)
{
printk("Disable Touch Debug!!\n");
Touch_Dbg_Enable = false;
}
/*
else if((int)argp == KEY_F2)
{
int ret = 0;
printk("Start Touch Firmware update!!\n");
ret = firmware_update_by_user();
}
*/
break;
case TOUCH_IOCTL_RELEASE_KEY:
if ( (int)argp == 0x20a )
input_report_key(cyttsp_data->input, 0xe3, 0);
else if ( (int)argp == 0x20b )
input_report_key(cyttsp_data->input, 0xe4, 0);
else
input_report_key(cyttsp_data->input, (int)argp, 0);
input_sync(cyttsp_data->input);
break;
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
case TOUCH_IOCTL_PRESS_TOUCH:
{
int touchX=arg&0x0000FFFF;
int touchY= (arg >> 16) & 0x0000FFFF;
input_report_abs(cyttsp_data->input, ABS_MT_TOOL_TYPE , 1);
input_report_abs(cyttsp_data->input, ABS_MT_TOUCH_MAJOR, CYTTSP_TOUCH);
input_report_abs(cyttsp_data->input, ABS_MT_WIDTH_MAJOR, CYTTSP_SMALL_TOOL_WIDTH);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_X, touchX);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_Y, touchY);
CYTTSP_MT_SYNC(cyttsp_data->input);
input_sync(cyttsp_data->input);
}
break;
case TOUCH_IOCTL_RELEASE_TOUCH:
{
int touchX=arg&0x0000FFFF;
int touchY= (arg >> 16) & 0x0000FFFF;
input_report_abs(cyttsp_data->input, ABS_MT_TOOL_TYPE , 1);
input_report_abs(cyttsp_data->input, ABS_MT_TOUCH_MAJOR, CYTTSP_NOTOUCH);
input_report_abs(cyttsp_data->input, ABS_MT_WIDTH_MAJOR, CYTTSP_SMALL_TOOL_WIDTH);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_X, touchX);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_Y, touchY);
CYTTSP_MT_SYNC(cyttsp_data->input);
input_sync(cyttsp_data->input);
}
break;
// ---
case TOUCH_IOCTL_SENSOR_X:
{
int send_data;
send_data = SENSOR_X;
if (copy_to_user(argp, &send_data, sizeof(send_data)))
return false;
}
break;
case TOUCH_IOCTL_SENSOR_Y:
{
int send_data;
send_data = SENSOR_Y;
if (copy_to_user(argp, &send_data, sizeof(send_data)))
return false;
}
break;
case TOUCH_IOCTL_CHECK_BASE:
{
u8 send_byte[MAX_NODE];
//printk("TOUCH_IOCTL_CHECK_BASE!!\n");
disable_irq_nosync(ts_temp->client->irq);
pantech_auto_check(send_byte);
enable_irq(ts_temp->client->irq);
if (copy_to_user(argp, send_byte, MAX_NODE))
return false;
}
break;
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
case TOUCH_IOCTL_READ_IC_VERSION:
{
int ret = 0;
ret = firmware_version_check();
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_READ_FW_VERSION:
{
int ret =0;
if(bBlack == false) // White Model etc..
ret = CYTTPS_NONBLACK_FIRMWARE_VER_ID;
else // Black Model
ret = CYTTPS_FIRMWARE_VER_ID;
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_START_UPDATE:
{
int ret = 0;
ret = firmware_update_by_user(); // if ret == 0 success, or not fail
printk("TOUCH_IOCTL_START_UPDATE ret : %d\n", ret);
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
#endif
case TOUCH_CHARGER_MODE:
printk("TOUCH_CHARGER_MODE Setting : %d\n", (int)arg);
Touch_ChagerMode = arg;
break;
case TOUCH_IOCTL_SELF_TEST:
{
int ret = 0;
ret = pantech_selftest_check();
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_SET_COLOR:
bBlack = arg;
break;
default:
break;
}
// mutex_unlock(&cyttsp_mutex);
return true;
}
#endif
void Change_Active_Distance(u8 value)
{
int rc = -1;
u8 byte_data;
struct cyttsp *ts = ts_temp;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET,sizeof(byte_data), &byte_data);
//printk("Chage_Active_Distance : %02x\n", byte_data);
byte_data = value;
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET, sizeof(byte_data), &byte_data);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
return;
}
static ssize_t cyttsp_irq_status(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = container_of(dev,
struct i2c_client, dev);
struct cyttsp *ts = i2c_get_clientdata(client);
return sprintf(buf, "%u\n", atomic_read(&ts->irq_enabled));
}
static ssize_t cyttsp_irq_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct i2c_client *client = container_of(dev,
struct i2c_client, dev);
struct cyttsp *ts = i2c_get_clientdata(client);
int err = 0;
unsigned long value;
/*
struct qtm_obj_message *msg;
*/
if (size > 2)
return -EINVAL;
err = strict_strtoul(buf, 10, &value);
if (err != 0)
return err;
switch (value) {
case 0:
if (atomic_cmpxchg(&ts->irq_enabled, 1, 0)) {
pr_info("touch irq disabled!\n");
disable_irq_nosync(ts->client->irq);
}
err = size;
break;
case 1:
if (!atomic_cmpxchg(&ts->irq_enabled, 0, 1)) {
pr_info("touch irq enabled!\n");
/*
msg = cyttsp_read_msg(ts);
if (msg == NULL)
pr_err("%s: Cannot read message\n", __func__);
*/
enable_irq(ts->client->irq);
}
err = size;
break;
default:
pr_info("cyttsp_irq_enable failed -> irq_enabled = %d\n",
atomic_read(&ts->irq_enabled));
err = -EINVAL;
break;
}
return err;
}
static DEVICE_ATTR(irq_enable, 0664, cyttsp_irq_status, cyttsp_irq_enable);
int pantech_ctl_update(int cmd, int value)
{
int rt = -1;
struct regulator *vreg_touch, *vreg_touch_temp;
switch(cmd)
{
case ISSP_IOCTL_SCLK_TO_GPIO:
if(value){
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
else{
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
rt = 1;
break;
case ISSP_IOCTL_DATA_TO_GPIO:
if(value){
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
else{
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
rt = 1;
break;
case ISSP_IOCTL_SCLK:
gpio_set_value(GPIO_TOUCH_SCL, value);
rt = 1;
break;
case ISSP_IOCTL_DATA:
gpio_set_value(GPIO_TOUCH_SDA, value);
rt = 1;
break;
case ISSP_IOCTL_RESET:
break;
case ISSP_IOCTL_POWER:
//printk("Touch Power: %d, cmd: %d\n", value, cmd);
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_touch = regulator_get(NULL, "8058_l11");
regulator_set_voltage(vreg_touch, 1900000, 1900000);
#else
vreg_touch = regulator_get(NULL, "8058_lvs0");
#endif
if(value)
rt = regulator_enable(vreg_touch);
else
rt = regulator_disable(vreg_touch);
regulator_put(vreg_touch);
break;
case ISSP_IOCTL_POWER_ALL:
//printk("Touch Power All: %d, cmd: %d\n", value, cmd);
vreg_touch_temp = regulator_get(NULL, "8058_l19");
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_touch = regulator_get(NULL, "8058_l11");
regulator_set_voltage(vreg_touch, 1900000, 1900000);
#else
vreg_touch = regulator_get(NULL, "8058_lvs0");
#endif
regulator_set_voltage(vreg_touch_temp, 3000000, 3000000);
if(value)
{
rt = regulator_enable(vreg_touch);
rt = regulator_enable(vreg_touch_temp);
}
else
{
rt = regulator_disable(vreg_touch);
rt = regulator_disable(vreg_touch_temp);
}
regulator_put(vreg_touch);
regulator_put(vreg_touch_temp);
break;
case ISSP_IOCTL_READ_DATA_PIN:
rt = gpio_get_value(GPIO_TOUCH_SDA);
break;
case ISSP_IOCTL_WAIT:
udelay(value);
break;
case ISSP_IOCTL_INTR:
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_CHG, value);
rt = 1;
break;
case ISSP_TEST_READ_SCL:
rt = gpio_get_value(GPIO_TOUCH_SCL);
break;
case ISSP_TEST_READ_SDA:
rt = gpio_get_value(GPIO_TOUCH_SDA);
break;
case ISSP_TEST_READ_RESET:
rt = gpio_get_value(GPIO_TOUCH_RST);
break;
case ISSP_COMPLITED_UPDATA:
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
rt = 1;
break;
default:
dbg("UNKNOWN CMD\n");
break;
}
return rt;
}
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
void check_firmware_update(struct work_struct *work3)
{
int retry_cnt = 3;
u8 byte_data[4];
int rc = -1, check_update_pass = 0, curr_version =0;
struct cyttsp *ts = ts_temp;
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return;
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
#endif
wake_lock(&touch_wake_lock);
disable_irq(ts->client->irq);
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
} while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
dbg("i2c communcation1 %s, byte_data = %d, %d, %d, %d\n", (rc < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS",byte_data[0],byte_data[1],byte_data[2],byte_data[3]);
if((int)byte_data[0] == 0 || rc < CYTTSP_OPERATIONAL)
{
dbg("Retry read firmware version!\n");
msleep(200);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(200);
retry_cnt = 3;
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
} while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
}
pantech_ctl_update(ISSP_IOCTL_INTR,0);
#ifdef FEATURE_SKY_NONBLACK_FIRMWARE
if(rc >= CYTTSP_OPERATIONAL) // read success
bBlack = (int)byte_data[0] % 2;
if(bBlack == false) // White Model etc..
curr_version = CYTTPS_NONBLACK_FIRMWARE_VER_ID;
else // Black Model
curr_version = CYTTPS_FIRMWARE_VER_ID;
#else
curr_version = CYTTPS_FIRMWARE_VER_ID;
#endif
dbg("[Touch] Model Black Check: %d, Current Version: %d\n", bBlack, curr_version);
if(((curr_version > byte_data[0]) && (byte_data[0] != 0)) || (rc < CYTTSP_OPERATIONAL))
{
retry_cnt = 5;
dbg("Start Firmware Update chip id: %d\n", byte_data[0]);
do{
check_update_pass = touch_update_main(bBlack);
udelay(2*1000);
}while((check_update_pass != 0) && --retry_cnt);
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
pantech_ctl_update(ISSP_IOCTL_INTR,1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA,0);
if(check_update_pass != 0)
{
msleep(200);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(100);
cancel_work_sync(&ts->work);
}
dbg("check_firmware_update end!!(check_update_pass = %d)\n",check_update_pass);
enable_irq(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
#endif
wake_unlock(&touch_wake_lock);
return;
}
static int firmware_version_check(void)
{
int rc = -1, retry_cnt = 3;
u8 byte_data[4];
struct cyttsp *ts = ts_temp;
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA, 0);
msleep(300);
// return false;
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(rc < CYTTSP_OPERATIONAL)
{
printk("Can't read Touch Firmware Version\n");
return 1;
}
printk("Touch Firmware Update Version : %d, Current Version: %d\n" ,
CYTTPS_FIRMWARE_VER_ID,(int)byte_data[0]);
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 0);
}
return (int)byte_data[0]; // Need not
}
static int firmware_set_charger_mode(int mode)
{
int rc = -1, retry_cnt = 3;
u8 byte_data[4], send_byte = 0x00;
struct cyttsp *ts = ts_temp;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(rc < CYTTSP_OPERATIONAL)
{
printk("Can't read Touch Charger Mode\n");
return 1;
}
if(Touch_Dbg_Enable)
printk("Touch IC Charger Mode %02x\n" ,(int)byte_data[0]);
if(mode > BATTERY_PLUGGED_NONE) // charger mode on
{
if((int)byte_data[0] != CYTTPS_CHARGER_MODE)
{
send_byte = CYTTPS_CHARGER_MODE;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE, sizeof(send_byte), &send_byte);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
}
}
else // charger mode off
{
if((int)byte_data[0] != 0x00)
{
send_byte = 0x00;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE, sizeof(send_byte), &send_byte);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
}
}
return 0;
}
static int firmware_update_by_user(void)
{
struct cyttsp *ts = ts_temp;
int check_update_pass = -1;
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
msleep(300);
// return false;
}
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
#endif
Touch_Status= TOUCH_UPDATE;
wake_lock(&touch_wake_lock);
/*ÀÎÅÍ·´ÅÍ PIN HIGH »óŸ¦ º¯°æÇϱâ À§ÇØ IRQ¸¦ ÇØÁ¦ÇÔ */
disable_irq(ts->client->irq);
/* ÀÎÆ®·´ÅÍ PIN HIGH »óÅ·ΠÀÎÇÏ¿© 2.6V_TOUCH Àü¿ø OFFÇÏ¿©µµ 1.2V Àü¾Ð È帣´Â Çö»óÀ¸·Î Value°ªÀ» 0À¸·Î ¼³Á¤ */
pantech_ctl_update(ISSP_IOCTL_INTR,0);
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
check_update_pass = touch_update_main(bBlack);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
pantech_ctl_update(ISSP_IOCTL_INTR,1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA,0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(100);
cancel_work_sync(&ts->work);
enable_irq(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
#endif
wake_unlock(&touch_wake_lock);
Touch_Status= TOUCH_POWERON;
return check_update_pass;
}
#endif
/* The cyttsp_xy_worker function reads the XY coordinates and sends them to
* the input layer. It is scheduled from the interrupt (or timer).
*/
#ifdef FEATURE_TOUCH_KEY
#define CYTTSP_MENU_KEY 0x01
#define CYTTSP_BACK_KEY 0x02
#define CYTTSP_HOME_KEY 0x04
#define CYTTSP_NULL_KEY 0x08
static int key_status = 0x00;
#endif
#if 0//def FEATURE_SKY_TOUCH_DELTA_DEBUG
static u16 pre_x_data;
static u16 pre_y_data;
static u16 delta_x;
static u16 delta_y;
#endif
#ifdef FEATURE_CYTTSP_HEARTBEAT
void cyttsp_check_heartbeat(struct work_struct *work2)
{
struct cyttsp *ts = container_of(work2,struct cyttsp,work2);
int retry_cnt = 3;
u8 new_heartbeart_data[4];
int rc = -1;
static u8 old_heartbeat_data = 0xFF;
memset((void*)new_heartbeart_data,0x00,sizeof(new_heartbeart_data));
if(start_heartbeat_timer == false)
return;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
/* Read Heartbeat Count */
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_HEARTBEAT,sizeof(new_heartbeart_data), (u8 *)&new_heartbeart_data);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(Touch_Dbg_Enable)
printk("##### Check Count = %s, byte_data = %d, %d, %d, %d\n", (rc < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS",new_heartbeart_data[0],new_heartbeart_data[1],new_heartbeart_data[2],new_heartbeart_data[3]);
if(start_heartbeat_timer == false)
return;
if(rc < CYTTSP_OPERATIONAL || old_heartbeat_data == new_heartbeart_data[0])
{
/* I2c error or Touch Chip's heartbeat value is not change */
disable_irq(ts->client->irq);
pantech_ctl_update(ISSP_IOCTL_INTR,0);
pantech_ctl_update(ISSP_IOCTL_POWER,0);
msleep(200);
pantech_ctl_update(ISSP_IOCTL_INTR,1);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
enable_irq(ts->client->irq);
pantech_ctl_update(ISSP_IOCTL_POWER,1);
if(Touch_Dbg_Enable)
printk("HeartBeat Fail old_data = %d, new_data = %d",old_heartbeat_data, new_heartbeart_data[0]);
}
if(!start_heartbeat_timer)
old_heartbeat_data = 0xFF;
// Set Charger Mode
firmware_set_charger_mode(Touch_ChagerMode);
return;
}
#endif
static bool cur_touchflag[TOUCH_MAX_NUM];
int touch_mask[TOUCH_MAX_NUM];
struct cyttsp_trk cur_trk[TOUCH_MAX_NUM];
void cyttsp_xy_worker(struct work_struct *work)
{
struct cyttsp *ts = container_of(work,struct cyttsp,work);
int i;
int retval = 0;
u8 curr_touches = 0;
u8 id = 0;
// int t = 0;
// int num_sent = 0;
// int signal = 0;
int tch = 0;
#ifdef FEATURE_TOUCH_KEY
int key_relese = true;
#endif
for (i=0;i<TOUCH_MAX_NUM;i++)
{
touch_mask[i] = -1;
}
if(Touch_Dbg_Enable)
printk("[TOUCH] Start cyttsp_xy_worker\n");
if(Touch_Status >= TOUCH_POWEROFF)
goto exit_xy_worker;
/* get event data from CYTTSP device */
i = CYTTSP_NUM_RETRY;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(struct cyttsp_gen3_xydata_t), (u8 *)&g_xy_data);
}
while ((retval < CYTTSP_OPERATIONAL) && --i);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
/* return immediately on failure to read device on the i2c bus */
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_debug("exit_xy_worker 1");
goto exit_xy_worker;
}
cyttsp_xdebug("TTSP worker start 2:\n");
if ((curr_touches = GET_NUM_TOUCHES(g_xy_data.tt_stat)) > CYTTSP_NUM_MT_TOUCH_ID) {
/* if the number of fingers on the touch surface is more than the maximum
* then there will be no new track information even for the orginal
* touches. Therefore, ignore this touch event.
*/
cyttsp_debug("exit_xy_worker 2");
goto exit_xy_worker;
}
else if (IS_LARGE_AREA(g_xy_data.tt_stat)==1) {
/* terminate all active tracks */
curr_touches = CYTTSP_NOTOUCH;
cyttsp_debug("Large object detected. Terminating active tracks\n");
}
#ifdef FEATURE_TOUCH_KEY
for(i=0; i<curr_touches; i++)
{
int x =0, y=0;
switch(i)
{
case 0:
x = be16_to_cpu(g_xy_data.x1);
y = be16_to_cpu(g_xy_data.y1);
break;
case 1:
x = be16_to_cpu(g_xy_data.x2);
y = be16_to_cpu(g_xy_data.y2);
break;
case 2:
x = be16_to_cpu(g_xy_data.x3);
y = be16_to_cpu(g_xy_data.y3);
break;
case 3:
x = be16_to_cpu(g_xy_data.x4);
y = be16_to_cpu(g_xy_data.y4);
break;
default:
break;
}
if(y > Y_MAX)
{
key_relese = false;
if(y < NULL_KEY_AREA && (!key_status || key_status == CYTTSP_NULL_KEY))
{
key_status = CYTTSP_NULL_KEY;
dbg("Down TOUCH NULL\n");
}
else if((MENU_KEY_MIN < x && x < MENU_KEY_MAX) && (!key_status || key_status == CYTTSP_MENU_KEY))
{
key_status = CYTTSP_MENU_KEY;
input_report_key(ts->input, KEY_MENU, CYTTSP_TOUCH);
dbg("Down TOUCH MENU\n");
input_sync(ts->input);
}
else if((HOME_KEY_MIN < x && x < HOME_KEY_MAX) && (!key_status || key_status == CYTTSP_HOME_KEY))
{
key_status = CYTTSP_HOME_KEY;
input_report_key(ts->input, KEY_HOMEPAGE, CYTTSP_TOUCH);
dbg("Down TOUCH HOME\n");
input_sync(ts->input);
}
else if((BACK_KEY_MIN < x && x < BACK_KEY_MAX) && (!key_status || key_status == CYTTSP_BACK_KEY))
{
key_status = CYTTSP_BACK_KEY;
input_report_key(ts->input, KEY_BACK, CYTTSP_TOUCH);
dbg("Down TOUCH BACK\n");
input_sync(ts->input);
}
else if(!key_status)
key_status = CYTTSP_NULL_KEY;
}
}
if(key_relese && (curr_touches < prev_touches) && key_status)
{
if(key_status == CYTTSP_MENU_KEY)
input_report_key(ts->input, KEY_MENU, CYTTSP_NOTOUCH);
if(key_status == CYTTSP_HOME_KEY)
input_report_key(ts->input, KEY_HOMEPAGE, CYTTSP_NOTOUCH);
if(key_status == CYTTSP_BACK_KEY)
input_report_key(ts->input, KEY_BACK, CYTTSP_NOTOUCH);
if(key_status != CYTTSP_NULL_KEY)
input_sync(ts->input);
dbg("Up Key: %02x\n", key_status);
key_status = 0;
}
#endif
/* send no events if there were no previous touches and no new touches */
if ((prev_touches == CYTTSP_NOTOUCH) &&
((curr_touches == CYTTSP_NOTOUCH) || (curr_touches > CYTTSP_NUM_MT_TOUCH_ID))) {
cyttsp_debug("exit_xy_worker 3");
goto exit_xy_worker;
}
cyttsp_debug("prev=%d curr=%d\n", prev_touches, curr_touches);
dbg("cur#: %d, tch : 0x%x\n", curr_touches,tch);
dbg("touch12_id : 0x%x, touch34_id : 0x%x\n", g_xy_data.touch12_id,g_xy_data.touch34_id);
/* extract xy_data for all currently reported touches */
for (tch = 0; tch < curr_touches; tch++)
{
if (tch < 2)
{
id = (tch & 0x01) ?
GET_TOUCH2_ID(g_xy_data.touch12_id) : //LO_TRACKID(*(ts->tch_map[tch].id)) :
GET_TOUCH1_ID(g_xy_data.touch12_id); //HI_TRACKID(*(ts->tch_map[tch].id));
// touch_mask[id] = tch;
if (tch == 0)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x1);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y1);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z1;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
if (tch == 1)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x2);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y2);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z2;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
}
else
{
id = (tch & 0x01) ?
GET_TOUCH4_ID(g_xy_data.touch34_id) : //LO_TRACKID(*(ts->tch_map[tch].id)) :
GET_TOUCH3_ID(g_xy_data.touch34_id); //HI_TRACKID(*(ts->tch_map[tch].id));
if (tch == 2)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x3);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y3);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z3;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
if (tch == 3)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x4);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y4);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z4;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
}
if(id < TOUCH_MAX_NUM){
touch_mask[id] = tch;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
dbg("tch#: %d, ID: %d, Xpos: %d, Ypos: %d\n",
tch, id, cur_trk[id].abs[CY_ABS_X_OST], cur_trk[id].abs[CY_ABS_Y_OST]);
}
// Release Event
if ( curr_touches == 0 )
{
dbg("Touch Released\n");
for (i=0; i < TOUCH_MAX_NUM; i++)
{
if (cur_touchflag[i] /*cur_trk[i].abs[CY_ABS_ID_OST] >= 0*/)
{
cur_trk[i].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[i] = 0;
input_mt_slot(ts->input, i);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
dbg("Touch Released 1, I : %d\n",i);
}
}
}
// Finger Touched
else
{
dbg("Touch Pressed\n");
for (i=0; i<TOUCH_MAX_NUM; i++)
{
if ( touch_mask[i] < 0 ) // 1 case - the 1st finger : touched / the 2nd finger : released
{
#if 1
if ( cur_trk[i].abs[CY_ABS_ID_OST] >= 0 )
{
cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] = 0;
cur_trk[i].abs[CY_ABS_ID_OST] = -1;
input_mt_slot(ts->input, i);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
dbg("Touch Pressed 1\n");
}
#endif
}
else
{
if(touch_mask[i] >= 0) // if finger is touched
{
input_mt_slot(ts->input, i);
if ( (cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] == 0) )
{
dbg("Touch Pressed 2-1 I:%d, touchflag : %d\n",i,cur_touchflag[i]);
cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] = 1;
//cur_trk[i].abs[CY_ABS_ID_OST] = input_mt_new_trkid(ts->input);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
}
// Move Event
// input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_X, cur_trk[i].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, cur_trk[i].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, cur_trk[i].abs[CY_ABS_P_OST]);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, 1);
input_report_abs(ts->input, ABS_MT_WIDTH_MAJOR, cur_trk[i].abs[CY_ABS_P_OST]);
dbg("Touch Pressed 2-2 I:%d, touchflag : %d\n",i,cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]]);
}
}
}
}
input_report_key(ts->input, BTN_TOUCH, (curr_touches>0)? 1:0 );
input_sync(ts->input);
// update previous touch num
prev_touches = curr_touches;
goto exit_xy_worker;
#if 0
/* provide input event signaling for each active touch */
for (id = 0, num_sent = 0; id < CYTTSP_NUM_TRACK_ID; id++)
{
if (cur_trk[id].tch)
{
t = cur_trk[id].abs[CY_ABS_ID_OST];
/* send 0 based track id's */
t -= 1;
input_report_abs(ts->input, ABS_MT_TRACKING_ID, t);
input_report_abs(ts->input, ABS_MT_POSITION_X, cur_trk[id].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, cur_trk[id].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, cur_trk[id].abs[CY_ABS_P_OST]);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, cur_trk[id].abs[CY_ABS_W_OST]);
num_sent++;
input_mt_sync(ts->input);
ts->prv_trk[id] = cur_trk[id];
ts->prv_trk[id].abs[CY_ABS_ID_OST] = t;
#if 0
cyttsp_dbg(ts, CY_DBG_LVL_1, "%s: ID:%3d X:%3d Y:%3d " "Z:%3d W=%3d T=%3d\n", __func__, id,
cur_trk[id].abs[CY_ABS_X_OST],
cur_trk[id].abs[CY_ABS_Y_OST],
cur_trk[id].abs[CY_ABS_P_OST],
cur_trk[id].abs[CY_ABS_W_OST],
t);
#endif
}
else if ((ABS_MT_PRESSURE == ABS_MT_TOUCH_MAJOR) && ts->prv_trk[id].tch)
{
/*
* pre-Gingerbread:
* need to report last position with
* and report that position with
* no touch if the touch lifts off
*/
input_report_abs(ts->input, ABS_MT_TRACKING_ID, ts->prv_trk[id].abs[CY_ABS_ID_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_X, ts->prv_trk[id].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, ts->prv_trk[id].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, CYTTSP_NOTOUCH);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, CYTTSP_NOTOUCH);
num_sent++;
input_mt_sync(ts->input);
ts->prv_trk[id].tch = CYTTSP_NOTOUCH;
#if 0
cyttsp_dbg(ts, CY_DBG_LVL_1,
"%s: ID:%3d X:%3d Y:%3d "
"Z:%3d W=%3d T=%3d liftoff\n",
__func__, ts->prv_trk[id].abs[CY_ABS_ID_OST],
ts->prv_trk[id].abs[CY_ABS_X_OST],
ts->prv_trk[id].abs[CY_ABS_Y_OST],
CYTTSP_NOTOUCH,
CYTTSP_NOTOUCH,
ts->prv_trk[id].abs[CY_ABS_ID_OST]);
#endif
}
}
if (num_sent == 0)
{
/* in case of 0-touch; all liftoff; Gingerbread+ */
input_mt_sync(ts->input);
}
input_sync(ts->input);
// update previous touch num
prev_touches = curr_touches;
goto exit_xy_worker;
#endif
exit_xy_worker:
/*if(cyttsp_disable_touch) {
cyttsp_debug("Not enabling touch\n");
}
else*/ { // N1037 20120521 for ICS cyttsp_disable_touch ¼³Á¤µÇ¸é¼ touch¿Àµ¿ÀÛ ¹ß»ý ICS org¿¡¼ »ç¿ëµÇÁö ¾Ê´Â ÄÚµå ÀÓ
if(ts->client->irq == 0) {
/* restart event timer */
mod_timer(&ts->timer, jiffies + TOUCHSCREEN_TIMEOUT);
}
else {
/* re-enable the interrupt after processing */
enable_irq(ts->client->irq);
}
}
return;
}
#if 0
static int cyttsp_inlist(u16 prev_track[], u8 curr_track_id, u8 *prev_loc, u8 num_touches)
{
u8 id =0;
*prev_loc = CYTTSP_IGNORE_TOUCH;
cyttsp_xdebug("IN p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
for (id = 0, *prev_loc = CYTTSP_IGNORE_TOUCH;
(id < num_touches); id++) {
cyttsp_xdebug("p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
if (prev_track[id] == curr_track_id) {
*prev_loc = id;
break;
}
}
cyttsp_xdebug("OUT p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
return ((*prev_loc < CYTTSP_NUM_TRACK_ID) ? true : false);
}
static int cyttsp_next_avail_inlist(u16 curr_track[], u8 *new_loc, u8 num_touches)
{
u8 id;
for (id = 0, *new_loc = CYTTSP_IGNORE_TOUCH;
(id < num_touches); id++) {
if (curr_track[id] > CYTTSP_NUM_TRACK_ID) {
*new_loc = id;
break;
}
}
return ((*new_loc < CYTTSP_NUM_TRACK_ID) ? true : false);
}
#endif
/* Timer function used as dummy interrupt driver */
static void cyttsp_timer(unsigned long handle)
{
struct cyttsp *ts = (struct cyttsp *) handle;
cyttsp_xdebug("TTSP Device timer event\n");
#ifdef FEATURE_CYTTSP_HEARTBEAT
/* schedule motion signal handling */
if(start_heartbeat_timer)
{
schedule_work(&ts->work2);
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * HZ);
}
#else
/* schedule motion signal handling */
schedule_work(&ts->work);
#endif
return;
}
/* ************************************************************************
* ISR function. This function is general, initialized in drivers init
* function
* ************************************************************************ */
static irqreturn_t cyttsp_irq(int irq, void *handle)
{
struct cyttsp *ts = (struct cyttsp *) handle;
cyttsp_xdebug("%s: Got IRQ\n", CYTTSP_I2C_NAME);
if(Touch_Status >= TOUCH_POWEROFF)
return IRQ_HANDLED;
/* disable further interrupts until this interrupt is processed */
disable_irq_nosync(ts->client->irq);
/* schedule motion signal handling */
schedule_work(&ts->work);
return IRQ_HANDLED;
}
#ifdef CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
/* ************************************************************************
* Probe initialization functions
* ************************************************************************ */
static int cyttsp_putbl(struct cyttsp *ts, int show, int show_status, int show_version, int show_cid)
{
int retval = CYTTSP_OPERATIONAL;
int num_bytes = (show_status * 3) + (show_version * 6) + (show_cid * 3);
if (show_cid) {
num_bytes = sizeof(struct cyttsp_bootloader_data_t);
}
else if (show_version) {
num_bytes = sizeof(struct cyttsp_bootloader_data_t) - 3;
}
else {
num_bytes = sizeof(struct cyttsp_bootloader_data_t) - 9;
}
if (show) {
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
num_bytes, (u8 *)&g_bl_data);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if (show_status) {
cyttsp_debug("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X\n", \
show, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo);
}
if (show_version) {
cyttsp_debug("BL%d: ttspver=0x%02X%02X appid=0x%02X%02X appver=0x%02X%02X\n", \
show, \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
g_bl_data.appver_hi, g_bl_data.appver_lo);
}
if (show_cid) {
cyttsp_debug("BL%d: cid=0x%02X%02X%02X\n", \
show, \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2);
}
mdelay(CYTTSP_DELAY_DFLT);
}
return retval;
}
#endif //CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
#ifdef CYTTSP_INCLUDE_LOAD_FILE
#define CYTTSP_MAX_I2C_LEN 256
#define CYTTSP_MAX_TRY 10
#define CYTTSP_BL_PAGE_SIZE 16
#define CYTTSP_BL_NUM_PAGES 5
static int cyttsp_i2c_write_block_data(struct i2c_client *client, u8 command,
u8 length, const u8 *values)
{
int retval = CYTTSP_OPERATIONAL;
u8 dataray[CYTTSP_MAX_I2C_LEN];
u8 try;
dataray[0] = command;
if (length) {
memcpy(&dataray[1], values, length);
}
try = CYTTSP_MAX_TRY;
do {
retval = i2c_master_send(client, dataray, length+1);
mdelay(CYTTSP_DELAY_DFLT*2);
}
while ((retval != length+1) && try--);
return retval;
}
static int cyttsp_i2c_write_block_data_chunks(struct cyttsp *ts, u8 command,
u8 length, const u8 *values)
{
int retval = CYTTSP_OPERATIONAL;
int block = 1;
u8 dataray[CYTTSP_MAX_I2C_LEN];
/* first page already includes the bl page offset */
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
CYTTSP_BL_PAGE_SIZE+1, values);
mdelay(10);
values += CYTTSP_BL_PAGE_SIZE+1;
length -= CYTTSP_BL_PAGE_SIZE+1;
/* rem blocks require bl page offset stuffing */
while (length && (block < CYTTSP_BL_NUM_PAGES) && !(retval < CYTTSP_OPERATIONAL)) {
dataray[0] = CYTTSP_BL_PAGE_SIZE*block;
memcpy(&dataray[1], values,
length >= CYTTSP_BL_PAGE_SIZE ? CYTTSP_BL_PAGE_SIZE : length);
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
length >= CYTTSP_BL_PAGE_SIZE ? CYTTSP_BL_PAGE_SIZE+1 : length+1, dataray);
mdelay(10);
values += CYTTSP_BL_PAGE_SIZE;
length = length >= CYTTSP_BL_PAGE_SIZE ? length - CYTTSP_BL_PAGE_SIZE : 0;
block++;
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
return retval;
}
static int cyttsp_bootload_app(struct cyttsp *ts)
{
int retval = CYTTSP_OPERATIONAL;
int i, tries;
u8 host_reg;
cyttsp_debug("load new firmware \n");
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
/* reset TTSP Device back to bootloader mode */
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete reset back to bootloader */
// mdelay(CYTTSP_DELAY_DFLT);
mdelay(1000);
cyttsp_putbl(ts,3, true, true, true);
cyttsp_debug("load file -- tts_ver=0x%02X%02X app_id=0x%02X%02X app_ver=0x%02X%02X\n", \
cyttsp_fw_tts_verh, cyttsp_fw_tts_verl, \
cyttsp_fw_app_idh, cyttsp_fw_app_idl, \
cyttsp_fw_app_verh, cyttsp_fw_app_verl);
/* download new TTSP Application to the Bootloader
*
*/
if (!(retval < CYTTSP_OPERATIONAL)) {
i = 0;
/* send bootload initiation command */
if (cyttsp_fw[i].Command == CYTTSP_BL_INIT_LOAD) {
g_bl_data.bl_file = 0;
g_bl_data.bl_status = 0;
g_bl_data.bl_error = 0;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
/* delay to allow bootloader to get ready for block writes */
i++;
tries = 0;
cyttsp_debug("wait init f=%02X, s=%02X, e=%02X t=%d\n",g_bl_data.bl_file,
g_bl_data.bl_status, g_bl_data.bl_error, tries);
do {
mdelay(1000);
cyttsp_putbl(ts,4, true, false, false);
}
while (g_bl_data.bl_status != 0x10 &&
g_bl_data.bl_status != 0x11 &&
tries++ < 10);
/* send bootload firmware load blocks -
* kernel limits transfers to I2C_SMBUS_BLOCK_MAX(32) bytes
*/
if (!(retval < CYTTSP_OPERATIONAL)) {
while (cyttsp_fw[i].Command == CYTTSP_BL_WRITE_BLK) {
retval = cyttsp_i2c_write_block_data_chunks(ts,
CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
// if (cyttsp_fw[i].Address & 0x01) {
// mdelay(CYTTSP_DELAY_DNLOAD);
// }
// else {
// mdelay(CYTTSP_DELAY_DNLOAD);
// }
/* bootloader requires delay after odd block addresses */
mdelay(100);
cyttsp_debug("BL DNLD Rec=% 3d Len=% 3d Addr=%04X\n",
cyttsp_fw[i].Record, cyttsp_fw[i].Length,
cyttsp_fw[i].Address);
i++;
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_debug("BL fail Rec=%3d retval=%d\n",cyttsp_fw[i-1].Record, retval);
break;
}
else {
/* reset TTSP I2C counter */
retval = cyttsp_i2c_write_block_data(ts->client,
CYTTSP_REG_BASE,
0, NULL);
mdelay(10);
/* set arg2 to non-0 to activate */
cyttsp_putbl(ts,5, true, false, false);
}
}
if (!(retval < CYTTSP_OPERATIONAL)) {
while (i < cyttsp_fw_records) {
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
i++;
tries = 0;
cyttsp_debug("wait init f=%02X, s=%02X, e=%02X t=%d\n",g_bl_data.bl_file,
g_bl_data.bl_status, g_bl_data.bl_error, tries);
do {
mdelay(1000);
cyttsp_putbl(ts,6, true, false, false);
}
while (g_bl_data.bl_status != 0x10 &&
g_bl_data.bl_status != 0x11 &&
tries++ < 10);
cyttsp_putbl(ts,7, true, false, false);
if (retval < CYTTSP_OPERATIONAL) {
break;
}
}
}
}
}
}
/* Do we need to reset TTSP Device back to bootloader mode?? */
/*
*/
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete reset back to bootloader */
/*
*/
mdelay(1000);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
/* set arg2 to non-0 to activate */
retval = cyttsp_putbl(ts, 8, true, true, true);
return retval;
}
#else
#if 0
static int cyttsp_bootload_app(struct cyttsp *ts)
{
cyttsp_debug("no-load new firmware \n");
return CYTTSP_OPERATIONAL;
}
#endif
#endif /* CYTTSP_INCLUDE_LOAD_FILE */
#if 0
static int cyttsp_power_on(struct cyttsp *ts)
{
int retval = CYTTSP_OPERATIONAL;
u8 host_reg;
int tries;
static u8 bl_cmd[] = {
CYTTSP_BL_FILE0, CYTTSP_BL_CMD, CYTTSP_BL_EXIT,
CYTTSP_BL_KEY0, CYTTSP_BL_KEY1, CYTTSP_BL_KEY2,
CYTTSP_BL_KEY3, CYTTSP_BL_KEY4, CYTTSP_BL_KEY5,
CYTTSP_BL_KEY6, CYTTSP_BL_KEY7};
cyttsp_debug("Power up \n");
/* check if the TTSP device has a bootloader installed */
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
tries = 0;
do {
mdelay(1000);
/* set arg2 to non-0 to activate */
retval = cyttsp_putbl(ts, 1, true, true, true);
cyttsp_info("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X R=%d\n", \
101, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo,
retval);
cyttsp_info("BL%d: tver=%02X%02X a_id=%02X%02X aver=%02X%02X\n", \
102, \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
g_bl_data.appver_hi, g_bl_data.appver_lo);
cyttsp_info("BL%d: c_id=%02X%02X%02X\n", \
103, \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2);
}
while (!(retval < CYTTSP_OPERATIONAL) &&
!GET_BOOTLOADERMODE(g_bl_data.bl_status) &&
!(g_bl_data.bl_file == CYTTSP_OPERATE_MODE + CYTTSP_LOW_POWER_MODE) &&
tries++ < 10);
/* is bootloader missing? */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug("Retval=%d Check if bootloader is missing...\n", retval);
if (!GET_BOOTLOADERMODE(g_bl_data.bl_status)) {
/* skip all bootloader and sys info and go straight to operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug("Bootloader is missing (retval = %d)\n", retval);
host_reg = CYTTSP_OPERATE_MODE/* + CYTTSP_LOW_POWER_MODE*/;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
goto bypass;
}
}
}
/* take TTSP out of bootloader mode; go to TrueTouch operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug1("exit bootloader; go operational\n");
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(bl_cmd), bl_cmd);
tries = 0;
do {
mdelay(1000);
cyttsp_putbl(ts,4, true, false, false);
cyttsp_info("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X\n", \
104, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo);
}
while (GET_BOOTLOADERMODE(g_bl_data.bl_status) &&
tries++ < 10);
}
if (!(retval < CYTTSP_OPERATIONAL) &&
cyttsp_app_load()) {
mdelay(1000);
if (CYTTSP_DIFF(g_bl_data.ttspver_hi, cyttsp_tts_verh()) ||
CYTTSP_DIFF(g_bl_data.ttspver_lo, cyttsp_tts_verl()) ||
CYTTSP_DIFF(g_bl_data.appid_hi, cyttsp_app_idh()) ||
CYTTSP_DIFF(g_bl_data.appid_lo, cyttsp_app_idl()) ||
CYTTSP_DIFF(g_bl_data.appver_hi, cyttsp_app_verh()) ||
CYTTSP_DIFF(g_bl_data.appver_lo, cyttsp_app_verl()) ||
CYTTSP_DIFF(g_bl_data.cid_0, cyttsp_cid_0()) ||
CYTTSP_DIFF(g_bl_data.cid_1, cyttsp_cid_1()) ||
CYTTSP_DIFF(g_bl_data.cid_2, cyttsp_cid_2()) ||
cyttsp_force_fw_load()) {
cyttsp_debug("blttsp=0x%02X%02X flttsp=0x%02X%02X force=%d\n", \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
cyttsp_tts_verh(), cyttsp_tts_verl(), cyttsp_force_fw_load());
cyttsp_debug("blappid=0x%02X%02X flappid=0x%02X%02X\n", \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
cyttsp_app_idh(), cyttsp_app_idl());
cyttsp_debug("blappver=0x%02X%02X flappver=0x%02X%02X\n", \
g_bl_data.appver_hi, g_bl_data.appver_lo, \
cyttsp_app_verh(), cyttsp_app_verl());
cyttsp_debug("blcid=0x%02X%02X%02X flcid=0x%02X%02X%02X\n", \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2, \
cyttsp_cid_0(), cyttsp_cid_1(), cyttsp_cid_2());
/* enter bootloader to load new app into TTSP Device */
retval = cyttsp_bootload_app(ts);
/* take TTSP device out of bootloader mode; switch back to TrueTouch operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(bl_cmd), bl_cmd);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
}
}
}
bypass:
/* switch to System Information mode to read versions and set interval registers */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_debug("switch to sysinfo mode \n");
host_reg = CYTTSP_SYSINFO_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to SysInfo mode */
mdelay(1000);
if (!(retval < CYTTSP_OPERATIONAL)) {
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(struct cyttsp_sysinfo_data_t), (u8 *)&g_sysinfo_data);
cyttsp_debug("SI2: hst_mode=0x%02X mfg_cmd=0x%02X mfg_stat=0x%02X\n", \
g_sysinfo_data.hst_mode, g_sysinfo_data.mfg_cmd, \
g_sysinfo_data.mfg_stat);
cyttsp_debug("SI2: bl_ver=0x%02X%02X\n", \
g_sysinfo_data.bl_verh, g_sysinfo_data.bl_verl);
cyttsp_debug("SI2: sysinfo act_int=0x%02X tch_tmout=0x%02X lp_int=0x%02X\n", \
g_sysinfo_data.act_intrvl, g_sysinfo_data.tch_tmout, \
g_sysinfo_data.lp_intrvl);
cyttsp_info("SI%d: tver=%02X%02X a_id=%02X%02X aver=%02X%02X\n", \
102, \
g_sysinfo_data.tts_verh, g_sysinfo_data.tts_verl, \
g_sysinfo_data.app_idh, g_sysinfo_data.app_idl, \
g_sysinfo_data.app_verh, g_sysinfo_data.app_verl);
cyttsp_info("SI%d: c_id=%02X%02X%02X\n", \
103, \
g_sysinfo_data.cid[0], g_sysinfo_data.cid[1], g_sysinfo_data.cid[2]);
if (!(retval < CYTTSP_OPERATIONAL) &&
(CYTTSP_DIFF(ts->platform_data->act_intrvl, CYTTSP_ACT_INTRVL_DFLT) ||
CYTTSP_DIFF(ts->platform_data->tch_tmout, CYTTSP_TCH_TMOUT_DFLT) ||
CYTTSP_DIFF(ts->platform_data->lp_intrvl, CYTTSP_LP_INTRVL_DFLT))) {
if (!(retval < CYTTSP_OPERATIONAL)) {
u8 intrvl_ray[sizeof(ts->platform_data->act_intrvl) +
sizeof(ts->platform_data->tch_tmout) +
sizeof(ts->platform_data->lp_intrvl)];
u8 i = 0;
intrvl_ray[i++] = ts->platform_data->act_intrvl;
intrvl_ray[i++] = ts->platform_data->tch_tmout;
intrvl_ray[i++] = ts->platform_data->lp_intrvl;
cyttsp_debug("SI2: platinfo act_intrvl=0x%02X tch_tmout=0x%02X lp_intrvl=0x%02X\n", \
ts->platform_data->act_intrvl, ts->platform_data->tch_tmout, \
ts->platform_data->lp_intrvl);
// set intrvl registers
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_ACT_INTRVL,
sizeof(intrvl_ray), intrvl_ray);
mdelay(CYTTSP_DELAY_SYSINFO);
}
}
}
/* switch back to Operational mode */
cyttsp_debug("switch back to operational mode \n");
if (!(retval < CYTTSP_OPERATIONAL)) {
host_reg = CYTTSP_OPERATE_MODE/* + CYTTSP_LOW_POWER_MODE*/;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
}
}
/* init gesture setup;
* this is required even if not using gestures
* in order to set the active distance */
if (!(retval < CYTTSP_OPERATIONAL)) {
u8 gesture_setup;
cyttsp_debug("init gesture setup \n");
gesture_setup = ts->platform_data->gest_set;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET,
sizeof(gesture_setup), &gesture_setup);
mdelay(CYTTSP_DELAY_DFLT);
}
if (!(retval < CYTTSP_OPERATIONAL)) {
ts->platform_data->power_state = CYTTSP_ACTIVE_STATE;
}
else {
ts->platform_data->power_state = CYTTSP_IDLE_STATE;
}
cyttsp_debug("Retval=%d Power state is %s\n", retval, (ts->platform_data->power_state == CYTTSP_ACTIVE_STATE) ? "ACTIVE" : "IDLE");
return retval;
}
#endif
/* cyttsp_initialize: Driver Initialization. This function takes
* care of the following tasks:
* 1. Create and register an input device with input layer
* 2. Take CYTTSP device out of bootloader mode; go operational
* 3. Start any timers/Work queues. */
static int cyttsp_initialize(struct i2c_client *client, struct cyttsp *ts)
{
struct input_dev *input_device;
int error = 0;
int retval = CYTTSP_OPERATIONAL;
u8 id;
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
cyttsp_data = ts;
#endif
/* Create the input device and register it. */
input_device = input_allocate_device();
if (!input_device) {
error = -ENOMEM;
cyttsp_xdebug1("err input allocate device\n");
goto error_free_device;
}
if (!client) {
error = ~ENODEV;
cyttsp_xdebug1("err client is Null\n");
goto error_free_device;
}
if (!ts) {
error = ~ENODEV;
cyttsp_xdebug1("err context is Null\n");
goto error_free_device;
}
ts->input = input_device;
input_device->name = CYTTSP_I2C_NAME;
input_device->phys = ts->phys;
input_device->dev.parent = &client->dev;
set_bit(EV_SYN, input_device->evbit);
set_bit(EV_KEY, input_device->evbit);
set_bit(EV_ABS, input_device->evbit);
set_bit(BTN_TOUCH, input_device->keybit);
//set_bit(BTN_2, input_device->keybit); // N1037 20120321 fix
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
set_bit(KEY_MENU, input_device->keybit);
set_bit(KEY_BACK, input_device->keybit);
set_bit(KEY_POWER, input_device->keybit);
set_bit(KEY_HOMEPAGE, input_device->keybit);
// ---
set_bit(KEY_SEARCH, input_device->keybit);
set_bit(KEY_0, input_device->keybit);
set_bit(KEY_1, input_device->keybit);
set_bit(KEY_2, input_device->keybit);
set_bit(KEY_3, input_device->keybit);
set_bit(KEY_4, input_device->keybit);
set_bit(KEY_5, input_device->keybit);
set_bit(KEY_6, input_device->keybit);
set_bit(KEY_7, input_device->keybit);
set_bit(KEY_8, input_device->keybit);
set_bit(KEY_9, input_device->keybit);
set_bit(0xe3, input_device->keybit); /* '*' */
set_bit(0xe4, input_device->keybit); /* '#' */
set_bit(KEY_LEFTSHIFT, input_device->keybit);
set_bit(KEY_RIGHTSHIFT, input_device->keybit);
set_bit(KEY_LEFT, input_device->keybit);
set_bit(KEY_RIGHT, input_device->keybit);
set_bit(KEY_UP, input_device->keybit);
set_bit(KEY_DOWN, input_device->keybit);
set_bit(KEY_ENTER, input_device->keybit);
set_bit(KEY_SEND, input_device->keybit);
set_bit(KEY_END, input_device->keybit);
set_bit(KEY_VOLUMEUP, input_device->keybit);
set_bit(KEY_VOLUMEDOWN, input_device->keybit);
set_bit(KEY_CLEAR, input_device->keybit);
set_bit(KEY_CAMERA, input_device->keybit);
set_bit(KEY_DELETE, input_device->keybit);
set_bit(KEY_WWW, input_device->keybit);
#endif // FEATURE_SKY_PROCESS_CMD_KEY
// for ICS version - 0511 KJHW
/* clear current touch tracking structures */
memset(cur_trk, 0, sizeof(cur_trk));
for (id = 0; id < TOUCH_MAX_NUM; id++)
{
cur_trk[id].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[id] = 0;
}
input_mt_init_slots(input_device, TOUCH_MAX_NUM);
if (ts->platform_data->use_gestures) {
set_bit(BTN_3, input_device->keybit);
}
input_set_abs_params(input_device, ABS_X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_Y, 0, ts->platform_data->maxy, 0, 0);
input_set_abs_params(input_device, ABS_TOOL_WIDTH, 0, CYTTSP_LARGE_TOOL_WIDTH, 0 ,0);
input_set_abs_params(input_device, ABS_PRESSURE, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_HAT0X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_HAT0Y, 0, ts->platform_data->maxy, 0, 0);
if (ts->platform_data->use_gestures) {
input_set_abs_params(input_device, ABS_HAT1X, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_HAT1Y, 0, CYTTSP_MAXZ, 0, 0);
}
if (ts->platform_data->use_mt) {
input_set_abs_params(input_device, ABS_MT_POSITION_X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_MT_POSITION_Y, 0, ts->platform_data->maxy, 0, 0);
input_set_abs_params(input_device, ABS_MT_TOUCH_MAJOR, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_MT_WIDTH_MAJOR, 0, CYTTSP_LARGE_TOOL_WIDTH, 0, 0);
if (ts->platform_data->use_trk_id) {
input_set_abs_params(input_device, ABS_MT_TRACKING_ID, 0, CYTTSP_NUM_TRACK_ID, 0, 0);
}
}
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
input_set_abs_params(input_device, ABS_MT_TOOL_TYPE, 0, 1, 0, 0);
// ---
cyttsp_info("%s: Register input device\n", CYTTSP_I2C_NAME);
error = input_register_device(input_device);
if (error) {
cyttsp_alert("%s: Failed to register input device\n", CYTTSP_I2C_NAME);
retval = error;
goto error_free_device;
}
else
cyttsp_info("%s: Register input device success...\n", CYTTSP_I2C_NAME);
/* Prepare our worker structure prior to setting up the timer/ISR */
INIT_WORK(&ts->work,cyttsp_xy_worker);
#ifdef FEATURE_CYTTSP_HEARTBEAT
INIT_WORK(&ts->work2,cyttsp_check_heartbeat);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
//INIT_WORK(&ts->work3,check_firmware_update); // N1037 20120312 for ICS
INIT_DELAYED_WORK(&ts->work3,check_firmware_update);
#endif
/* Power on the chip and make sure that I/Os are set as specified
* in the platform
*/
#if 0 //Cypress ¾÷ü ¿äû»çÇ×.
retval = cyttsp_power_on(ts);
if (retval < 0) {
goto error_free_device;
}
#endif
/* Timer or Interrupt setup */
if(ts->client->irq == 0) {
cyttsp_info("Setting up timer\n");
setup_timer(&ts->timer, cyttsp_timer, (unsigned long) ts);
mod_timer(&ts->timer, jiffies + TOUCHSCREEN_TIMEOUT);
}
else {
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
setup_timer(&ts->timer, cyttsp_timer, (unsigned long) ts);
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * 20 * HZ); //óÀ½ ½ÃÀÛÀº 60ÃÊ µÚ¿¡ ŸÀÌ¸Ó µ¹°Ô ÇÔ ºÎÆÃ½Ã°£¿¡ ¿µÇâÀ» ÁÖÁö ¾Ê±â À§ÇÔ.
#endif
cyttsp_info("Setting up interrupt\n");
/* request_irq() will also call enable_irq() */
error = request_irq (client->irq,cyttsp_irq,IRQF_TRIGGER_FALLING,
client->dev.driver->name,ts);
if (error) {
cyttsp_alert("error: could not request irq\n");
retval = error;
goto error_free_irq;
}
}
atomic_set(&ts->irq_enabled, 1);
retval = device_create_file(&ts->client->dev, &dev_attr_irq_enable);
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_alert("File device creation failed: %d\n", retval);
retval = -ENODEV;
goto error_free_irq;
}
cyttsp_info("%s: Successful registration\n", CYTTSP_I2C_NAME);
goto success;
error_free_irq:
cyttsp_alert("Error: Failed to register IRQ handler\n");
free_irq(client->irq,ts);
error_free_device:
if (input_device) {
input_free_device(input_device);
}
success:
return retval;
}
static int pantech_auto_check(u8* return_byte)
{
u8 host_reg, byte_data[4], prev_data=0xff, byte_node1[MAX_NODE], byte_node2[MAX_NODE], send_byte[MAX_NODE];
int retval = CYTTSP_OPERATIONAL, retry_cnt = 100, i;
struct cyttsp *ts = ts_temp;
dbg("pantech_auto_check!! start\n");
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return -1;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
// Enter Test Mode
host_reg = CYTTSP_TEST_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
// Read Raw counts or baseline
byte_data[0] = 0x00;
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_MODE , sizeof(byte_data), (u8 *)&byte_data);
msleep(10);
}
while (byte_data[0] == prev_data && --retry_cnt);
prev_data = byte_data[0];
do {
/* Read Count
Must set a i2c.h I2C_SMBUS_BLOCK_MAX 32 -> I2C_SMBUS_BLOCK_MAX 256
*/
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SENSOR_BASE , sizeof(byte_node1), (u8 *)&byte_node1);
msleep(10);
}
while (retval < CYTTSP_OPERATIONAL && --retry_cnt);
// Read Raw counts or baseline
host_reg = CYTTSP_T_TEST_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
byte_data[0] = 0x00;
retry_cnt = 100;
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_MODE , sizeof(byte_data), (u8 *)&byte_data);
msleep(10);
}
while (byte_data[0] == prev_data && --retry_cnt);
prev_data = byte_data[0];
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SENSOR_BASE , sizeof(byte_node2), (u8 *)&byte_node2);
msleep(10);
}
while (retval < CYTTSP_OPERATIONAL && --retry_cnt);
for(i=0; i<MAX_NODE; i++)
{
if(byte_node1[i] >= CYTTSP_BASE_MIN && byte_node1[i] <= CYTTSP_BASE_MAX &&
byte_node2[i] >= CYTTSP_BASE_MIN && byte_node2[i] <= CYTTSP_BASE_MAX)
send_byte[i] = 0;
else
send_byte[i] = 1;
// printk("Check Valid %d, byte_node1 %d, byte_node2 %d : %d\n", i , byte_node1[i], byte_node2[i], send_byte[i]);
}
// Retrun Operate Mode
host_reg = CYTTSP_OPERATE_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
msleep(100);
dbg("pantech_auto_check!! end\n");
for(i=0;i<MAX_NODE;i++)
return_byte[i]=send_byte[i];
return 0;
}
static int pantech_selftest_check(void)
{
u8 host_reg, byte_data[2];
int retval = CYTTSP_OPERATIONAL;
struct cyttsp *ts = ts_temp;
printk("pantech_selftest_check!! start\n");
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return -1;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
// Enter system information Mode
host_reg = CYTTSP_SYSINFO_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
// Start self test
host_reg = 0x01;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_SELF_TEST, sizeof(host_reg), &host_reg);
msleep(1000);
// Read test result
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SELF_TEST , sizeof(byte_data), (u8 *)&byte_data);
printk("0x18 test: %02x, 0x19 test: %02x\n", byte_data[0], byte_data[1]);
// Retrun Operate Mode
host_reg = CYTTSP_OPERATE_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
msleep(100);
printk("pantech_selftest_check!! end\n");
if(byte_data[0] != 0)
return CYTTSP_BIST_PROCESS;
else if(byte_data[1] != 0xff)
{
if(!(byte_data[1] & 0x01))
return CYTTSP_OPEN_TEST;
else if(!(byte_data[1] & 0x02))
return CYTTSP_SHORT_GND;
else if(!(byte_data[1] & 0x04))
return CYTTSP_SHORT_VDD;
else if(!(byte_data[1] & 0x08))
return CYTTSP_SHORT_PIN;
else if(!(byte_data[1] & 0x10))
return CYTTSP_LOCAL_IDAC;
else if(!(byte_data[1] & 0x20))
return CYTTSP_GLOBAL_IDAC;
else if(!(byte_data[1] & 0x40))
return CYTTSP_BASELINE_TEST;
else if(!(byte_data[1] & 0x80))
return CYTTSP_COMPLETE_BIT;
}
else
return 0;
return 0;
}
static void init_hw_setting(void)
{
int rc;
struct regulator *vreg_touch, *vreg_power_1_8;
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_CHG, 0);
// Power On, AVDD
vreg_touch = regulator_get(NULL, "8058_l19");
if (IS_ERR(vreg_touch))
{
rc = PTR_ERR(vreg_touch);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_touch, rc);
}
rc = regulator_set_voltage(vreg_touch, 3000000, 3000000);
if (rc) {
printk(KERN_ERR "%s: vreg set level failed (%d)\n", __func__, rc);
return;
}
rc = regulator_enable(vreg_touch);
if (rc) {
printk(KERN_ERR "%s: vreg enable failed (%d)\n",__func__, rc);
return;
}
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_power_1_8 = regulator_get(NULL, "8058_l11");
if (IS_ERR(vreg_power_1_8))
{
rc = PTR_ERR(vreg_power_1_8);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_power_1_8, rc);
}
rc = regulator_set_voltage(vreg_power_1_8, 1900000, 1900000);
if (rc) {
printk(KERN_ERR "%s: vreg set level failed (%d)\n", __func__, rc);
return;
}
rc = regulator_enable(vreg_power_1_8);
if (rc) {
printk(KERN_ERR "%s: vreg enable failed (%d)\n",__func__, rc);
return;
}
#else
// Power On DVDD
vreg_power_1_8 = regulator_get(NULL, "8058_lvs0");
if (IS_ERR(vreg_power_1_8))
{
rc = PTR_ERR(vreg_power_1_8);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_power_1_8, rc);
}
rc = regulator_enable(vreg_power_1_8);
#endif
gpio_set_value(GPIO_TOUCH_CHG, 1);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_ID, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_ID, 0);
regulator_put(vreg_touch);
regulator_put(vreg_power_1_8);
msleep(100);
Touch_Status = TOUCH_POWERON;
}
/* I2C driver probe function */
static int __devinit cyttsp_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct cyttsp *ts;
int error;
int retval = CYTTSP_OPERATIONAL;
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
int rc;
#endif
cyttsp_info("Start Probe\n");
/* allocate and clear memory */
ts = kzalloc (sizeof(struct cyttsp),GFP_KERNEL);
if (ts == NULL) {
cyttsp_xdebug1("err kzalloc for cyttsp\n");
retval = -ENOMEM;
}
init_hw_setting();
if (!(retval < CYTTSP_OPERATIONAL)) {
/* register driver_data */
ts->client = client;
ts->platform_data = client->dev.platform_data;
i2c_set_clientdata(client,ts);
ts->client->irq = IRQ_TOUCH_INT;
error = cyttsp_initialize(client, ts);
if (error) {
cyttsp_xdebug1("err cyttsp_initialize\n");
if (ts != NULL) {
/* deallocate memory */
kfree(ts);
}
/*
i2c_del_driver(&cyttsp_driver);
*/
retval = -ENODEV;
}
else {
cyttsp_openlog();
}
}
#ifdef CONFIG_HAS_EARLYSUSPEND
if (!(retval < CYTTSP_OPERATIONAL)) {
ts->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1;
ts->early_suspend.suspend = cyttsp_early_suspend;
ts->early_suspend.resume = cyttsp_late_resume;
register_early_suspend(&ts->early_suspend);
}
#endif /* CONFIG_HAS_EARLYSUSPEND */
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
rc = misc_register(&touch_event);
if (rc) {
pr_err("::::::::: can''t register touch_fops\n");
}
#endif
cyttsp_info("Start Probe %s\n", (retval < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS");
ts_temp = ts;
#ifdef CYTTSP_MUTEX_LOCK
mutex_init(&ts->lock_mutex);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
#if defined(CONFIG_APACHE_BOARD)
schedule_work(&ts->work3);
// INIT_DELAYED_WORK(&work_delay_firmware,check_firmware_update);
// schedule_delayed_work(&work_delay_firmware, msecs_to_jiffies(30000));
#elif defined(CONFIG_EF33_BOARD) || defined(CONFIG_EF34_BOARD)
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
//schedule_work(&ts->work3); // N1037 20120312 for ICS
schedule_delayed_work(&ts->work3, msecs_to_jiffies(3000));
#endif
#else
schedule_work(&ts->work3);
#endif
#endif
wake_lock_init(&touch_wake_lock, WAKE_LOCK_SUSPEND, "touch");
return retval;
}
/* Function to manage power-on resume */
static int cyttsp_resume(struct i2c_client *client)
{
struct cyttsp *ts;
int ret=0;
int retval = CYTTSP_OPERATIONAL;
dbg("Wake Up\n");
ts = (struct cyttsp *) i2c_get_clientdata(client);
if(ts == NULL)
return retval;
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA, 0);
Touch_Status = TOUCH_POWERON;
// for ICS version - 0511 KJHW
input_mt_init_slots(ts->input, TOUCH_MAX_NUM);
msleep(100);
ret = request_irq (client->irq,cyttsp_irq,IRQF_TRIGGER_FALLING, client->dev.driver->name,ts);
#ifdef FEATURE_CYTTSP_HEARTBEAT
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * HZ);
start_heartbeat_timer = true;
#endif
/* re-enable the interrupt after resuming */
// enable_irq(ts->client->irq);
cyttsp_debug("Wake Up %s\n", (retval < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS" );
return retval;
}
/* Function to manage low power suspend */
static int cyttsp_suspend(struct i2c_client *client, pm_message_t message)
{
struct cyttsp *ts;
int retval = CYTTSP_OPERATIONAL, id =0;
dbg("Enter Sleep\n");
ts = (struct cyttsp *) i2c_get_clientdata(client);
if(ts == NULL)
return retval;
/* disable worker */
disable_irq_nosync(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
retval = cancel_work_sync(&ts->work2);
del_timer(&ts->timer);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
// cancel_work_sync(&ts->work3);
#endif
Touch_Status = TOUCH_POWEROFF;
retval = cancel_work_sync(&ts->work);
pantech_ctl_update(ISSP_IOCTL_POWER_ALL, 0);
free_irq(client->irq,ts);
pantech_ctl_update(ISSP_IOCTL_SCLK_TO_GPIO, 1);
pantech_ctl_update(ISSP_IOCTL_DATA_TO_GPIO, 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 0);
pantech_ctl_update(ISSP_IOCTL_SCLK, 0);
pantech_ctl_update(ISSP_IOCTL_DATA, 0);
// for ICS version - 0511 KJHW
for (id = 0; id < TOUCH_MAX_NUM; id++)
{
cur_trk[id].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[id] = 0;
input_mt_slot(ts->input, id);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[id].abs[CY_ABS_ID_OST]);
input_report_key(ts->input, BTN_TOUCH, 0 );
input_sync(ts->input);
}
// for ICS version - 0511 KJHW
input_mt_destroy_slots(ts->input);
return retval;
}
/* registered in driver struct */
static int __devexit cyttsp_remove(struct i2c_client *client)
{
struct cyttsp *ts;
int err;
cyttsp_alert("Unregister\n");
/* clientdata registered on probe */
ts = i2c_get_clientdata(client);
device_remove_file(&ts->client->dev, &dev_attr_irq_enable);
/* Start cleaning up by removing any delayed work and the timer */
if (cancel_delayed_work((struct delayed_work *)&ts->work)<0) {
cyttsp_alert("error: could not remove work from workqueue\n");
}
/* free up timer or irq */
if(ts->client->irq == 0) {
err = del_timer(&ts->timer);
if (err < 0) {
cyttsp_alert("error: failed to delete timer\n");
}
}
else {
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
del_timer(&ts->timer);
#endif
free_irq(client->irq,ts);
}
/* housekeeping */
if (ts != NULL) {
kfree(ts);
}
/* clientdata registered on probe */
cyttsp_alert("Leaving\n");
return 0;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cyttsp_early_suspend(struct early_suspend *handler)
{
struct cyttsp *ts;
ts = container_of(handler, struct cyttsp, early_suspend);
cyttsp_suspend(ts->client, PMSG_SUSPEND);
}
static void cyttsp_late_resume(struct early_suspend *handler)
{
struct cyttsp *ts;
ts = container_of(handler, struct cyttsp, early_suspend);
cyttsp_resume(ts->client);
}
#endif /* CONFIG_HAS_EARLYSUSPEND */
static int cyttsp_init(void)
{
int ret;
cyttsp_info("Cypress TrueTouch(R) Standard Product I2C Touchscreen Driver (Built %s @ %s)\n",__DATE__,__TIME__);
ret = i2c_add_driver(&cyttsp_driver);
return ret;
}
static void cyttsp_exit(void)
{
return i2c_del_driver(&cyttsp_driver);
}
module_init(cyttsp_init);
module_exit(cyttsp_exit);
| cmvega/cmvega | drivers/input/touchscreen/cyttsp-i2c.c | C | gpl-2.0 | 80,215 |
# Again-
Remind me
| Rapidwave72/Again- | README.md | Markdown | gpl-2.0 | 20 |
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
global $DB;
global $USER;
// Require config.php file for database connection // 1
require_once('/home/libecour/public_html/moodle/config.php');
// Get quiz number // 2
$quiz = $_GET['quiz'];
// Create connection - MySQLi (object-oriented) // 3
$conn = new mysqli($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname);
// Check connection - MySQLi (object-oriented) // 4
if ($conn->connect_error) {
die("Connection to the database failed: " . $conn->connect_error . "<br>");
}
// Set character set to UTF8 // 5
mysqli_set_charset($conn,"utf8");
// Check if user is connected // 6
if ($USER->id != 0) {
// Select Statement - MySQLi (object-oriented) // 7
$sql = "SELECT id FROM mdl_pe_learner_profile WHERE userid = $USER->id" ;
$result = $conn->query($sql);
// Get learner profile id // 8
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$learnerprofileid = $row['id'];
}
// free result set // 9
$result->free();
// Select Statement - MySQLi (object-oriented) // 10
$sql = "SELECT abilitylevel FROM mdl_pe_user_ability_levels WHERE learnerprofileid = $learnerprofileid AND libethemeid = 2" ;
$result = $conn->query($sql);
// Get ability level
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$abilitylevel = $row['abilitylevel'];
// free result set // 11
$result->free();
// Insert rows in mdl_pe_ability_level_log table // 12
$sql = "INSERT INTO mdl_pe_ability_level_log (learnerprofileid, libethemeid, quiz, abilitylevel, timelogged) VALUES ($learnerprofileid, 2, $quiz, '$abilitylevel', NULL)";
$conn->query($sql);
}
}
// Close database connection // 13
$conn->close();
| LIBE-VLE/libecour | pe/abilitylevellog.php | PHP | gpl-2.0 | 1,922 |
#!/usr/bin/perl
use strict;
my $head = "download:";
my $output;
open ( RULES, $ARGV[0] ) or die;
while ( <RULES> )
{
chomp;
if ( ! m/^#/ and ! m/^\s*$/ )
{
@_ = split ( /;/, $_ );
my $file = $_[0];
$head .= " \$(archivedir)/" . $file;
$output .= "\$(archivedir)/" . $file . ":\n\tfalse || ";
$output .= "mkdir -p \$(archivedir) && ( \\\n\t";
shift @_;
foreach ( @_ )
{
if ( $_ =~ m#^ftp://# )
{
$output .= "wget -c --passive-ftp --no-check-certificate -P \$(archivedir) " . $_ . "/" . $file . " || \\\n\t";
}
elsif ( $_ =~ m#^(http|https)://# )
{
$output .= "wget -t 2 -T 10 -c --no-check-certificate -P \$(archivedir) " . $_ . "/" . $file . " || \\\n\t";
}
}
$output .= "wget -c --no-check-certificate -P \$(archivedir) http://www.i-have-a-dreambox.com/Archive/" . $file . " )";
$output .= "\n\t\@touch \$\@";
$output .= "\n\n";
}
}
close ( RULES );
print $head . "\n\n" . $output . "\n";
| UkCvs/commando | cdk/rules-archive.pl | Perl | gpl-2.0 | 1,003 |
---
layout: default
title: (#TBD) Method に関する処理 : Java のコードによるメソッド呼び出し処理 (1) : 呼び出し元(caller側)での invoke 処理 : C2 JIT Compiler が生成したコードの場合
---
[Up](no3059lvH.html) [Top](../index.html)
#### (#TBD) Method に関する処理 : Java のコードによるメソッド呼び出し処理 (1) : 呼び出し元(caller側)での invoke 処理 : C2 JIT Compiler が生成したコードの場合
---
#Under Construction
| hsmemo/hsmemo.github.com | articles/nogNTjQjaM.md | Markdown | gpl-2.0 | 516 |
/*
* AudioCore.c: Implements the JNi interface and handles
*
* (C) Copyright 2015 Simon Grätzer
* Email: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*/
#include "de_rwth_aachen_comsys_audiosync_AudioCore.h"
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <signal.h>
#include <assert.h>
#include "audioplayer.h"
#include "AudioStreamSession.h"
#include "SenderSession.h"
#include "ReceiverSession.h"
#include "decoder.h"
#include "jrtplib/rtpsourcedata.h"
#define debugLog(...) __android_log_print(ANDROID_LOG_DEBUG, "AudioCore", __VA_ARGS__)
//#define debugLog(...) printf(__VA_ARGS__)
#ifdef RTP_SUPPORT_THREAD
void thread_exit_handler(int sig) {
debugLog("this signal is %d \n", sig);
pthread_exit(0);
}
#endif
// Global audiostream manager
AudioStreamSession *audioSession;
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_initAudio(JNIEnv *env, jobject thiz,
jint samplesPerSec,
jint framesPerBuffer) {
audioplayer_initGlobal((uint32_t) samplesPerSec, (uint32_t) framesPerBuffer);
#ifdef RTP_SUPPORT_THREAD
// Workaround to kill threads since pthread_cancel is not supported
// See jthread.cpp
struct sigaction actions;
memset(&actions, 0, sizeof(actions));
sigemptyset(&actions.sa_mask);
actions.sa_flags = 0;
actions.sa_handler = thread_exit_handler;
sigaction(SIGUSR1, &actions, NULL);
#endif
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_deinitAudio(JNIEnv *env, jobject thiz) {
if (audioSession) audioSession->Stop();
if (audioSession) delete audioSession;
audioplayer_cleanup();
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startStreamingAsset (JNIEnv *env, jobject thiz,
jint portbase,
jobject assetManager,
jstring jPath) {
AAssetManager *mgr = AAssetManager_fromJava(env, assetManager);
const char *path = env->GetStringUTFChars(jPath, 0);
// Open the asset from the assets/ folder
AAsset *asset = AAssetManager_open(mgr, path, AASSET_MODE_UNKNOWN);
env->ReleaseStringUTFChars(jPath, path);
if (NULL == asset) {
debugLog("_ASSET_NOT_FOUND_");
return;
}
off_t outStart, fileSize;
int fd = AAsset_openFileDescriptor(asset, &outStart, &fileSize);
assert(0 <= fd);
debugLog("Audio file offset: %ld, size: %ld", outStart, fileSize);
AMediaExtractor *extr = decoder_createExtractorFromFd(fd, outStart, fileSize);
audioSession = SenderSession::StartStreaming((uint16_t) portbase, extr);
AAsset_close(asset);
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startStreamingUri
(JNIEnv *env, jobject thiz, jint portbase, jstring jPath) {
const char *path = env->GetStringUTFChars(jPath, 0);
AMediaExtractor *extr = decoder_createExtractorFromUri(path);
env->ReleaseStringUTFChars(jPath, path);
audioSession = SenderSession::StartStreaming((uint16_t) portbase, extr);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: startReceiving
* Signature: (Ljava/lang/String;I)V
*/
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startReceiving(JNIEnv *env, jobject thiz,
jstring jHost, jint portbase) {
const char *host = env->GetStringUTFChars(jHost, 0);
audioSession = ReceiverSession::StartReceiving(host, (uint16_t) portbase);
env->ReleaseStringUTFChars(jHost, host);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: stop
* Signature: ()V
*/
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_stopServices(JNIEnv *env, jobject thiz) {
if (audioSession) audioSession->Stop();
audioplayer_stopPlayback();
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_setDeviceLatency(JNIEnv *env, jobject thiz, jlong latencyMs) {
if (latencyMs >= 0)
audioplayer_setDeviceLatency((int64_t)latencyMs * 1000);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: getRtpSourceCount
* Signature: ()I
*/
jobjectArray Java_de_rwth_1aachen_comsys_audiosync_AudioCore_getAudioDestinations
(JNIEnv *env, jobject thiz) {
if (audioSession == NULL) return NULL;
int i = 0;
if (audioSession->GotoFirstSource())
do {
jrtplib::RTPSourceData *source = audioSession->GetCurrentSourceInfo();
if (source == nullptr || source->IsOwnSSRC()) continue;
i++;
} while (audioSession->GotoNextSource());
if (i == 0) return NULL;
jclass clzz = env->FindClass("de/rwth_aachen/comsys/audiosync/AudioDestination");
jmethodID init = env->GetMethodID(clzz, "<init>", "()V");
jfieldID nameID = env->GetFieldID(clzz, "name", "Ljava/lang/String;");
jfieldID jitterID = env->GetFieldID(clzz, "jitter", "I");
jfieldID timeOffsetID = env->GetFieldID(clzz, "timeOffset", "I");
jfieldID packetsLostID = env->GetFieldID(clzz, "packetsLost", "I");
jobjectArray ret = env->NewObjectArray(i, clzz, NULL);
i = 0;
if (audioSession->GotoFirstSource()) {
do {
jrtplib::RTPSourceData *source = audioSession->GetCurrentSourceInfo();
if (source != nullptr && !source->IsOwnSSRC()) {
jrtplib::RTPSourceData *sourceData = audioSession->GetCurrentSourceInfo();
size_t nameLen = 0;
uint8_t *nameChars = sourceData->SDES_GetName(&nameLen);
char chars[256] = {0};
memcpy(chars, nameChars, nameLen);
jobject dest = env->NewObject(clzz, init);
env->SetObjectField(dest, nameID, env->NewStringUTF(chars));
env->SetIntField(dest, jitterID, (jint) sourceData->INF_GetJitter());
env->SetIntField(dest, timeOffsetID, (jint)sourceData->GetClockOffsetUSeconds());
env->SetIntField(dest, packetsLostID, (jint) sourceData->RR_GetPacketsLost());
env->SetObjectArrayElement(ret, i, dest);
i++;
}
} while (audioSession->GotoNextSource());
}
return ret;
}
/*
* Return current presentation time in milliseconds
*/
jlong Java_de_rwth_1aachen_comsys_audiosync_AudioCore_getCurrentPresentationTime
(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsRunning())
return (jlong)(audioSession->CurrentPlaybackTimeUs() / 1000);
return -1;
}
jboolean Java_de_rwth_1aachen_comsys_audiosync_AudioCore_isRunning (JNIEnv *, jobject) {
bool a = audioSession != NULL && audioSession->IsRunning();
return (jboolean) (a ? JNI_TRUE : JNI_FALSE);
}
jboolean Java_de_rwth_1aachen_comsys_audiosync_AudioCore_isSending(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsSender()) {
return (jboolean) (audioSession->IsRunning());
}
return JNI_FALSE;
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_pauseSending
(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsSender()) {
SenderSession *sender = (SenderSession *)audioSession;
// TODO
}
}
| graetzer/AudioSync | app/src/main/jni/AudioCore.cpp | C++ | gpl-2.0 | 7,611 |
<?php
/**
* This file is for debugging and app development purposes only.
* Should not be used for front-end features.
* Possible purposes are:
* -- you want to test the functionality of the methods you created from another registered class.
* -- or you may want to test the effective of such algorithms.
*
*/
# Begin coding below
?> | thesisteam/dbms | page/debug.php | PHP | gpl-2.0 | 354 |
package cz.vutbr.fit.xfekia00;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
/**
* jedno vykonanie skriptu sa uklada ako polozka historie
* @author Filip Fekiac
*/
public class HistoryItem {
private final String usedDatabase; // pouzity databazovy system
private final LinkedList<String[][]> resultList; // vysledky dopytov
private final LinkedList<String[]> resultHeader; // hlavicky dopytov
private final LinkedList<String> resultCaption; // jednotlive dopyty
private final Calendar date;
public HistoryItem(String _usedDB) {
usedDatabase = _usedDB;
resultList = new LinkedList<>();
resultHeader = new LinkedList<>();
resultCaption = new LinkedList<>();
date = Calendar.getInstance();
}
public void addResultItem(int pos, String[][] _item) {
resultList.add(pos, _item);
}
public void addHeaderItem(int pos, String[] _item) {
resultHeader.add(pos, _item);
}
public void addCaptionItem(int pos, String _item) {
resultCaption.add(pos, _item);
}
public String getUsedDatabase() {
return usedDatabase;
}
public LinkedList<String[][]> getResultList() {
return resultList;
}
public LinkedList<String[]> getResultHeader() {
return resultHeader;
}
public LinkedList<String> getResultCaption() {
return resultCaption;
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
return format.format(date.getTime()) + " " + usedDatabase;
}
}
| waresko18/TempJDBC | src-gui/src/cz/vutbr/fit/xfekia00/HistoryItem.java | Java | gpl-2.0 | 1,674 |
<html>
<head>
<title>
WARNING: at arch/x86/kernel/cpu/perf_event_intel.c:1373 perfevents: irq loop stuck!
</title>
</head>
<body>
<center>
<h1>
WARNING: at arch/x86/kernel/cpu/perf_event_intel.c:1373 perfevents: irq loop stuck!
</h1>
</center>
<h3>Severity</h3>
Just a warning, although it does cause a long pause while
the interrupt is stuck on.
<h3>Found by</h3>
perf_fuzzer
<h3>First Seen</h3>
3.15-rc1
<h3>Most recently Seen</h3>
4.8-rc1
<h3>Reproducible</h3>
yes
<h3>Found On</h3>
Haswell
<h3>Linux-kernel Mailing List Report</h3>
13 May 2014 --
<a href="https://lkml.org/lkml/2014/5/13/906">perfevents: irq loop stuck!</a>
<h3>Analysis</h3>
There are two problems. The first was the 63-bit overflow issue
detailed below which makes triggering the problem easier.
The other is the overflow interrupt getting stuck on when
the fixed-counter-0 sample_period is 2.<br><br>
<h3>Kernel Splat</h3>
<ol>
<li>
<pre>
*** perf_fuzzer 0.30-pre *** by Vince Weaver
Linux version 4.0.0+ x86_64
Processor: Intel 6/60/3
Seeding random number generator with 1429913766
/proc/sys/kernel/perf_event_max_sample_rate currently: 100000/s
/proc/sys/kernel/perf_event_paranoid currently: 0
Logging perf_event_open() failures: no
Running fsync after every syscall: no
To reproduce, try: ./perf_fuzzer -s 30000 -r 1429913766
Pid=26448, sleeping 1s
==================================================
Fuzzing the following syscalls:
mmap perf_event_open close read write ioctl fork prctl poll
*NOT* Fuzzing the following syscalls:
Also attempting the following:
signal-handler-on-overflow busy-instruction-loop accessing-perf-proc-and-sys-files trashing-the-mmap-page
*NOT* attempting the following:
==================================================
Iteration 10000
Open attempts: 127761 Successful: 907 Currently open: 595
EPERM : 13
ENOENT : 638
E2BIG : 12148
EBADF : 7160
UNKNOWN 16 : 1
EINVAL : 106556
ENOSPC : 9
EOPNOTSUPP : 329
Type (Hardware 216/16984)(software 320/18429)(tracepoint 68/18304)(Cache 57/16130)(cpu 172/18053)(breakpoint 23/18313)(power 0/2258)(intel_bts 51/2332)(uncore_imc 0/2316)(#9 0/18)(#10 0/18)(#11 0/12)(#12 0/24)(#13 0/18)(#14 0/14)(>14 0/14538)
Close attempts: 312 Successful: 312
Read attempts: 894 Successful: 786
Write attempts: 871 Successful: 0
Ioctl attempts: 914 Successful: 411
Mmap attempts: 907 Successful: 102
Prctl attempts: 900 Successful: 900
Fork attempts: 446 Successful: 446
Poll attempts: 883 Successful: 865
Access attempts: 939 Successful: 466
Trash mmap attempts: 900 Successful: 900
Overflows: 0
SIGIOs due to RT signal queue full: 0
[ 8224.179407] ------------[ cut here ]------------
[ 8224.184368] WARNING: CPU: 0 PID: 0 at arch/x86/kernel/cpu/perf_event_intel.c:1602 intel_pmu_handle_irq+0x2bc/0x450()
[ 8224.195686] perfevents: irq loop stuck!
[ 8224.199835] Modules linked in: fuse x86_pkg_temp_thermal intel_powerclamp intel_rapl iosf_mbi coretemp kvm crct10dif_pclmul snd_hda_codec_hdmi crc32_pclmul ghash_clmulni_intel snd_hda_codec_realtek aesni_intel snd_hda_codec_generic aes_x86_64 i915 snd_hda_intel snd_hda_controller snd_hda_codec snd_hda_core snd_hwdep lrw snd_pcm gf128mul iTCO_wdt iTCO_vendor_support drm_kms_helper glue_helper snd_timer ppdev evdev drm ablk_helper snd cryptd mei_me soundcore xhci_pci tpm_tis psmouse xhci_hcd mei serio_raw lpc_ich tpm mfd_core parport_pc pcspkr parport wmi i2c_algo_bit battery i2c_i801 button processor video sg sr_mod sd_mod cdrom ahci libahci libata ehci_pci ehci_hcd e1000e usbcore ptp crc32c_intel fan scsi_mod pps_core usb_common thermal thermal_sys
[ 8224.273188] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G W 4.0.0+ #136
[ 8224.281012] Hardware name: LENOVO 10AM000AUS/SHARKBAY, BIOS FBKT72AUS 01/26/2014
[ 8224.288988] ffffffff81a093a8 ffff88011ea05b50 ffffffff816d5639 0000000000000000
[ 8224.297058] ffff88011ea05ba0 ffff88011ea05b90 ffffffff81072e4a ffff880119b87090
[ 8224.306453] 0000000000000064 ffff88011ea0bd80 ffff8800c38c7800 0000000000000040
[ 8224.315894] Call Trace:
[ 8224.319886] <NMI> [<ffffffff816d5639>] dump_stack+0x45/0x57
[ 8224.327439] [<ffffffff81072e4a>] warn_slowpath_common+0x8a/0xc0
[ 8224.335238] [<ffffffff81072ec6>] warn_slowpath_fmt+0x46/0x50
[ 8224.342812] [<ffffffff8103399c>] intel_pmu_handle_irq+0x2bc/0x450
[ 8224.350830] [<ffffffff81164215>] ? perf_event_task_tick+0x1d5/0x2b0
[ 8224.359025] [<ffffffff8102a40b>] perf_event_nmi_handler+0x2b/0x50
[ 8224.367069] [<ffffffff810185c0>] nmi_handle+0xa0/0x150
[ 8224.374067] [<ffffffff81018525>] ? nmi_handle+0x5/0x150
[ 8224.381169] [<ffffffff8101886a>] default_do_nmi+0x4a/0x140
[ 8224.388487] [<ffffffff810189f8>] do_nmi+0x98/0xe0
[ 8224.394886] [<ffffffff816df8af>] end_repeat_nmi+0x1e/0x2e
[ 8224.402082] [<ffffffff8105bffa>] ? native_write_msr_safe+0xa/0x10
[ 8224.409958] [<ffffffff8105bffa>] ? native_write_msr_safe+0xa/0x10
[ 8224.417785] [<ffffffff8105bffa>] ? native_write_msr_safe+0xa/0x10
[ 8224.425536] <<EOE>> <IRQ> [<ffffffff8103356e>] intel_pmu_enable_event+0x20e/0x230
[ 8224.435001] [<ffffffff8102b721>] x86_pmu_start+0x81/0x120
[ 8224.442007] [<ffffffff8102bf25>] x86_pmu_enable+0x295/0x310
[ 8224.449150] [<ffffffff811621aa>] perf_pmu_enable+0x2a/0x30
[ 8224.456173] [<ffffffff81029fe8>] x86_pmu_commit_txn+0x78/0xa0
[ 8224.456173] [<ffffffff81029fe8>] x86_pmu_commit_txn+0x78/0xa0
[ 8224.463561] [<ffffffff81427f6b>] ? debug_object_activate+0x14b/0x1e0
[ 8224.471591] [<ffffffff810bdde9>] ? __lock_acquire.isra.31+0x3b9/0x1000
[ 8224.479715] [<ffffffff81427f6b>] ? debug_object_activate+0x14b/0x1e0
[ 8224.487676] [<ffffffff810bcba4>] ? __lock_is_held+0x54/0x80
[ 8224.494794] [<ffffffff81162d50>] ? event_sched_in.isra.85+0x190/0x330
[ 8224.502894] [<ffffffff811630a8>] group_sched_in+0x1b8/0x1e0
[ 8224.510082] [<ffffffff8101df1a>] ? native_sched_clock+0x2a/0x90
[ 8224.517646] [<ffffffff811637bc>] __perf_event_enable+0x25c/0x2a0
[ 8224.525297] [<ffffffff810f3e69>] ? tick_nohz_irq_exit+0x29/0x30
[ 8224.532776] [<ffffffff8115ef30>] ? cpu_clock_event_start+0x40/0x40
[ 8224.540595] [<ffffffff8115ef80>] remote_function+0x50/0x60
[ 8224.547668] [<ffffffff810f8cd1>] flush_smp_call_function_queue+0x81/0x180
[ 8224.556126] [<ffffffff810f9763>] generic_smp_call_function_single_interrupt+0x13/0x60
[ 8224.565749] [<ffffffff8104b5c8>] smp_trace_call_function_single_interrupt+0x38/0xc0
[ 8224.575132] [<ffffffff816de9be>] trace_call_function_single_interrupt+0x6e/0x80
[ 8224.584168] <EOI> [<ffffffff8156e8b5>] ? cpuidle_enter_state+0x65/0x160
[ 8224.592646] [<ffffffff8156e8a1>] ? cpuidle_enter_state+0x51/0x160
[ 8224.600408] [<ffffffff8156e9e7>] cpuidle_enter+0x17/0x20
[ 8224.607285] [<ffffffff810b6e39>] cpu_startup_entry+0x399/0x440
[ 8224.614712] [<ffffffff816c9ddb>] rest_init+0xbb/0xd0
[ 8224.621283] [<ffffffff81d46f74>] start_kernel+0x44e/0x45b
[ 8224.628212] [<ffffffff81d46120>] ? early_idt_handlers+0x120/0x120
[ 8224.635980] [<ffffffff81d464d7>] x86_64_start_reservations+0x2a/0x2c
[ 8224.643999] [<ffffffff81d46614>] x86_64_start_kernel+0x13b/0x14a
[ 8224.651691] ---[ end trace 5679ca0875946dba ]---
[ 8224.657764]
[ 8224.660447] CPU#0: ctrl: 0000000000000000
[ 8224.666448] CPU#0: status: 0000000000000000
[ 8224.672414] CPU#0: overflow: 0000000000000000
[ 8224.678373] CPU#0: fixed: 00000000000000b9
[ 8224.684338] CPU#0: pebs: 0000000000000000
[ 8224.690322] CPU#0: debugctl: 0000000000000000
[ 8224.696253] CPU#0: active: 0000000300000000
[ 8224.702232] CPU#0: gen-PMC0 ctrl: 00000000108001c2
[ 8224.708823] CPU#0: gen-PMC0 count: 0000000000000001
[ 8224.715371] CPU#0: gen-PMC0 left: 0000ffffffffffff
[ 8224.721914] CPU#0: gen-PMC1 ctrl: 00000000001382d0
[ 8224.728402] CPU#0: gen-PMC1 count: 0000000000ff3792
[ 8224.734849] CPU#0: gen-PMC1 left: 0000ffffff012119
[ 8224.741271] CPU#0: gen-PMC2 ctrl: 00000003ff96764b
[ 8224.747600] CPU#0: gen-PMC2 count: 0000000000000001
[ 8224.753884] CPU#0: gen-PMC2 left: 0000ffffffffffff
[ 8224.760100] CPU#0: gen-PMC3 ctrl: 0000000000131acd
[ 8224.766320] CPU#0: gen-PMC3 count: 000000000000288a
[ 8224.772585] CPU#0: gen-PMC3 left: 0000ffffffffffff
[ 8224.778769] CPU#0: fixed-PMC0 count: 0000fffffffffffe
[ 8224.784973] CPU#0: fixed-PMC1 count: 0000fffda1877268
[ 8224.791196] CPU#0: fixed-PMC2 count: 0000000000f222eb
[ 8224.797450] perf_event_intel: clearing PMU state on CPU#0
[ 8224.804063] INFO: NMI handler (perf_event_nmi_handler) took too long to run: 624.630 msecs
[ 8224.813789] perf interrupt took too long (4880480 > 2500), lowering kernel.perf_event_max_sample_rate to 50000
[ 8224.825400] perf interrupt took too long (4842512 > 5000), lowering kernel.perf_event_max_sample_rate to 25000
[ 8225.007411] perf interrupt took too long (4804688 > 10000), lowering kernel.perf_event_max_sample_rate to 12500
[ 8225.244832] perf interrupt took too long (4767159 > 20000), lowering kernel.perf_event_max_sample_rate to 6250
[ 8225.295535] perf interrupt took too long (4729923 > 38461), lowering kernel.perf_event_max_sample_rate to 3250
[ 8225.747314] perf interrupt took too long (4692980 > 71428), lowering kernel.perf_event_max_sample_rate to 1750
</pre>
<li>With PeterZ's 63-bit limit patch applied.
<pre>
*** perf_fuzzer 0.29-pre *** by Vince Weaver
Linux version 3.15.0-rc5+ x86_64
Processor: Intel 6/60/3
Seeding random number generator with 1400341222
/proc/sys/kernel/perf_event_max_sample_rate currently: 12500/s
/proc/sys/kernel/perf_event_paranoid currently: 1
Logging perf_event_open() failures: no
Running fsync after every syscall: no
To reproduce, try: ./perf_fuzzer -t OCIRMQWPFpAi -s 50000 -r 1400341222
Pid=9255, sleeping 1s
==================================================
Fuzzing the following syscalls:
mmap perf_event_open close read write ioctl fork prctl poll
*NOT* Fuzzing the following syscalls:
Also attempting the following:
busy-instruction-loop accessing-perf-proc-and-sys-files trashing-the-mmap-page
*NOT* attempting the following:
signal-handler-on-overflow
==================================================
Iteration 10000
Open attempts: 204136 Successful: 889
EPERM : 23
ENOENT : 1782
E2BIG : 23607
EBADF : 10276
EACCES : 983
EINVAL : 165653
ENOSPC : 304
EOPNOTSUPP : 619
Type (Hardware 192/26697)(software 411/30206)(tracepoint 75/29889)(Cache 34/25527)(cpu 151/30007)(breakpoint 26/29908)(uncore_imc 0/4158)(power 0/4179)(#8 0/104)(#9 0/30)(#10 0/24)(#11 0/21)(#12 0/28)(#13 0/24)(#14 0/27)(>14 0/23307)
Close attempts: 855 Successful: 855
Read attempts: 932 Successful: 838
Write attempts: 845 Successful: 0
Ioctl attempts: 875 Successful: 397
Mmap attempts: 889 Successful: 377
Prctl attempts: 891 Successful: 891
Fork attempts: 463 Successful: 463
Poll attempts: 871 Successful: 0
Access attempts: 907 Successful: 461
Trash mmap attempts: 894 Successful: 894
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 20000
Open attempts: 198724 Successful: 946
EPERM : 20
ENOENT : 1780
E2BIG : 22966
EBADF : 9207
EACCES : 973
EINVAL : 161838
ENOSPC : 329
EOPNOTSUPP : 665
Type (Hardware 211/26247)(software 395/29165)(tracepoint 85/28975)(Cache 62/25198)(cpu 178/29118)(breakpoint 15/29305)(uncore_imc 0/4178)(power 0/4140)(#8 0/96)(#9 0/25)(#10 0/27)(#11 0/23)(#12 0/25)(#13 0/22)(#14 0/32)(>14 0/22148)
Close attempts: 910 Successful: 910
Read attempts: 918 Successful: 827
Write attempts: 908 Successful: 0
Ioctl attempts: 907 Successful: 404
Mmap attempts: 946 Successful: 369
Prctl attempts: 866 Successful: 866
Fork attempts: 448 Successful: 448
Poll attempts: 884 Successful: 1
Access attempts: 916 Successful: 485
Trash mmap attempts: 936 Successful: 936
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 30000
Open attempts: 195961 Successful: 886
EPERM : 22
ENOENT : 1790
E2BIG : 22597
EBADF : 9114
EACCES : 994
EINVAL : 159620
ENOSPC : 327
EOPNOTSUPP : 611
Type (Hardware 212/25756)(software 347/29144)(tracepoint 91/28665)(Cache 45/24682)(cpu 172/28491)(breakpoint 19/28515)(uncore_imc 0/4074)(power 0/4151)(#8 0/89)(#9 0/35)(#10 0/29)(#11 0/15)(#12 0/24)(#13 0/26)(#14 0/32)(>14 0/22233)
Close attempts: 933 Successful: 933
Read attempts: 900 Successful: 806
Write attempts: 902 Successful: 0
Ioctl attempts: 925 Successful: 416
Mmap attempts: 886 Successful: 371
Prctl attempts: 884 Successful: 884
Fork attempts: 455 Successful: 455
Poll attempts: 912 Successful: 2
Access attempts: 952 Successful: 474
Trash mmap attempts: 904 Successful: 904
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 40000
Open attempts: 188894 Successful: 919
EPERM : 18
ENOENT : 1756
E2BIG : 22159
EBADF : 8667
EACCES : 944
EINVAL : 153542
ENOSPC : 307
EOPNOTSUPP : 582
Type (Hardware 215/25176)(software 395/27947)(tracepoint 64/27458)(Cache 52/23674)(cpu 173/27533)(breakpoint 20/27463)(uncore_imc 0/3960)(power 0/4112)(#8 0/72)(#9 0/37)(#10 0/24)(#11 0/24)(#12 0/30)(#13 0/28)(#14 0/30)(>14 0/21326)
Close attempts: 862 Successful: 862
Read attempts: 928 Successful: 818
Write attempts: 925 Successful: 0
Ioctl attempts: 898 Successful: 397
Mmap attempts: 919 Successful: 367
Prctl attempts: 903 Successful: 903
Fork attempts: 454 Successful: 454
Poll attempts: 936 Successful: 0
Access attempts: 875 Successful: 444
Trash mmap attempts: 899 Successful: 899
Overflows: 0
SIGIOs due to RT signal queue full: 0
[69213.252805] ------------[ cut here ]------------
[69213.260637] WARNING: CPU: 4 PID: 11343 at arch/x86/kernel/cpu/perf_event_intel.c:1373 intel_pmu_handle_irq+0x2a4/0x3c0()
[69213.276788] perfevents: irq loop stuck!
[69213.285424] Modules linked in: fuse x86_pkg_temp_thermal intel_powerclamp coretemp snd_hda_codec_realtek kvm snd_hda_codec_hdmi snd_hda_codec_generic crc32_pclmul snd_hda_intel ghash_clmulni_intel aesni_intel snd_hda_controller aes_x86_64 snd_hda_codec i915 snd_hwdep iTCO_wdt lrw snd_pcm gf128mul drm_kms_helper glue_helper snd_timer iTCO_vendor_support ppdev evdev drm wmi battery parport_pc mei_me tpm_tis parport ablk_helper button i2c_algo_bit processor video i2c_i801 psmouse i2c_core snd pcspkr serio_raw cryptd soundcore tpm lpc_ich mfd_core mei sd_mod crc_t10dif sr_mod crct10dif_generic cdrom ehci_pci ehci_hcd xhci_hcd ahci e1000e libahci libata crct10dif_pclmul crct10dif_common ptp usbcore crc32c_intel scsi_mod pps_core usb_common fan thermal thermal_sys
[69213.378556] CPU: 4 PID: 11343 Comm: perf_fuzzer Tainted: G D 3.15.0-rc5+ #108
[69213.391205] Hardware name: LENOVO 10AM000AUS/SHARKBAY, BIOS FBKT72AUS 01/26/2014
[69213.403033] 0000000000000009 ffff88011eb06cb0 ffffffff8164a8f0 ffff88011eb06cf8
[69213.414865] ffff88011eb06ce8 ffffffff810646ad 0000000000000064 ffff88011eb0cbe0
[69213.426497] ffff880036ec8000 0000000000000040 ffff88011eb0cde0 ffff88011eb06d48
[69213.438024] Call Trace:
[69213.444133] <NMI> [<ffffffff8164a8f0>] dump_stack+0x45/0x56
[69213.453792] [<ffffffff810646ad>] warn_slowpath_common+0x7d/0xa0
[69213.463691] [<ffffffff8106471c>] warn_slowpath_fmt+0x4c/0x50
[69213.473231] [<ffffffff8102efe4>] intel_pmu_handle_irq+0x2a4/0x3c0
[69213.483198] [<ffffffff8165440b>] perf_event_nmi_handler+0x2b/0x50
[69213.493162] [<ffffffff81653bd8>] nmi_handle.isra.5+0xa8/0x150
[69213.502796] [<ffffffff81653b35>] ? nmi_handle.isra.5+0x5/0x150
[69213.512514] [<ffffffff81653d58>] do_nmi+0xd8/0x340
[69213.521079] [<ffffffff81653201>] end_repeat_nmi+0x1e/0x2e
[69213.530362] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[69213.540425] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[69213.550387] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[69213.560288] <<EOE>> <IRQ> [<ffffffff8102ebcd>] intel_pmu_enable_event+0x21d/0x240
[69213.571791] [<ffffffff81027bfa>] x86_pmu_start+0x7a/0x100
[69213.580833] [<ffffffff810283f5>] x86_pmu_enable+0x295/0x310
[69213.590010] [<ffffffff8113538f>] perf_pmu_enable+0x2f/0x40
[69213.599039] [<ffffffff81136c04>] perf_cpu_hrtimer_handler+0xf4/0x200
[69213.609033] [<ffffffff8108b286>] __run_hrtimer+0x86/0x1e0
[69213.617999] [<ffffffff81136b10>] ? perf_event_context_sched_in+0xd0/0xd0
[69213.628315] [<ffffffff8108bdd7>] hrtimer_interrupt+0xf7/0x240
[69213.637648] [<ffffffff81044677>] local_apic_timer_interrupt+0x37/0x60
[69213.647709] [<ffffffff8165da16>] smp_trace_apic_timer_interrupt+0x46/0xb9
[69213.658188] [<ffffffff8165c41d>] trace_apic_timer_interrupt+0x6d/0x80
[69213.668302] <EOI>
[69213.670400] ---[ end trace 4d7b668c63a63e5c ]---
[69213.681834]
[69213.686561] CPU#4: ctrl: 0000000000000000
[69213.694352] CPU#4: status: 0000000000000000
[69213.701979] CPU#4: overflow: 0000000000000000
[69213.709599] CPU#4: fixed: 00000000000000b8
[69213.717172] CPU#4: pebs: 0000000000000000
[69213.724596] CPU#4: active: 0000000300000000
[69213.731939] CPU#4: gen-PMC0 ctrl: 000000000013412e
[69213.739877] CPU#4: gen-PMC0 count: 000000000000002c
[69213.747820] CPU#4: gen-PMC0 left: 0000ffffffffffd7
[69213.755657] CPU#4: gen-PMC1 ctrl: 0000000000138b40
[69213.763461] CPU#4: gen-PMC1 count: 00000000000086b3
[69213.771152] CPU#4: gen-PMC1 left: 0000ffffffff81c9
[69213.778742] CPU#4: gen-PMC2 ctrl: 000000000013024e
[69213.786271] CPU#4: gen-PMC2 count: 0000000000000001
[69213.793784] CPU#4: gen-PMC2 left: 0000ffffffffffff
[69213.801227] CPU#4: gen-PMC3 ctrl: 0000000000134f2e
[69213.808720] CPU#4: gen-PMC3 count: 00000000000009f9
[69213.816192] CPU#4: gen-PMC3 left: 0000fffffffff6de
[69213.823620] CPU#4: fixed-PMC0 count: 0000fffffffffffe
[69213.831035] CPU#4: fixed-PMC1 count: 0000ffffea2a90b2
[69213.838477] CPU#4: fixed-PMC2 count: 00000000051c5865
[69213.845792] perf_event_intel: clearing PMU state on CPU#4
[69213.853505] INFO: NMI handler (perf_event_nmi_handler) took too long to run: 600.823 msecs
[69213.864201] perf interrupt took too long (4696473 > 20000), lowering kernel.perf_event_max_sample_rate to 6250
</pre>
<li>Reproducibe case with 0.29-pre
<pre>
./perf_fuzzer -t OCIRMQWPFpAi -s 50000 -r 1400007525
</pre>
<li>
<pre>
*** perf_fuzzer 0.28 *** by Vince Weaver
Linux version 3.15.0-rc1+ x86_64
Processor: Intel 6/60/3
Seeding random number generator with 1399378358
/proc/sys/kernel/perf_event_max_sample_rate currently: 6250/s
/proc/sys/kernel/perf_event_paranoid currently: 1
Logging perf_event_open() failures: no
Running fsync after every syscall: no
To reproduce, try: ./perf_fuzzer -t OCIRMQWPFpAi -s 50000 -r 1399378358
Pid=4598, sleeping 1s
==================================================
Fuzzing the following syscalls:
mmap perf_event_open close read write ioctl fork prctl poll
*NOT* Fuzzing the following syscalls:
Also attempting the following:
busy-instruction-loop accessing-perf-proc-and-sys-files trashing-the-mma
p-page
*NOT* attempting the following:
signal-handler-on-overflow
==================================================
[76576.580505] ------------[ cut here ]------------
[76576.585446] WARNING: CPU: 4 PID: 4598 at arch/x86/kernel/cpu/perf_event_intel.c:1373 intel_pmu_handle_irq+0x2a4/0x3c0()
[76576.597028] perfevents: irq loop stuck!
[76576.601156] Modules linked in: fuse x86_pkg_temp_thermal intel_powerclamp coretemp kvm snd_hda_codec_hdmi crct10dif_pclmul crc32_pclmul ghash_clmulni_intel snd_hda_codec_realtek snd_hda_codec_generic i915 aesni_intel snd_hda_intel snd_hda_controller snd_hda_codec snd_hwdep snd_pcm snd_seq snd_timer snd_seq_device tpm_tis ppdev snd aes_x86_64 parport_pc tpm evdev mei_me drm_kms_helper iTCO_wdt drm soundcore lrw gf128mul glue_helper iTCO_vendor_support wmi ablk_helper i2c_algo_bit button battery processor mei psmouse parport pcspkr serio_raw cryptd i2c_i801 video i2c_core lpc_ich mfd_core sd_mod sr_mod crc_t10dif cdrom crct10dif_common ahci libahci ehci_pci e1000e libata xhci_hcd ehci_hcd ptp crc32c_intel usbcore scsi_mod pps_core usb_common fan thermal thermal_sys
[76576.675785] CPU: 4 PID: 4598 Comm: perf_fuzzer Not tainted 3.15.0-rc1+ #104
[76576.683257] Hardware name: LENOVO 10AM000AUS/SHARKBAY, BIOS FBKT72AUS 01/26/2014
[76576.691229] 0000000000000009 ffff88011eb06cb0 ffffffff81649ca0 ffff88011eb06cf8
[76576.699279] ffff88011eb06ce8 ffffffff810646ad 0000000000000064 ffff88011eb0cbe0
[76576.707343] ffff8800c9c1d800 0000000000000040 ffff88011eb0cde0 ffff88011eb06d48
[76576.715389] Call Trace:
[76576.718009] <NMI> [<ffffffff81649ca0>] dump_stack+0x45/0x56
[76576.724230] [<ffffffff810646ad>] warn_slowpath_common+0x7d/0xa0
[76576.730682] [<ffffffff8106471c>] warn_slowpath_fmt+0x4c/0x50
[76576.736888] [<ffffffff8102ef94>] intel_pmu_handle_irq+0x2a4/0x3c0
[76576.743541] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[76576.750209] [<ffffffff8165378b>] perf_event_nmi_handler+0x2b/0x50
[76576.756867] [<ffffffff81652f58>] nmi_handle.isra.5+0xa8/0x150
[76576.763149] [<ffffffff81652eb5>] ? nmi_handle.isra.5+0x5/0x150
[76576.769543] [<ffffffff816530d8>] do_nmi+0xd8/0x340
[76576.774799] [<ffffffff81652581>] end_repeat_nmi+0x1e/0x2e
[76576.780706] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[76576.787384] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[76576.794028] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[76576.800659] <<EOE>> [<ffffffff8102eb7d>] intel_pmu_enable_event+0x21d/0x240
[76576.808304] [<ffffffff81027baa>] x86_pmu_start+0x7a/0x100
[76576.814200] [<ffffffff810283a5>] x86_pmu_enable+0x295/0x310
[76576.820254] [<ffffffff8113528f>] perf_pmu_enable+0x2f/0x40
[76576.826225] [<ffffffff8102644a>] x86_pmu_commit_txn+0x7a/0xa0
[76576.832496] [<ffffffff8108b98a>] ? __hrtimer_start_range_ns+0x19a/0x3a0
[76576.839738] [<ffffffff810b0cad>] ? __lock_acquire.isra.29+0x3bd/0xb90
[76576.846734] [<ffffffff8101a21e>] ? arch_install_hw_breakpoint+0xce/0x100
[76576.854001] [<ffffffff81135fe0>] ? event_sched_in.isra.76+0x150/0x1e0
[76576.861030] [<ffffffff81136230>] group_sched_in+0x1c0/0x1e0
[76576.867117] [<ffffffff81136725>] __perf_event_enable+0x255/0x260
[76576.873717] [<ffffffff811318f0>] remote_function+0x40/0x50
[76576.879698] [<ffffffff810dda26>] generic_exec_single+0x126/0x170
[76576.886210] [<ffffffff811318b0>] ? task_clock_event_add+0x40/0x40
[76576.892894] [<ffffffff810ddad7>] smp_call_function_single+0x67/0xa0
[76576.899684] [<ffffffff811307f9>] task_function_call+0x49/0x60
[76576.905957] [<ffffffff811364d0>] ? perf_event_sched_in+0x90/0x90
[76576.913747] [<ffffffff811308a0>] perf_event_enable+0x90/0xf0
[76576.921171] [<ffffffff81130810>] ? task_function_call+0x60/0x60
[76576.928855] [<ffffffff8113097f>] perf_event_for_each_child+0x3f/0xb0
[76576.937001] [<ffffffff811372af>] perf_event_task_enable+0x4f/0x80
[76576.944851] [<ffffffff8107be85>] SyS_prctl+0x255/0x4b0
[76576.951663] [<ffffffff813becc6>] ? lockdep_sys_exit_thunk+0x35/0x67
[76576.959707] [<ffffffff8165a96d>] system_call_fastpath+0x1a/0x1f
[76576.967357] ---[ end trace 2b5a3d32e8d767a6 ]---
[76576.973524]
[76576.976338] CPU#4: ctrl: 0000000000000000
[76576.982445] CPU#4: status: 0000000000000000
[76576.988522] CPU#4: overflow: 0000000000000000
[76576.994597] CPU#4: fixed: 00000000000000b9
[76577.000694] CPU#4: pebs: 0000000000000000
[76577.006774] CPU#4: active: 0000000300000007
[76577.012842] CPU#4: gen-PMC0 ctrl: 000000002450123c
[76577.019480] CPU#4: gen-PMC0 count: 0000000000000001
[76577.026151] CPU#4: gen-PMC0 left: 0000ffffffffffff
[76577.032825] CPU#4: gen-PMC1 ctrl: 0000000010c101c2
[76577.039477] CPU#4: gen-PMC1 count: 00000000039f37f8
[76577.046121] CPU#4: gen-PMC1 left: 0000fffffc618a8f
[76577.052722] CPU#4: gen-PMC2 ctrl: 0000000000540800
[76577.059354] CPU#4: gen-PMC2 count: 0000000000000001
[76577.065924] CPU#4: gen-PMC2 left: 0000ffffffffffff
[76577.072474] CPU#4: gen-PMC3 ctrl: 000000000010412e
[76577.079016] CPU#4: gen-PMC3 count: 0000000000000001
[76577.091968] CPU#4: fixed-PMC0 count: 0000fffffffffffe
[76577.098320] CPU#4: fixed-PMC1 count: 0000fffcb8c081d9
[76577.104602] CPU#4: fixed-PMC2 count: 000000000288ac63
[76577.110844] perf_event_intel: clearing PMU state on CPU#4
[76577.117485] INFO: NMI handler (perf_event_nmi_handler) took too long to run: 536.956 msecs
[76577.127177] perf interrupt took too long (4196671 > 38461), lowering kernel.perf_event_max_sample_rate to 3250
[76577.138804] perf_event_intel: clearing PMU state on CPU#4
[76577.145453] perf interrupt took too long (4215989 > 71428), lowering kernel.perf_event_max_sample_rate to 1750
[76577.619546] perf interrupt took too long (4117985 > 500000), lowering kernel.perf_event_max_sample_rate to 250
</pre>
<li>
<pre>
*** perf_fuzzer 0.28 *** by Vince Weaver
Linux version 3.15.0-rc1+ x86_64
Processor: Intel 6/60/3
Seeding random number generator with 1399077851
/proc/sys/kernel/perf_event_max_sample_rate currently: 12500/s
/proc/sys/kernel/perf_event_paranoid currently: 1
Logging perf_event_open() failures: no
Running fsync after every syscall: no
To reproduce, try: ./perf_fuzzer -t OCIRMQWPFpAi -s 50000 -r 1399077851
Pid=4743, sleeping 1s
==================================================
Fuzzing the following syscalls:
mmap perf_event_open close read write ioctl fork prctl poll
*NOT* Fuzzing the following syscalls:
Also attempting the following:
busy-instruction-loop accessing-perf-proc-and-sys-files trashing-the-mmap-page
*NOT* attempting the following:
signal-handler-on-overflow
==================================================
Iteration 10000
Open attempts: 353239 Successful: 915
EPERM : 17
ENOENT : 942
E2BIG : 41017
EBADF : 6289
EACCES : 272
EINVAL : 303113
ENOSPC : 19
EOPNOTSUPP : 655
Close attempts: 876 Successful: 876
Read attempts: 881 Successful: 763
Write attempts: 844 Successful: 0
Ioctl attempts: 854 Successful: 388
Mmap attempts: 915 Successful: 289
Prctl attempts: 884 Successful: 884
Fork attempts: 445 Successful: 445
Poll attempts: 900 Successful: 7
Access attempts: 929 Successful: 466
Trash mmap attempts: 843 Successful: 843
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 20000
Open attempts: 336925 Successful: 913
EPERM : 19
ENOENT : 923
E2BIG : 39023
EBADF : 5522
EACCES : 247
EINVAL : 289437
ENOSPC : 144
EOPNOTSUPP : 697
Close attempts: 901 Successful: 901
Read attempts: 952 Successful: 819
Write attempts: 929 Successful: 0
Ioctl attempts: 857 Successful: 379
Mmap attempts: 913 Successful: 262
Prctl attempts: 875 Successful: 875
Fork attempts: 460 Successful: 460
Poll attempts: 885 Successful: 8
Access attempts: 927 Successful: 482
Trash mmap attempts: 889 Successful: 889
Overflows: 0
SIGIOs due to RT signal queue full: 0
[17190.202941] ------------[ cut here ]------------
[17190.207906] WARNING: CPU: 2 PID: 4743 at arch/x86/kernel/cpu/perf_event_intel.c:1373 intel_pmu_handle_irq+0x2a4/0x3c0()
[17190.219460] perfevents: irq loop stuck!
[17190.223579] Modules linked in: fuse x86_pkg_temp_thermal intel_powerclamp coretemp kvm snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic snd_hda_intel snd_hda_controller crct10dif_pclmul snd_hda_codec crc32_pclmul snd_hwdep ghash_clmulni_intel snd_pcm aesni_intel aes_x86_64 lrw snd_seq snd_timer snd_seq_device gf128mul snd i915 glue_helper evdev soundcore drm_kms_helper mei_me iTCO_wdt iTCO_vendor_support lpc_ich battery drm ppdev psmouse serio_raw ablk_helper cryptd wmi parport_pc mei parport tpm_tis i2c_algo_bit button processor video tpm i2c_i801 i2c_core mfd_core pcspkr sd_mod sr_mod crc_t10dif cdrom crct10dif_common ehci_pci ahci xhci_hcd ehci_hcd libahci e1000e libata ptp crc32c_intel usbcore scsi_mod pps_core usb_common thermal fan thermal_sys
[17190.298419] CPU: 2 PID: 4743 Comm: perf_fuzzer Not tainted 3.15.0-rc1+ #102
[17190.305926] Hardware name: LENOVO 10AM000AUS/SHARKBAY, BIOS FBKT72AUS 01/26/2014
[17190.313906] 0000000000000009 ffff88011ea86cb0 ffffffff81649c80 ffff88011ea86cf8
[17190.322034] ffff88011ea86ce8 ffffffff810646ad 0000000000000064 ffff88011ea8cbe0
[17190.330134] ffff8800cf7a7800 0000000000000040 ffff88011ea8cde0 ffff88011ea86d48
[17190.338122] Call Trace:
[17190.340775] <NMI> [<ffffffff81649c80>] dump_stack+0x45/0x56
[17190.347023] [<ffffffff810646ad>] warn_slowpath_common+0x7d/0xa0
[17190.353472] [<ffffffff8106471c>] warn_slowpath_fmt+0x4c/0x50
[17190.359677] [<ffffffff8102ef94>] intel_pmu_handle_irq+0x2a4/0x3c0
[17190.366315] [<ffffffff8105034d>] ? native_write_msr_safe+0xd/0x10
[17190.372954] [<ffffffff8165378b>] perf_event_nmi_handler+0x2b/0x50
[17190.379629] [<ffffffff81652f58>] nmi_handle.isra.5+0xa8/0x150
[17190.385879] [<ffffffff81652eb5>] ? nmi_handle.isra.5+0x5/0x150
[17190.392287] [<ffffffff816530d8>] do_nmi+0xd8/0x340
[17190.397572] [<ffffffff81652581>] end_repeat_nmi+0x1e/0x2e
[17190.403472] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[17190.410098] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[17190.416765] [<ffffffff8105034a>] ? native_write_msr_safe+0xa/0x10
[17190.423386] <<EOE>> [<ffffffff8102eb7d>] intel_pmu_enable_event+0x21d/0x240
[17190.431048] [<ffffffff81027baa>] x86_pmu_start+0x7a/0x100
[17190.436992] [<ffffffff810283a5>] x86_pmu_enable+0x295/0x310
[17190.443104] [<ffffffff8113528f>] perf_pmu_enable+0x2f/0x40
[17190.449087] [<ffffffff811369a8>] perf_event_context_sched_in+0x88/0xd0
[17190.456165] [<ffffffff8113713d>] __perf_event_task_sched_in+0x1dd/0x1f0
[17190.463412] [<ffffffff81090ca8>] finish_task_switch+0xd8/0x120
[17190.469750] [<ffffffff8164ca90>] __schedule+0x2c0/0x740
[17190.475443] [<ffffffff8164cf39>] schedule+0x29/0x70
[17190.480772] [<ffffffff8164c74c>] schedule_hrtimeout_range_clock+0x13c/0x180
[17190.488331] [<ffffffff8108b1c0>] ? hrtimer_get_res+0x50/0x50
[17190.494491] [<ffffffff8164c6c9>] ? schedule_hrtimeout_range_clock+0xb9/0x180
[17190.502135] [<ffffffff8164c7a3>] schedule_hrtimeout_range+0x13/0x20
[17190.508983] [<ffffffff811c94c9>] poll_schedule_timeout+0x49/0x70
[17190.515535] [<ffffffff811cab22>] do_sys_poll+0x422/0x540
[17190.521354] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.528737] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.536129] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.543552] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.550915] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.558290] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.565698] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.573075] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.580488] [<ffffffff811c9650>] ? poll_select_copy_remaining+0x130/0x130
[17190.589071] [<ffffffff811cad15>] SyS_poll+0x65/0x100
[17190.595690] [<ffffffff8165a96d>] system_call_fastpath+0x1a/0x1f
[17190.603315] ---[ end trace d44f7960e96a18da ]---
[17190.609412]
[17190.612182] CPU#2: ctrl: 0000000000000000
[17190.618136] CPU#2: status: 0000000000000000
[17190.624190] CPU#2: overflow: 0000000000000000
[17190.630144] CPU#2: fixed: 00000000000000ba
[17190.636123] CPU#2: pebs: 0000000000000000
[17190.642042] CPU#2: active: 0000000300000001
[17190.648000] CPU#2: gen-PMC0 ctrl: 00000000004000c4
[17190.654531] CPU#2: gen-PMC0 count: 0000000000000001
[17190.661059] CPU#2: gen-PMC0 left: 0000ffffffffffff
[17190.667576] CPU#2: gen-PMC1 ctrl: 0000000000120280
[17190.674101] CPU#2: gen-PMC1 count: 0000000000005439
[17190.680623] CPU#2: gen-PMC1 left: 0000ffffffffaf43
[17190.687127] CPU#2: gen-PMC2 ctrl: 0000000000114f2e
[17190.693589] CPU#2: gen-PMC2 count: 0000000000000001
[17190.700039] CPU#2: gen-PMC2 left: 0000ffffffffffff
[17190.706455] CPU#2: gen-PMC3 ctrl: 00000000001300c0
[17190.712846] CPU#2: gen-PMC3 count: 0000000000000001
[17190.719135] CPU#2: gen-PMC3 left: 0000ffffffffffff
[17190.725357] CPU#2: fixed-PMC0 count: 0000fffffffffffe
[17190.731529] CPU#2: fixed-PMC1 count: 0000ffff192febe2
[17190.737687] CPU#2: fixed-PMC2 count: 0000000000000001
[17190.743840] perf_event_intel: clearing PMU state on CPU#2
</pre>
<li>
<pre>
*** perf_fuzzer 0.28 *** by Vince Weaver
Linux version 3.15.0-rc1+ x86_64
Processor: Intel 6/60/3
Seeding random number generator with 1398101771
/proc/sys/kernel/perf_event_max_sample_rate currently: 50000/s
/proc/sys/kernel/perf_event_paranoid currently: 1
Logging perf_event_open() failures: no
Running fsync after every syscall: no
To reproduce, try: ./perf_fuzzer -t OCIRMQWPFpAi -s 50000 -r 1398101771
Pid=11876, sleeping 1s
==================================================
Fuzzing the following syscalls:
mmap perf_event_open close read write ioctl fork prctl poll
*NOT* Fuzzing the following syscalls:
Also attempting the following:
busy-instruction-loop accessing-perf-proc-and-sys-files trashing-the-mmap-page
*NOT* attempting the following:
signal-handler-on-overflow
==================================================
Iteration 10000
Open attempts: 337104 Successful: 905
EPERM : 14
ENOENT : 919
E2BIG : 39172
EBADF : 5587
EACCES : 249
EINVAL : 289434
ENOSPC : 179
EOPNOTSUPP : 645
Close attempts: 874 Successful: 874
Read attempts: 912 Successful: 781
Write attempts: 869 Successful: 0
Ioctl attempts: 875 Successful: 404
Mmap attempts: 905 Successful: 270
Prctl attempts: 889 Successful: 889
Fork attempts: 482 Successful: 482
Poll attempts: 945 Successful: 13
Access attempts: 857 Successful: 459
Trash mmap attempts: 885 Successful: 885
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 20000
Open attempts: 356748 Successful: 929
EPERM : 16
ENOENT : 966
E2BIG : 41129
EBADF : 5836
EACCES : 279
EINVAL : 306820
ENOSPC : 133
EOPNOTSUPP : 640
Close attempts: 913 Successful: 913
Read attempts: 925 Successful: 793
Write attempts: 859 Successful: 0
Ioctl attempts: 908 Successful: 400
Mmap attempts: 929 Successful: 283
Prctl attempts: 853 Successful: 853
Fork attempts: 483 Successful: 483
Poll attempts: 946 Successful: 19
Access attempts: 921 Successful: 441
Trash mmap attempts: 867 Successful: 867
Overflows: 0
SIGIOs due to RT signal queue full: 0
Iteration 30000
Open attempts: 356531 Successful: 924
EPERM : 14
ENOENT : 1027
E2BIG : 41510
EBADF : 5409
EACCES : 263
EINVAL : 306288
ENOSPC : 397
EOPNOTSUPP : 699
Close attempts: 871 Successful: 871
Read attempts: 886 Successful: 772
Write attempts: 905 Successful: 0
Ioctl attempts: 912 Successful: 402
Mmap attempts: 924 Successful: 231
Prctl attempts: 958 Successful: 958
Fork attempts: 449 Successful: 449
Poll attempts: 880 Successful: 42
Access attempts: 941 Successful: 478
Trash mmap attempts: 935 Successful: 935
Overflows: 0
SIGIOs due to RT signal queue full: 0
[233086.504483] perf interrupt took too long (5017 > 5000), lowering kernel.perf_event_max_sample_rate to 25000
Iteration 40000
Open attempts: 323102 Successful: 866
EPERM : 14
ENOENT : 883
E2BIG : 37600
EBADF : 5049
EACCES : 232
EINVAL : 277485
ENOSPC : 351
EOPNOTSUPP : 622
Close attempts: 928 Successful: 928
Read attempts: 881 Successful: 726
Write attempts: 891 Successful: 0
Ioctl attempts: 889 Successful: 404
Mmap attempts: 866 Successful: 232
Prctl attempts: 882 Successful: 882
Fork attempts: 463 Successful: 463
Poll attempts: 949 Successful: 34
Access attempts: 939 Successful: 472
Trash mmap attempts: 907 Successful: 907
Overflows: 0
SIGIOs due to RT signal queue full: 0
[233108.540578] ------------[ cut here ]------------
[233108.545658] WARNING: CPU: 3 PID: 11876 at arch/x86/kernel/cpu/perf_event_intel.c:1373 intel_pmu_handle_irq+0x2a4/0x3c0()
[233108.557265] perfevents: irq loop stuck!
[233108.561443] Modules linked in: fuse x86_pkg_temp_thermal intel_powerclamp coretemp snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic kvm snd_hda_intel snd_hda_controller crct10dif_pclmul snd_hda_codec crc32_pclmul ghash_clmulni_intel aesni_intel aes_x86_64 mei_me snd_hwdep snd_pcm lrw gf128mul glue_helper snd_seq i915 mei ablk_helper iTCO_wdt snd_timer cryptd snd_seq_device parport_pc iTCO_vendor_support psmouse wmi i2c_i801 pcspkr snd parport serio_raw tpm_tis drm_kms_helper lpc_ich mfd_core drm evdev tpm i2c_algo_bit button processor video battery i2c_core soundcore sg sd_mod sr_mod crc_t10dif cdrom crct10dif_common hid_generic usbhid hid ahci libahci libata ehci_pci xhci_hcd ehci_hcd e1000e scsi_mod ptp crc32c_intel usbcore pps_core usb_common fan thermal thermal_sys
[233108.636437] CPU: 3 PID: 11876 Comm: perf_fuzzer Not tainted 3.15.0-rc1+ #66
[233108.643855] Hardware name: LENOVO 10AM000AUS/SHARKBAY, BIOS FBKT72AUS 01/26/2014
[233108.651806] 0000000000000009 ffff88011eac6cb0 ffffffff8164f86d ffff88011eac6cf8
[233108.659967] ffff88011eac6ce8 ffffffff810647cd 0000000000000064 ffff88011eaccbe0
[233108.668082] ffff880004cbc000 0000000000000040 ffff88011eaccde0 ffff88011eac6d48
[233108.676239] Call Trace:
[233108.678919] <NMI> [<ffffffff8164f86d>] dump_stack+0x45/0x56
[233108.685240] [<ffffffff810647cd>] warn_slowpath_common+0x7d/0xa0
[233108.691783] [<ffffffff8106483c>] warn_slowpath_fmt+0x4c/0x50
[233108.698068] [<ffffffff81026e76>] ? x86_pmu_stop+0x76/0xd0
[233108.704058] [<ffffffff8102ef94>] intel_pmu_handle_irq+0x2a4/0x3c0
[233108.710799] [<ffffffff81116b8d>] ? trace_buffer_unlock_commit+0x4d/0x60
[233108.718108] [<ffffffff8112436a>] ? ftrace_event_buffer_commit+0x8a/0xc0
[233108.725417] [<ffffffff8165940b>] perf_event_nmi_handler+0x2b/0x50
[233108.732169] [<ffffffff81658bd8>] nmi_handle.isra.5+0xa8/0x150
[233108.738480] [<ffffffff81658b35>] ? nmi_handle.isra.5+0x5/0x150
[233108.744912] [<ffffffff81658d58>] do_nmi+0xd8/0x340
[233108.750267] [<ffffffff81658201>] end_repeat_nmi+0x1e/0x2e
[233108.756248] [<ffffffff8105046a>] ? native_write_msr_safe+0xa/0x10
[233108.762977] [<ffffffff8105046a>] ? native_write_msr_safe+0xa/0x10
[233108.769700] [<ffffffff8105046a>] ? native_write_msr_safe+0xa/0x10
[233108.776456] <<EOE>> [<ffffffff8102eb7d>] intel_pmu_enable_event+0x21d/0x240
[233108.784264] [<ffffffff81027baa>] x86_pmu_start+0x7a/0x100
[233108.790258] [<ffffffff810283a5>] x86_pmu_enable+0x295/0x310
[233108.796411] [<ffffffff81135a67>] perf_pmu_enable+0x27/0x30
[233108.802457] [<ffffffff8102644a>] x86_pmu_commit_txn+0x7a/0xa0
[233108.808831] [<ffffffff81116b8d>] ? trace_buffer_unlock_commit+0x4d/0x60
[233108.816143] [<ffffffff8112436a>] ? ftrace_event_buffer_commit+0x8a/0xc0
[233108.823428] [<ffffffff810b13bd>] ? __lock_acquire.isra.29+0x3bd/0xb90
[233108.830509] [<ffffffff810af8ca>] ? ftrace_raw_event_lock_acquire+0xba/0x100
[233108.838183] [<ffffffff81136748>] ? event_sched_in.isra.76+0x148/0x1e0
[233108.845318] [<ffffffff811369a0>] group_sched_in+0x1c0/0x1e0
[233108.851515] [<ffffffff81136e95>] __perf_event_enable+0x255/0x260
[233108.858151] [<ffffffff81132390>] remote_function+0x40/0x50
[233108.864288] [<ffffffff810de136>] generic_exec_single+0x126/0x170
[233108.870954] [<ffffffff81132350>] ? task_clock_event_add+0x40/0x40
[233108.877665] [<ffffffff810de1e7>] smp_call_function_single+0x67/0xa0
[233108.884584] [<ffffffff811312f4>] task_function_call+0x44/0x50
[233108.890971] [<ffffffff81136c40>] ? perf_event_sched_in+0x90/0x90
[233108.897650] [<ffffffff81131390>] perf_event_enable+0x90/0xf0
[233108.903936] [<ffffffff81131300>] ? task_function_call+0x50/0x50
[233108.910465] [<ffffffff8113146a>] perf_event_for_each_child+0x3a/0xa0
[233108.917448] [<ffffffff811379ff>] perf_event_task_enable+0x4f/0x80
[233108.924198] [<ffffffff8107c015>] SyS_prctl+0x255/0x4b0
[233108.929938] [<ffffffff81660d44>] tracesys+0xe1/0xe6
[233108.935334] ---[ end trace 01c78b8dcb064f75 ]---
[233108.940414]
[233108.942136] CPU#3: ctrl: 0000000000000000
[233108.947065] CPU#3: status: 0000000000000000
[233108.953180] CPU#3: overflow: 0000000000000000
[233108.959254] CPU#3: fixed: 00000000000000b0
[233108.965309] CPU#3: pebs: 0000000000000000
[233108.971365] CPU#3: active: 000000020000000f
[233108.977354] CPU#3: gen-PMC0 ctrl: 0000000000500030
[233108.983917] CPU#3: gen-PMC0 count: 0000000000000001
[233108.990455] CPU#3: gen-PMC0 left: 0000ffffffffffff
[233108.996937] CPU#3: gen-PMC1 ctrl: 000000000052013c
[233109.003417] CPU#3: gen-PMC1 count: 0000000000001d2e
[233109.009888] CPU#3: gen-PMC1 left: 0000ffffffffffff
[233109.016324] CPU#3: gen-PMC2 ctrl: 0000000010c001c2
[233109.022720] CPU#3: gen-PMC2 count: 000000000f44a8c7
[233109.029064] CPU#3: gen-PMC2 left: 0000fffff0bf60c5
[233109.035351] CPU#3: gen-PMC3 ctrl: 0000000000534f2e
[233109.041600] CPU#3: gen-PMC3 count: 0000fffffffe4164
[233109.047798] CPU#3: gen-PMC3 left: 000000000001be9c
[233109.054009] CPU#3: fixed-PMC0 count: 0000fffffffffffe
[233109.060247] CPU#3: fixed-PMC1 count: 0000fff95bbfd25f
[233109.066456] CPU#3: fixed-PMC2 count: 0000000000000001
[233109.072660] perf_event_intel: clearing PMU state on CPU#3
</pre>
</ol>
<hr>
<a href="bugs_found.html">Back to perf_fuzzer bugs found</a>
</body>
</html>
| deater/perf_event_tests | fuzzer/bugs-found/3.15-rc1.irq_loop_warning.html | HTML | gpl-2.0 | 43,133 |
/*
Copyright (C) 2004 Michael Liebscher
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* renderer.h: Interface to graphics API.
*
* Author: Michael Liebscher <[email protected]>
* Date: 2004
*
* Acknowledgement:
* This code was derived from Quake II, and was originally
* written by Id Software, Inc.
*
*/
/*
Notes:
This module communicates with the graphics API. The API can be any graphics
API, e.g OpenGL, DirectX, SDL, GDI, etc; as long as the functions listed in
this header are implemented.
*/
#ifndef __RENDERER_H__
#define __RENDERER_H__
#include "filesystem.h"
#include "platform.h"
#include "texture_manager.h"
#include "font_manager.h"
#ifdef _WIN32
#define OPENGL_DLL_NAME "opengl32.dll"
#elif __unix__
#define OPENGL_DLL_NAME "libGL.so.1"
#else
#error "Define OPENGL_DLL_NAME"
#endif
typedef enum
{
rserr_ok,
rserr_invalid_fullscreen,
rserr_invalid_mode,
rserr_unknown
} rserr_t;
int registration_sequence;
int R_Init( void *hinstance, void *hWnd );
void R_Shutdown( void );
void R_BeginRegistration( const char *model );
void R_EndRegistration( void );
void R_BeginFrame( void );
void R_EndFrame( void );
void R_AppActivate( _boolean active );
void R_SwapBuffers( int );
void R_SetPalette( const unsigned char *palette);
void R_DeleteTexture( unsigned int texnum );
_boolean R_UploadTexture( texture_t *tex, PW8 data );
void R_SetGL2D( void );
void R_Draw_Pic( int x, int y, const char *name );
void R_Draw_StretchPic( int x, int y, int w, int h, const char *name );
void R_Draw_Character( int x, int y, int num, font_t *myfont );
void R_Draw_Tile( int x, int y, int w, int h, const char *name );
void R_Draw_Fill( int x, int y, int w, int h, colour3_t c );
void R_Draw_Line( int nXStart, int nYStart, int nXEnd, int nYEnd, int width, colour3_t c );
#endif /* __RENDERER_H__ */
| MichaelLiebscher/Wolfenstein3D_Redux | wolf3dredux/env/renderer.h | C | gpl-2.0 | 2,616 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Postgre Database Adapter Class
*
* Note: _DB is an extender class that the app controller
* creates dynamically based on whether the active record
* class is being used or not.
*
* @package CodeIgniter
* @subpackage Drivers
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
class CI_DB_postgre_driver extends CI_DB {
var $dbdriver = 'postgre';
var $_escape_char = '"';
// clause and character used for LIKE escape sequences
var $_like_escape_str = " ESCAPE '%s' ";
var $_like_escape_chr = '!';
/**
* The syntax to count rows is slightly different across different
* database engines, so this string appears in each driver and is
* used for the count_all() and count_all_results() functions.
*/
var $_count_string = "SELECT COUNT(*) AS ";
var $_random_keyword = ' RANDOM()'; // database specific random keyword
/**
* Connection String
*
* @access private
* @return string
*/
function _connect_string()
{
$components = array(
'hostname' => 'host',
'port' => 'port',
'database' => 'dbname',
'username' => 'user',
'password' => 'password'
);
$connect_string = "";
foreach ($components as $key => $val)
{
if (isset($this->$key) && $this->$key != '')
{
$connect_string .= " $val=".$this->$key;
}
}
return trim($connect_string);
}
// --------------------------------------------------------------------
/**
* Non-persistent database connection
*
* @access private called by the base class
* @return resource
*/
function db_connect()
{
return @pg_connect($this->_connect_string());
}
// --------------------------------------------------------------------
/**
* Persistent database connection
*
* @access private called by the base class
* @return resource
*/
function db_pconnect()
{
return @pg_pconnect($this->_connect_string());
}
// --------------------------------------------------------------------
/**
* Reconnect
*
* Keep / reestablish the db connection if no queries have been
* sent for a length of time exceeding the server's idle timeout
*
* @access public
* @return void
*/
function reconnect()
{
if (pg_ping($this->conn_id) === FALSE)
{
$this->conn_id = FALSE;
}
}
// --------------------------------------------------------------------
/**
* Select the database
*
* @access private called by the base class
* @return resource
*/
function db_select()
{
// Not needed for Postgre so we'll return TRUE
return TRUE;
}
// --------------------------------------------------------------------
/**
* Set client character set
*
* @access public
* @param string
* @param string
* @return resource
*/
function db_set_charset($charset, $collation)
{
// @todo - add support if needed
return TRUE;
}
// --------------------------------------------------------------------
/**
* Version number query string
*
* @access public
* @return string
*/
function _version()
{
return "SELECT version() AS ver";
}
// --------------------------------------------------------------------
/**
* Execute the query
*
* @access private called by the base class
* @param string an SQL query
* @return resource
*/
function _execute($sql)
{
$sql = $this->_prep_query($sql);
return @pg_query($this->conn_id, $sql);
}
// --------------------------------------------------------------------
/**
* Prep the query
*
* If needed, each database adapter can prep the query string
*
* @access private called by execute()
* @param string an SQL query
* @return string
*/
function _prep_query($sql)
{
return $sql;
}
// --------------------------------------------------------------------
/**
* Begin Transaction
*
* @access public
* @return bool
*/
function trans_begin($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return TRUE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
return TRUE;
}
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
$this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
return @pg_exec($this->conn_id, "begin");
}
// --------------------------------------------------------------------
/**
* Commit Transaction
*
* @access public
* @return bool
*/
function trans_commit()
{
if ( ! $this->trans_enabled)
{
return TRUE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
return TRUE;
}
return @pg_exec($this->conn_id, "commit");
}
// --------------------------------------------------------------------
/**
* Rollback Transaction
*
* @access public
* @return bool
*/
function trans_rollback()
{
if ( ! $this->trans_enabled)
{
return TRUE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
return TRUE;
}
return @pg_exec($this->conn_id, "rollback");
}
// --------------------------------------------------------------------
/**
* Escape String
*
* @access public
* @param string
* @param bool whether or not the string will be used in a LIKE condition
* @return string
*/
function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}
$str = pg_escape_string($str);
// escape LIKE condition wildcards
if ($like === TRUE)
{
$str = str_replace( array('%', '_', $this->_like_escape_chr),
array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
$str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Affected Rows
*
* @access public
* @return integer
*/
function affected_rows()
{
return @pg_affected_rows($this->result_id);
}
// --------------------------------------------------------------------
/**
* Insert ID
*
* @access public
* @return integer
*/
function insert_id()
{
$v = $this->_version();
$v = $v['server'];
$table = func_num_args() > 0 ? func_get_arg(0) : NULL;
$column = func_num_args() > 1 ? func_get_arg(1) : NULL;
if ($table == NULL && $v >= '8.1')
{
$sql='SELECT LASTVAL() as ins_id';
}
elseif ($table != NULL && $column != NULL && $v >= '8.0')
{
$sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column);
$query = $this->query($sql);
$row = $query->row();
$sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq);
}
elseif ($table != NULL)
{
// seq_name passed in table parameter
$sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table);
}
else
{
return pg_last_oid($this->result_id);
}
$query = $this->query($sql);
$row = $query->row();
return $row->ins_id;
}
// --------------------------------------------------------------------
/**
* "Count All" query
*
* Generates a platform-specific query string that counts all records in
* the specified database
*
* @access public
* @param string
* @return string
*/
function count_all($table = '')
{
if ($table == '')
{
return 0;
}
$query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
if ($query->num_rows() == 0)
{
return 0;
}
$row = $query->row();
$this->_reset_select();
return (int) $row->numrows;
}
// --------------------------------------------------------------------
/**
* Show table query
*
* Generates a platform-specific query string so that the table names can be fetched
*
* @access private
* @param boolean
* @return string
*/
function _list_tables($prefix_limit = FALSE)
{
$sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'";
if ($prefix_limit !== FALSE AND $this->dbprefix != '')
{
$sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Show column query
*
* Generates a platform-specific query string so that the column names can be fetched
*
* @access public
* @param string the table name
* @return string
*/
function _list_columns($table = '')
{
return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'";
}
// --------------------------------------------------------------------
/**
* Field data query
*
* Generates a platform-specific query so that the column data can be retrieved
*
* @access public
* @param string the table name
* @return object
*/
function _field_data($table)
{
return "SELECT * FROM ".$table." LIMIT 1";
}
// --------------------------------------------------------------------
/**
* The error message string
*
* @access private
* @return string
*/
function _error_message()
{
return pg_last_error($this->conn_id);
}
// --------------------------------------------------------------------
/**
* The error message number
*
* @access private
* @return integer
*/
function _error_number()
{
return '';
}
// --------------------------------------------------------------------
/**
* Escape the SQL Identifiers
*
* This function escapes column and table names
*
* @access private
* @param string
* @return string
*/
function _escape_identifiers($item)
{
if ($this->_escape_char == '')
{
return $item;
}
foreach ($this->_reserved_identifiers as $id)
{
if (strpos($item, '.'.$id) !== FALSE)
{
$str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
// remove duplicates if the user already included the escape
return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
}
}
if (strpos($item, '.') !== FALSE)
{
$str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
}
else
{
$str = $this->_escape_char.$item.$this->_escape_char;
}
// remove duplicates if the user already included the escape
return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
}
// --------------------------------------------------------------------
/**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
* about operator precedence in harmony with SQL standards
*
* @access public
* @param type
* @return type
*/
function _from_tables($tables)
{
if ( ! is_array($tables))
{
$tables = array($tables);
}
return implode(', ', $tables);
}
// --------------------------------------------------------------------
/**
* Insert statement
*
* Generates a platform-specific insert string from the supplied data
*
* @access public
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
function _insert($table, $keys, $values)
{
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
}
// --------------------------------------------------------------------
/**
* Insert_batch statement
*
* Generates a platform-specific insert string from the supplied data
*
* @access public
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
function _insert_batch($table, $keys, $values)
{
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
}
// --------------------------------------------------------------------
/**
* Update statement
*
* Generates a platform-specific update string from the supplied data
*
* @access public
* @param string the table name
* @param array the update data
* @param array the where clause
* @param array the orderby clause
* @param array the limit clause
* @return string
*/
function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
{
foreach ($values as $key => $val)
{
$valstr[] = $key." = ".$val;
}
$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
$orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
$sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
$sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
$sql .= $orderby.$limit;
return $sql;
}
// --------------------------------------------------------------------
/**
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
* If the database does not support the truncate() command
* This function maps to "DELETE FROM table"
*
* @access public
* @param string the table name
* @return string
*/
function _truncate($table)
{
return "TRUNCATE ".$table;
}
// --------------------------------------------------------------------
/**
* Delete statement
*
* Generates a platform-specific delete string from the supplied data
*
* @access public
* @param string the table name
* @param array the where clause
* @param string the limit clause
* @return string
*/
function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
$conditions = '';
if (count($where) > 0 OR count($like) > 0)
{
$conditions = "\nWHERE ";
$conditions .= implode("\n", $this->ar_where);
if (count($where) > 0 && count($like) > 0)
{
$conditions .= " AND ";
}
$conditions .= implode("\n", $like);
}
$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
return "DELETE FROM ".$table.$conditions.$limit;
}
// --------------------------------------------------------------------
/**
* Limit string
*
* Generates a platform-specific LIMIT clause
*
* @access public
* @param string the sql query string
* @param integer the number of rows to limit the query to
* @param integer the offset value
* @return string
*/
function _limit($sql, $limit, $offset)
{
$sql .= "LIMIT ".$limit;
if ($offset > 0)
{
$sql .= " OFFSET ".$offset;
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Close DB Connection
*
* @access public
* @param resource
* @return void
*/
function _close($conn_id)
{
@pg_close($conn_id);
}
}
/* End of file postgre_driver.php */
/* Location: ./system/database/drivers/postgre/postgre_driver.php */ | abhijeetmote/sama | system/database/drivers/postgre/postgre_driver.php | PHP | gpl-2.0 | 16,300 |
/*** ESSENTIAL STYLES ***/
.sf-menu, .sf-menu * {
margin: 0;
padding: 0;
list-style: none;
}
.sf-menu {
line-height: 1.0;
}
.sf-menu ul {
position: absolute;
top: -999em;
width: 10em; /* left offset of submenus need to match (see below) */
}
.sf-menu ul li {
width: 100%;
}
.sf-menu li:hover {
visibility: inherit; /* fixes IE7 'sticky bug' */
}
.sf-menu li {
float: left;
position: relative;
}
.sf-menu a {
display: block;
position: relative;
}
.sf-menu li:hover ul,
.sf-menu li.sfHover ul {
left: 0;
top: 2.5em; /* match top ul list item height */
z-index: 9999;
}
ul.sf-menu li:hover li ul,
ul.sf-menu li.sfHover li ul {
top: -999em;
}
ul.sf-menu li li:hover ul,
ul.sf-menu li li.sfHover ul {
left: 13.5em; /* match ul width */
top: 0;
}
ul.sf-menu li li:hover li ul,
ul.sf-menu li li.sfHover li ul {
top: -999em;
}
ul.sf-menu li li li:hover ul,
ul.sf-menu li li li.sfHover ul {
left: 10em; /* match ul width */
top: 0;
}
/*** DEMO SKIN ***/
.sf-menu {
float: left;
margin-bottom: 1px;
}
.sf-menu a {
padding: .75em 1em;
text-decoration:none;
}
.sf-menu a, .sf-menu a:visited { /* visited pseudo selector so IE6 applies text colour*/
color: #bbbbbb;
/*font-weight: bold;*/
}
.sf-menu li {
}
.sf-menu li li {
background: url("img/sub-menu-center.png") repeat-y transparent;
float: left;
}
.sf-menu .sub-menu {
margin-top: -26px;
padding-top: 17px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
z-index: 99999;
}
.sf-menu .sub-menu li{}
.sf-menu .sub-menu li a{
color: #4e4d4c!important;
margin: 5px 15px 5px 16px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(153, 153, 153, 0.28);
}
.sf-menu .sub-menu li:last-child a {border: none}
.sf-menu .sub-menu li:first-child a {margin-top: 10px}
.sf-menu .sub-menu li:last-child {
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
border-bottom: 1px solid rgba(0, 0, 0, 0.21);
}
.sf-menu .sub-menu-last ul li a{
border-bottom: 1px solid #e9e8e8!important;
padding: 0.7em 0;
width: 94%;
}
.sf-menu .sub-menu-last ul li a.sub-sub-menu-last{border-bottom:0px solid #fff!important;}
.sf-menu li li li {}
.sf-menu li:hover, .sf-menu li.sfHover,
.sf-menu a:focus, .sf-menu a:hover, .sf-menu a:active {
color: #fff;
outline: 0;
}
.sf-menu .sub-menu a:hover{
color:#ff6825!important;
outline: 0;
background: none!important;
}
.sf-menu .sub-menu li:hover{}
/*** arrows **/
.sf-menu a.sf-with-ul {
min-width: 1px; /* trigger IE7 hasLayout so spans position accurately */
}
.sf-sub-indicator {
position: absolute;
display: block;
right: .75em;
top: 1.05em; /* IE6 only */
width: 10px;
height: 10px;
text-indent: -999em;
overflow: hidden;
}
a > .sf-sub-indicator { /* give all except IE6 the correct values */
top: .8em;
background-position: 0 -100px; /* use translucent arrow for modern browsers*/
}
/* apply hovers to modern browsers */
a:focus > .sf-sub-indicator,
a:hover > .sf-sub-indicator,
a:active > .sf-sub-indicator,
li:hover > a > .sf-sub-indicator,
li.sfHover > a > .sf-sub-indicator {
background-position: -10px -100px; /* arrow hovers for modern browsers*/
}
/* point right for anchors in subs */
.sf-menu ul .sf-sub-indicator { background-position: -10px 0; }
.sf-menu ul a > .sf-sub-indicator { background-position: 0 0; }
/* apply hovers to modern browsers */
.sf-menu ul a:focus > .sf-sub-indicator,
.sf-menu ul a:hover > .sf-sub-indicator,
.sf-menu ul a:active > .sf-sub-indicator,
.sf-menu ul li:hover > a > .sf-sub-indicator,
.sf-menu ul li.sfHover > a > .sf-sub-indicator {
background-position: -10px 0; /* arrow hovers for modern browsers*/
}
/*** shadows for all but IE6 ***/
.sf-shadow ul { margin: 5px 0 0 0; }
.sf-shadow ul.sf-shadow-off {
background: transparent;
}
/*--- TOP, BOTTOM SUB-MENU --*/
.sub-menu-top{
background: url("img/sub-menu-top.png") no-repeat transparent;
float: left;
height: 3px;
width: 191px;
}
.sub-menu-bottom{
background: url("img/sub-menu-bottom.png") no-repeat transparent;
float: left;
height: 8px;
width: 191px;
}
| ajyn17/wp-khouse | wp-content/themes/eventor/script/menu/superfish.css | CSS | gpl-2.0 | 4,259 |
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "acresrc.h"
#define _COMPONENT ACPI_RESOURCES
ACPI_MODULE_NAME("rsutils")
u8 acpi_rs_decode_bitmask(u16 mask, u8 * list)
{
u8 i;
u8 bit_count;
ACPI_FUNCTION_ENTRY();
/* Decode the mask bits */
for (i = 0, bit_count = 0; mask; i++) {
if (mask & 0x0001) {
list[bit_count] = i;
bit_count++;
}
mask >>= 1;
}
return (bit_count);
}
u16 acpi_rs_encode_bitmask(u8 * list, u8 count)
{
u32 i;
u16 mask;
ACPI_FUNCTION_ENTRY();
/* Encode the list into a single bitmask */
for (i = 0, mask = 0; i < count; i++) {
mask |= (0x1 << list[i]);
}
return mask;
}
void
acpi_rs_move_data(void *destination, void *source, u16 item_count, u8 move_type)
{
u32 i;
ACPI_FUNCTION_ENTRY();
/* One move per item */
for (i = 0; i < item_count; i++) {
switch (move_type) {
/*
* For the 8-bit case, we can perform the move all at once
* since there are no alignment or endian issues
*/
case ACPI_RSC_MOVE8:
ACPI_MEMCPY(destination, source, item_count);
return;
/*
* 16-, 32-, and 64-bit cases must use the move macros that perform
* endian conversion and/or accomodate hardware that cannot perform
* misaligned memory transfers
*/
case ACPI_RSC_MOVE16:
ACPI_MOVE_16_TO_16(&ACPI_CAST_PTR(u16, destination)[i],
&ACPI_CAST_PTR(u16, source)[i]);
break;
case ACPI_RSC_MOVE32:
ACPI_MOVE_32_TO_32(&ACPI_CAST_PTR(u32, destination)[i],
&ACPI_CAST_PTR(u32, source)[i]);
break;
case ACPI_RSC_MOVE64:
ACPI_MOVE_64_TO_64(&ACPI_CAST_PTR(u64, destination)[i],
&ACPI_CAST_PTR(u64, source)[i]);
break;
default:
return;
}
}
}
void
acpi_rs_set_resource_length(acpi_rsdesc_size total_length,
union aml_resource *aml)
{
acpi_rs_length resource_length;
ACPI_FUNCTION_ENTRY();
/* Length is the total descriptor length minus the header length */
resource_length = (acpi_rs_length)
(total_length - acpi_ut_get_resource_header_length(aml));
/* Length is stored differently for large and small descriptors */
if (aml->small_header.descriptor_type & ACPI_RESOURCE_NAME_LARGE) {
/* Large descriptor -- bytes 1-2 contain the 16-bit length */
ACPI_MOVE_16_TO_16(&aml->large_header.resource_length,
&resource_length);
} else {
/* Small descriptor -- bits 2:0 of byte 0 contain the length */
aml->small_header.descriptor_type = (u8)
/* Clear any existing length, preserving descriptor type bits */
((aml->small_header.
descriptor_type & ~ACPI_RESOURCE_NAME_SMALL_LENGTH_MASK)
| resource_length);
}
}
void
acpi_rs_set_resource_header(u8 descriptor_type,
acpi_rsdesc_size total_length,
union aml_resource *aml)
{
ACPI_FUNCTION_ENTRY();
/* Set the Resource Type */
aml->small_header.descriptor_type = descriptor_type;
/* Set the Resource Length */
acpi_rs_set_resource_length(total_length, aml);
}
static u16 acpi_rs_strcpy(char *destination, char *source)
{
u16 i;
ACPI_FUNCTION_ENTRY();
for (i = 0; source[i]; i++) {
destination[i] = source[i];
}
destination[i] = 0;
/* Return string length including the NULL terminator */
return ((u16) (i + 1));
}
acpi_rs_length
acpi_rs_get_resource_source(acpi_rs_length resource_length,
acpi_rs_length minimum_length,
struct acpi_resource_source * resource_source,
union aml_resource * aml, char *string_ptr)
{
acpi_rsdesc_size total_length;
u8 *aml_resource_source;
ACPI_FUNCTION_ENTRY();
total_length =
resource_length + sizeof(struct aml_resource_large_header);
aml_resource_source = ACPI_ADD_PTR(u8, aml, minimum_length);
/*
* resource_source is present if the length of the descriptor is longer than
* the minimum length.
*
* Note: Some resource descriptors will have an additional null, so
* we add 1 to the minimum length.
*/
if (total_length > (acpi_rsdesc_size) (minimum_length + 1)) {
/* Get the resource_source_index */
resource_source->index = aml_resource_source[0];
resource_source->string_ptr = string_ptr;
if (!string_ptr) {
/*
* String destination pointer is not specified; Set the String
* pointer to the end of the current resource_source structure.
*/
resource_source->string_ptr =
ACPI_ADD_PTR(char, resource_source,
sizeof(struct acpi_resource_source));
}
/*
* In order for the Resource length to be a multiple of the native
* word, calculate the length of the string (+1 for NULL terminator)
* and expand to the next word multiple.
*
* Zero the entire area of the buffer.
*/
total_length = (u32)
ACPI_STRLEN(ACPI_CAST_PTR(char, &aml_resource_source[1])) + 1;
total_length = (u32) ACPI_ROUND_UP_TO_NATIVE_WORD(total_length);
ACPI_MEMSET(resource_source->string_ptr, 0, total_length);
/* Copy the resource_source string to the destination */
resource_source->string_length =
acpi_rs_strcpy(resource_source->string_ptr,
ACPI_CAST_PTR(char,
&aml_resource_source[1]));
return ((acpi_rs_length) total_length);
}
/* resource_source is not present */
resource_source->index = 0;
resource_source->string_length = 0;
resource_source->string_ptr = NULL;
return (0);
}
acpi_rsdesc_size
acpi_rs_set_resource_source(union aml_resource * aml,
acpi_rs_length minimum_length,
struct acpi_resource_source * resource_source)
{
u8 *aml_resource_source;
acpi_rsdesc_size descriptor_length;
ACPI_FUNCTION_ENTRY();
descriptor_length = minimum_length;
/* Non-zero string length indicates presence of a resource_source */
if (resource_source->string_length) {
/* Point to the end of the AML descriptor */
aml_resource_source = ACPI_ADD_PTR(u8, aml, minimum_length);
/* Copy the resource_source_index */
aml_resource_source[0] = (u8) resource_source->index;
/* Copy the resource_source string */
ACPI_STRCPY(ACPI_CAST_PTR(char, &aml_resource_source[1]),
resource_source->string_ptr);
/*
* Add the length of the string (+ 1 for null terminator) to the
* final descriptor length
*/
descriptor_length +=
((acpi_rsdesc_size) resource_source->string_length + 1);
}
/* Return the new total length of the AML descriptor */
return (descriptor_length);
}
acpi_status
acpi_rs_get_prt_method_data(struct acpi_namespace_node * node,
struct acpi_buffer * ret_buffer)
{
union acpi_operand_object *obj_desc;
acpi_status status;
ACPI_FUNCTION_TRACE(rs_get_prt_method_data);
/* Parameters guaranteed valid by caller */
/* Execute the method, no parameters */
status = acpi_ut_evaluate_object(node, METHOD_NAME__PRT,
ACPI_BTYPE_PACKAGE, &obj_desc);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Create a resource linked list from the byte stream buffer that comes
* back from the _CRS method execution.
*/
status = acpi_rs_create_pci_routing_table(obj_desc, ret_buffer);
/* On exit, we must delete the object returned by evaluate_object */
acpi_ut_remove_reference(obj_desc);
return_ACPI_STATUS(status);
}
acpi_status
acpi_rs_get_crs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer)
{
union acpi_operand_object *obj_desc;
acpi_status status;
ACPI_FUNCTION_TRACE(rs_get_crs_method_data);
/* Parameters guaranteed valid by caller */
/* Execute the method, no parameters */
status = acpi_ut_evaluate_object(node, METHOD_NAME__CRS,
ACPI_BTYPE_BUFFER, &obj_desc);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Make the call to create a resource linked list from the
* byte stream buffer that comes back from the _CRS method
* execution.
*/
status = acpi_rs_create_resource_list(obj_desc, ret_buffer);
/* On exit, we must delete the object returned by evaluate_object */
acpi_ut_remove_reference(obj_desc);
return_ACPI_STATUS(status);
}
#ifdef ACPI_FUTURE_USAGE
acpi_status
acpi_rs_get_prs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer)
{
union acpi_operand_object *obj_desc;
acpi_status status;
ACPI_FUNCTION_TRACE(rs_get_prs_method_data);
/* Parameters guaranteed valid by caller */
/* Execute the method, no parameters */
status = acpi_ut_evaluate_object(node, METHOD_NAME__PRS,
ACPI_BTYPE_BUFFER, &obj_desc);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Make the call to create a resource linked list from the
* byte stream buffer that comes back from the _CRS method
* execution.
*/
status = acpi_rs_create_resource_list(obj_desc, ret_buffer);
/* On exit, we must delete the object returned by evaluate_object */
acpi_ut_remove_reference(obj_desc);
return_ACPI_STATUS(status);
}
#endif /* ACPI_FUTURE_USAGE */
acpi_status
acpi_rs_get_method_data(acpi_handle handle,
char *path, struct acpi_buffer *ret_buffer)
{
union acpi_operand_object *obj_desc;
acpi_status status;
ACPI_FUNCTION_TRACE(rs_get_method_data);
/* Parameters guaranteed valid by caller */
/* Execute the method, no parameters */
status =
acpi_ut_evaluate_object(handle, path, ACPI_BTYPE_BUFFER, &obj_desc);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Make the call to create a resource linked list from the
* byte stream buffer that comes back from the method
* execution.
*/
status = acpi_rs_create_resource_list(obj_desc, ret_buffer);
/* On exit, we must delete the object returned by evaluate_object */
acpi_ut_remove_reference(obj_desc);
return_ACPI_STATUS(status);
}
acpi_status
acpi_rs_set_srs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *in_buffer)
{
struct acpi_evaluate_info *info;
union acpi_operand_object *args[2];
acpi_status status;
struct acpi_buffer buffer;
ACPI_FUNCTION_TRACE(rs_set_srs_method_data);
/* Allocate and initialize the evaluation information block */
info = ACPI_ALLOCATE_ZEROED(sizeof(struct acpi_evaluate_info));
if (!info) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
info->prefix_node = node;
info->pathname = METHOD_NAME__SRS;
info->parameters = args;
info->flags = ACPI_IGNORE_RETURN_VALUE;
/*
* The in_buffer parameter will point to a linked list of
* resource parameters. It needs to be formatted into a
* byte stream to be sent in as an input parameter to _SRS
*
* Convert the linked list into a byte stream
*/
buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
status = acpi_rs_create_aml_resources(in_buffer->pointer, &buffer);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
/* Create and initialize the method parameter object */
args[0] = acpi_ut_create_internal_object(ACPI_TYPE_BUFFER);
if (!args[0]) {
/*
* Must free the buffer allocated above (otherwise it is freed
* later)
*/
ACPI_FREE(buffer.pointer);
status = AE_NO_MEMORY;
goto cleanup;
}
args[0]->buffer.length = (u32) buffer.length;
args[0]->buffer.pointer = buffer.pointer;
args[0]->common.flags = AOPOBJ_DATA_VALID;
args[1] = NULL;
/* Execute the method, no return value is expected */
status = acpi_ns_evaluate(info);
/* Clean up and return the status from acpi_ns_evaluate */
acpi_ut_remove_reference(args[0]);
cleanup:
ACPI_FREE(info);
return_ACPI_STATUS(status);
}
| luckasfb/OT_903D-kernel-2.6.35.7 | kernel/drivers/acpi/acpica/rsutils.c | C | gpl-2.0 | 11,290 |
/* drivers/i2c/chips/lis3dh.c - LIS3DH motion sensor driver
*
*
*
* 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/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/miscdevice.h>
#include <asm/uaccess.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/kobject.h>
#include <linux/earlysuspend.h>
#include <linux/platform_device.h>
#include <asm/atomic.h>
#include <cust_acc.h>
#include <linux/hwmsensor.h>
#include <linux/hwmsen_dev.h>
#include <linux/sensors_io.h>
#include "lis3dh.h"
#include <linux/hwmsen_helper.h>
#include <mach/mt_devs.h>
#include <mach/mt_typedefs.h>
#include <mach/mt_gpio.h>
#include <mach/mt_pm_ldo.h>
#define POWER_NONE_MACRO MT65XX_POWER_NONE
/*----------------------------------------------------------------------------*/
//#define I2C_DRIVERID_LIS3DH 345
/*----------------------------------------------------------------------------*/
#define DEBUG 1
/*----------------------------------------------------------------------------*/
#define CONFIG_LIS3DH_LOWPASS /*apply low pass filter on output*/
/*----------------------------------------------------------------------------*/
#define LIS3DH_AXIS_X 0
#define LIS3DH_AXIS_Y 1
#define LIS3DH_AXIS_Z 2
#define LIS3DH_AXES_NUM 3
#define LIS3DH_DATA_LEN 6
#define LIS3DH_DEV_NAME "LIS3DH"
/*----------------------------------------------------------------------------*/
static const struct i2c_device_id lis3dh_i2c_id[] = {{LIS3DH_DEV_NAME,0},{}};
/*the adapter id will be available in customization*/
static struct i2c_board_info __initdata i2c_LIS3DH={ I2C_BOARD_INFO("LIS3DH", (0x32>>1))};
//static unsigned short lis3dh_force[] = {0x00, LIS3DH_I2C_SLAVE_ADDR, I2C_CLIENT_END, I2C_CLIENT_END};
//static const unsigned short *const lis3dh_forces[] = { lis3dh_force, NULL };
//static struct i2c_client_address_data lis3dh_addr_data = { .forces = lis3dh_forces,};
/*----------------------------------------------------------------------------*/
static int lis3dh_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id);
static int lis3dh_i2c_remove(struct i2c_client *client);
//static int lis3dh_i2c_detect(struct i2c_client *client, int kind, struct i2c_board_info *info);
static int lis3dh_local_init(void);
static int lis3dh_remove(void);
static int lis3dh_init_flag =0; // 0<==>OK -1 <==> fail
/*----------------------------------------------------------------------------*/
typedef enum {
ADX_TRC_FILTER = 0x01,
ADX_TRC_RAWDATA = 0x02,
ADX_TRC_IOCTL = 0x04,
ADX_TRC_CALI = 0X08,
ADX_TRC_INFO = 0X10,
} ADX_TRC;
/*----------------------------------------------------------------------------*/
struct scale_factor{
u8 whole;
u8 fraction;
};
/*----------------------------------------------------------------------------*/
struct data_resolution {
struct scale_factor scalefactor;
int sensitivity;
};
/*----------------------------------------------------------------------------*/
#define C_MAX_FIR_LENGTH (32)
/*----------------------------------------------------------------------------*/
struct data_filter {
s16 raw[C_MAX_FIR_LENGTH][LIS3DH_AXES_NUM];
int sum[LIS3DH_AXES_NUM];
int num;
int idx;
};
/*----------------------------------------------------------------------------*/
static struct sensor_init_info lis3dh_init_info = {
.name = "lis3dh",
.init = lis3dh_local_init,
.uninit = lis3dh_remove,
};
/*----------------------------------------------------------------------------*/
struct lis3dh_i2c_data {
struct i2c_client *client;
struct acc_hw *hw;
struct hwmsen_convert cvt;
/*misc*/
struct data_resolution *reso;
atomic_t trace;
atomic_t suspend;
atomic_t selftest;
atomic_t filter;
s16 cali_sw[LIS3DH_AXES_NUM+1];
/*data*/
s8 offset[LIS3DH_AXES_NUM+1]; /*+1: for 4-byte alignment*/
s16 data[LIS3DH_AXES_NUM+1];
#if defined(CONFIG_LIS3DH_LOWPASS)
atomic_t firlen;
atomic_t fir_en;
struct data_filter fir;
#endif
/*early suspend*/
#if defined(CONFIG_HAS_EARLYSUSPEND)
struct early_suspend early_drv;
#endif
};
/*----------------------------------------------------------------------------*/
static struct i2c_driver lis3dh_i2c_driver = {
.driver = {
// .owner = THIS_MODULE,
.name = LIS3DH_DEV_NAME,
},
.probe = lis3dh_i2c_probe,
.remove = lis3dh_i2c_remove,
// .detect = lis3dh_i2c_detect,
#if !defined(CONFIG_HAS_EARLYSUSPEND)
.suspend = lis3dh_suspend,
.resume = lis3dh_resume,
#endif
.id_table = lis3dh_i2c_id,
// .address_data = &lis3dh_addr_data,
};
/*----------------------------------------------------------------------------*/
static struct i2c_client *lis3dh_i2c_client = NULL;
//static struct platform_driver lis3dh_gsensor_driver;
static struct lis3dh_i2c_data *obj_i2c_data = NULL;
static bool sensor_power = false;
static GSENSOR_VECTOR3D gsensor_gain, gsensor_offset;
//static char selftestRes[10] = {0};
/*----------------------------------------------------------------------------*/
#define GSE_TAG "[Gsensor] "
#define GSE_FUN(f) printk(KERN_INFO GSE_TAG"%s\n", __FUNCTION__)
#define GSE_ERR(fmt, args...) printk(KERN_ERR GSE_TAG"%s %d : "fmt, __FUNCTION__, __LINE__, ##args)
#define GSE_LOG(fmt, args...) printk(KERN_INFO GSE_TAG fmt, ##args)
/*----------------------------------------------------------------------------*/
static struct data_resolution lis3dh_data_resolution[] = {
/* combination by {FULL_RES,RANGE}*/
{{ 1, 0}, 1024}, // dataformat +/-2g in 12-bit resolution; { 1, 0} = 1.0 = (2*2*1000)/(2^12); 1024 = (2^12)/(2*2)
{{ 1, 9}, 512}, // dataformat +/-4g in 12-bit resolution; { 1, 9} = 1.9 = (2*4*1000)/(2^12); 512 = (2^12)/(2*4)
{{ 3, 9}, 256}, // dataformat +/-8g in 12-bit resolution; { 1, 0} = 1.0 = (2*8*1000)/(2^12); 1024 = (2^12)/(2*8)
};
/*----------------------------------------------------------------------------*/
static struct data_resolution lis3dh_offset_resolution = {{15, 6}, 64};
/*
static int hwmsen_read_byte_sr(struct i2c_client *client, u8 addr, u8 *data)
{
u8 buf;
int ret = 0;
client->addr = client->addr& I2C_MASK_FLAG | I2C_WR_FLAG |I2C_RS_FLAG;
buf = addr;
ret = i2c_master_send(client, (const char*)&buf, 1<<8 | 1);
//ret = i2c_master_send(client, (const char*)&buf, 1);
if (ret < 0) {
GSE_ERR("send command error!!\n");
return -EFAULT;
}
*data = buf;
client->addr = client->addr& I2C_MASK_FLAG;
return 0;
}
*/
static void dumpReg(struct i2c_client *client)
{
int i=0;
u8 addr = 0x20;
u8 regdata=0;
for(i=0; i<3 ; i++)
{
//dump all
hwmsen_read_byte(client,addr,®data);
GSE_LOG("Reg addr=%x regdata=%x\n",addr,regdata);
addr++;
}
}
/*--------------------ADXL power control function----------------------------------*/
static void LIS3DH_power(struct acc_hw *hw, unsigned int on)
{
static unsigned int power_on = 0;
if(hw->power_id != POWER_NONE_MACRO) // have externel LDO
{
GSE_LOG("power %s\n", on ? "on" : "off");
if(power_on == on) // power status not change
{
GSE_LOG("ignore power control: %d\n", on);
}
else if(on) // power on
{
if(!hwPowerOn(hw->power_id, hw->power_vol, "LIS3DH"))
{
GSE_ERR("power on fails!!\n");
}
}
else // power off
{
if (!hwPowerDown(hw->power_id, "LIS3DH"))
{
GSE_ERR("power off fail!!\n");
}
}
}
power_on = on;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_SetDataResolution(struct lis3dh_i2c_data *obj)
{
int err = 0;
u8 dat, reso;
err = hwmsen_read_byte(obj->client, LIS3DH_REG_CTL_REG4, &dat);
if(err)
{
GSE_ERR("write data format fail!!\n");
return err;
}
/*the data_reso is combined by 3 bits: {FULL_RES, DATA_RANGE}*/
reso = (dat & 0x30)<<4;
if(reso >= 0x3)
reso = 0x2;
if(reso < sizeof(lis3dh_data_resolution)/sizeof(lis3dh_data_resolution[0]))
{
obj->reso = &lis3dh_data_resolution[reso];
return 0;
}
else
{
return -EINVAL;
}
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_ReadData(struct i2c_client *client, s16 data[LIS3DH_AXES_NUM])
{
struct lis3dh_i2c_data *priv = i2c_get_clientdata(client);
// u8 addr = LIS3DH_REG_DATAX0;
u8 buf[LIS3DH_DATA_LEN] = {0};
int err = 0;
if(NULL == client)
{
err = -EINVAL;
}
else
{
if(hwmsen_read_block(client, LIS3DH_REG_OUT_X, buf, 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
if(hwmsen_read_block(client, LIS3DH_REG_OUT_X+1, &buf[1], 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
data[LIS3DH_AXIS_X] = (s16)((buf[0]+(buf[1]<<8))>>4);
if(hwmsen_read_block(client, LIS3DH_REG_OUT_Y, &buf[2], 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
if(hwmsen_read_block(client, LIS3DH_REG_OUT_Y+1, &buf[3], 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
data[LIS3DH_AXIS_Y] = (s16)((s16)(buf[2] +( buf[3]<<8))>>4);
if(hwmsen_read_block(client, LIS3DH_REG_OUT_Z, &buf[4], 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
if(hwmsen_read_block(client, LIS3DH_REG_OUT_Z+1, &buf[5], 0x01))
{
GSE_ERR("read G sensor data register err!\n");
return -1;
}
data[LIS3DH_AXIS_Z] =(s16)((buf[4]+(buf[5]<<8))>>4);
//GSE_LOG("[%08X %08X %08X %08x %08x %08x]\n",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]);
data[LIS3DH_AXIS_X] &= 0xfff;
data[LIS3DH_AXIS_Y] &= 0xfff;
data[LIS3DH_AXIS_Z] &= 0xfff;
if(atomic_read(&priv->trace) & ADX_TRC_RAWDATA)
{
GSE_LOG("[%08X %08X %08X] => [%5d %5d %5d]\n", data[LIS3DH_AXIS_X], data[LIS3DH_AXIS_Y], data[LIS3DH_AXIS_Z],
data[LIS3DH_AXIS_X], data[LIS3DH_AXIS_Y], data[LIS3DH_AXIS_Z]);
}
if(data[LIS3DH_AXIS_X]&0x800)
{
data[LIS3DH_AXIS_X] = ~data[LIS3DH_AXIS_X];
data[LIS3DH_AXIS_X] &= 0xfff;
data[LIS3DH_AXIS_X]+=1;
data[LIS3DH_AXIS_X] = -data[LIS3DH_AXIS_X];
}
if(data[LIS3DH_AXIS_Y]&0x800)
{
data[LIS3DH_AXIS_Y] = ~data[LIS3DH_AXIS_Y];
data[LIS3DH_AXIS_Y] &= 0xfff;
data[LIS3DH_AXIS_Y]+=1;
data[LIS3DH_AXIS_Y] = -data[LIS3DH_AXIS_Y];
}
if(data[LIS3DH_AXIS_Z]&0x800)
{
data[LIS3DH_AXIS_Z] = ~data[LIS3DH_AXIS_Z];
data[LIS3DH_AXIS_Z] &= 0xfff;
data[LIS3DH_AXIS_Z]+=1;
data[LIS3DH_AXIS_Z] = -data[LIS3DH_AXIS_Z];
}
if(atomic_read(&priv->trace) & ADX_TRC_RAWDATA)
{
GSE_LOG("[%08X %08X %08X] => [%5d %5d %5d] after\n", data[LIS3DH_AXIS_X], data[LIS3DH_AXIS_Y], data[LIS3DH_AXIS_Z],
data[LIS3DH_AXIS_X], data[LIS3DH_AXIS_Y], data[LIS3DH_AXIS_Z]);
}
#ifdef CONFIG_LIS3DH_LOWPASS
if(atomic_read(&priv->filter))
{
if(atomic_read(&priv->fir_en) && !atomic_read(&priv->suspend))
{
int idx, firlen = atomic_read(&priv->firlen);
if(priv->fir.num < firlen)
{
priv->fir.raw[priv->fir.num][LIS3DH_AXIS_X] = data[LIS3DH_AXIS_X];
priv->fir.raw[priv->fir.num][LIS3DH_AXIS_Y] = data[LIS3DH_AXIS_Y];
priv->fir.raw[priv->fir.num][LIS3DH_AXIS_Z] = data[LIS3DH_AXIS_Z];
priv->fir.sum[LIS3DH_AXIS_X] += data[LIS3DH_AXIS_X];
priv->fir.sum[LIS3DH_AXIS_Y] += data[LIS3DH_AXIS_Y];
priv->fir.sum[LIS3DH_AXIS_Z] += data[LIS3DH_AXIS_Z];
if(atomic_read(&priv->trace) & ADX_TRC_FILTER)
{
GSE_LOG("add [%2d] [%5d %5d %5d] => [%5d %5d %5d]\n", priv->fir.num,
priv->fir.raw[priv->fir.num][LIS3DH_AXIS_X], priv->fir.raw[priv->fir.num][LIS3DH_AXIS_Y], priv->fir.raw[priv->fir.num][LIS3DH_AXIS_Z],
priv->fir.sum[LIS3DH_AXIS_X], priv->fir.sum[LIS3DH_AXIS_Y], priv->fir.sum[LIS3DH_AXIS_Z]);
}
priv->fir.num++;
priv->fir.idx++;
}
else
{
idx = priv->fir.idx % firlen;
priv->fir.sum[LIS3DH_AXIS_X] -= priv->fir.raw[idx][LIS3DH_AXIS_X];
priv->fir.sum[LIS3DH_AXIS_Y] -= priv->fir.raw[idx][LIS3DH_AXIS_Y];
priv->fir.sum[LIS3DH_AXIS_Z] -= priv->fir.raw[idx][LIS3DH_AXIS_Z];
priv->fir.raw[idx][LIS3DH_AXIS_X] = data[LIS3DH_AXIS_X];
priv->fir.raw[idx][LIS3DH_AXIS_Y] = data[LIS3DH_AXIS_Y];
priv->fir.raw[idx][LIS3DH_AXIS_Z] = data[LIS3DH_AXIS_Z];
priv->fir.sum[LIS3DH_AXIS_X] += data[LIS3DH_AXIS_X];
priv->fir.sum[LIS3DH_AXIS_Y] += data[LIS3DH_AXIS_Y];
priv->fir.sum[LIS3DH_AXIS_Z] += data[LIS3DH_AXIS_Z];
priv->fir.idx++;
data[LIS3DH_AXIS_X] = priv->fir.sum[LIS3DH_AXIS_X]/firlen;
data[LIS3DH_AXIS_Y] = priv->fir.sum[LIS3DH_AXIS_Y]/firlen;
data[LIS3DH_AXIS_Z] = priv->fir.sum[LIS3DH_AXIS_Z]/firlen;
if(atomic_read(&priv->trace) & ADX_TRC_FILTER)
{
GSE_LOG("add [%2d] [%5d %5d %5d] => [%5d %5d %5d] : [%5d %5d %5d]\n", idx,
priv->fir.raw[idx][LIS3DH_AXIS_X], priv->fir.raw[idx][LIS3DH_AXIS_Y], priv->fir.raw[idx][LIS3DH_AXIS_Z],
priv->fir.sum[LIS3DH_AXIS_X], priv->fir.sum[LIS3DH_AXIS_Y], priv->fir.sum[LIS3DH_AXIS_Z],
data[LIS3DH_AXIS_X], data[LIS3DH_AXIS_Y], data[LIS3DH_AXIS_Z]);
}
}
}
}
#endif
}
return err;
}
/*----------------------------------------------------------------------------*/
/*
static int LIS3DH_ReadOffset(struct i2c_client *client, s8 ofs[LIS3DH_AXES_NUM])
{
int err;
return err;
}
*/
/*----------------------------------------------------------------------------*/
static int LIS3DH_ResetCalibration(struct i2c_client *client)
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
memset(obj->cali_sw, 0x00, sizeof(obj->cali_sw));
return 0;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_ReadCalibration(struct i2c_client *client, int dat[LIS3DH_AXES_NUM])
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
dat[obj->cvt.map[LIS3DH_AXIS_X]] = obj->cvt.sign[LIS3DH_AXIS_X]*obj->cali_sw[LIS3DH_AXIS_X];
dat[obj->cvt.map[LIS3DH_AXIS_Y]] = obj->cvt.sign[LIS3DH_AXIS_Y]*obj->cali_sw[LIS3DH_AXIS_Y];
dat[obj->cvt.map[LIS3DH_AXIS_Z]] = obj->cvt.sign[LIS3DH_AXIS_Z]*obj->cali_sw[LIS3DH_AXIS_Z];
return 0;
}
/*----------------------------------------------------------------------------*/
/*
static int LIS3DH_ReadCalibrationEx(struct i2c_client *client, int act[LIS3DH_AXES_NUM], int raw[LIS3DH_AXES_NUM])
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
int err;
int mul;
if(err = LIS3DH_ReadOffset(client, obj->offset))
{
GSE_ERR("read offset fail, %d\n", err);
return err;
}
mul = obj->reso->sensitivity/lis3dh_offset_resolution.sensitivity;
raw[LIS3DH_AXIS_X] = obj->offset[LIS3DH_AXIS_X]*mul + obj->cali_sw[LIS3DH_AXIS_X];
raw[LIS3DH_AXIS_Y] = obj->offset[LIS3DH_AXIS_Y]*mul + obj->cali_sw[LIS3DH_AXIS_Y];
raw[LIS3DH_AXIS_Z] = obj->offset[LIS3DH_AXIS_Z]*mul + obj->cali_sw[LIS3DH_AXIS_Z];
act[obj->cvt.map[LIS3DH_AXIS_X]] = obj->cvt.sign[LIS3DH_AXIS_X]*raw[LIS3DH_AXIS_X];
act[obj->cvt.map[LIS3DH_AXIS_Y]] = obj->cvt.sign[LIS3DH_AXIS_Y]*raw[LIS3DH_AXIS_Y];
act[obj->cvt.map[LIS3DH_AXIS_Z]] = obj->cvt.sign[LIS3DH_AXIS_Z]*raw[LIS3DH_AXIS_Z];
return 0;
}
*/
/*----------------------------------------------------------------------------*/
static int LIS3DH_WriteCalibration(struct i2c_client *client, int dat[LIS3DH_AXES_NUM])
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
int err = 0;
// int cali[LIS3DH_AXES_NUM];
GSE_FUN();
if(!obj || ! dat)
{
GSE_ERR("null ptr!!\n");
return -EINVAL;
}
else
{
s16 cali[LIS3DH_AXES_NUM];
cali[obj->cvt.map[LIS3DH_AXIS_X]] = obj->cvt.sign[LIS3DH_AXIS_X]*obj->cali_sw[LIS3DH_AXIS_X];
cali[obj->cvt.map[LIS3DH_AXIS_Y]] = obj->cvt.sign[LIS3DH_AXIS_Y]*obj->cali_sw[LIS3DH_AXIS_Y];
cali[obj->cvt.map[LIS3DH_AXIS_Z]] = obj->cvt.sign[LIS3DH_AXIS_Z]*obj->cali_sw[LIS3DH_AXIS_Z];
cali[LIS3DH_AXIS_X] += dat[LIS3DH_AXIS_X];
cali[LIS3DH_AXIS_Y] += dat[LIS3DH_AXIS_Y];
cali[LIS3DH_AXIS_Z] += dat[LIS3DH_AXIS_Z];
obj->cali_sw[LIS3DH_AXIS_X] += obj->cvt.sign[LIS3DH_AXIS_X]*dat[obj->cvt.map[LIS3DH_AXIS_X]];
obj->cali_sw[LIS3DH_AXIS_Y] += obj->cvt.sign[LIS3DH_AXIS_Y]*dat[obj->cvt.map[LIS3DH_AXIS_Y]];
obj->cali_sw[LIS3DH_AXIS_Z] += obj->cvt.sign[LIS3DH_AXIS_Z]*dat[obj->cvt.map[LIS3DH_AXIS_Z]];
}
return err;
}
/*----------------------------------------------------------------------------*/
#if 0
static int LIS3DH_CheckDeviceID(struct i2c_client *client)
{
u8 databuf[10];
int res = 0;
/*
memset(databuf, 0, sizeof(u8)*10);
databuf[0] = LIS3DH_REG_DEVID;
res = i2c_master_send(client, databuf, 0x1);
if(res <= 0)
{
goto exit_LIS3DH_CheckDeviceID;
}
udelay(500);
databuf[0] = 0x0;
res = i2c_master_recv(client, databuf, 0x01);
if(res <= 0)
{
goto exit_LIS3DH_CheckDeviceID;
}
if(databuf[0]!=LIS3DH_FIXED_DEVID)
{
return LIS3DH_ERR_IDENTIFICATION;
}
exit_LIS3DH_CheckDeviceID:
if (res <= 0)
{
return LIS3DH_ERR_I2C;
}
*/
return LIS3DH_SUCCESS;
}
#endif
/*----------------------------------------------------------------------------*/
static int LIS3DH_SetPowerMode(struct i2c_client *client, bool enable)
{
u8 databuf[2];
int res = 0;
u8 addr = LIS3DH_REG_CTL_REG1;
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
if(enable == sensor_power)
{
GSE_LOG("Sensor power status is newest!\n");
return LIS3DH_SUCCESS;
}
if(hwmsen_read_byte(client, addr, &databuf[0]))
{
GSE_ERR("read power ctl register err!\n");
return LIS3DH_ERR_I2C;
}
databuf[0] &= ~LIS3DH_MEASURE_MODE;
if(enable == TRUE)
{
databuf[0] &= ~LIS3DH_MEASURE_MODE;
}
else
{
databuf[0] |= LIS3DH_MEASURE_MODE;
}
databuf[1] = databuf[0];
databuf[0] = LIS3DH_REG_CTL_REG1;
res = i2c_master_send(client, databuf, 0x2);
if(res <= 0)
{
GSE_LOG("set power mode failed!\n");
return LIS3DH_ERR_I2C;
}
else if(atomic_read(&obj->trace) & ADX_TRC_INFO)
{
GSE_LOG("set power mode ok %d!\n", databuf[1]);
}
sensor_power = enable;
return LIS3DH_SUCCESS;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_SetDataFormat(struct i2c_client *client, u8 dataformat)
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
u8 databuf[10];
u8 addr = LIS3DH_REG_CTL_REG4;
int res = 0;
memset(databuf, 0, sizeof(u8)*10);
if(hwmsen_read_byte(client, addr, &databuf[0]))
{
GSE_ERR("read reg_ctl_reg1 register err!\n");
return LIS3DH_ERR_I2C;
}
databuf[0] &= ~0x30;
databuf[0] |=dataformat;
databuf[1] = databuf[0];
databuf[0] = LIS3DH_REG_CTL_REG4;
res = i2c_master_send(client, databuf, 0x2);
if(res <= 0)
{
return LIS3DH_ERR_I2C;
}
return LIS3DH_SetDataResolution(obj);
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_SetBWRate(struct i2c_client *client, u8 bwrate)
{
u8 databuf[10];
u8 addr = LIS3DH_REG_CTL_REG1;
int res = 0;
memset(databuf, 0, sizeof(u8)*10);
if(hwmsen_read_byte(client, addr, &databuf[0]))
{
GSE_ERR("read reg_ctl_reg1 register err!\n");
return LIS3DH_ERR_I2C;
}
databuf[0] &= ~0xF0;
databuf[0] |= bwrate;
databuf[1] = databuf[0];
databuf[0] = LIS3DH_REG_CTL_REG1;
res = i2c_master_send(client, databuf, 0x2);
if(res <= 0)
{
return LIS3DH_ERR_I2C;
}
return LIS3DH_SUCCESS;
}
/*----------------------------------------------------------------------------*/
//enalbe data ready interrupt
static int LIS3DH_SetIntEnable(struct i2c_client *client, u8 intenable)
{
u8 databuf[10];
u8 addr = LIS3DH_REG_CTL_REG3;
int res = 0;
memset(databuf, 0, sizeof(u8)*10);
if(hwmsen_read_byte(client, addr, &databuf[0]))
{
GSE_ERR("read reg_ctl_reg1 register err!\n");
return LIS3DH_ERR_I2C;
}
databuf[0] = 0x00;
databuf[1] = databuf[0];
databuf[0] = LIS3DH_REG_CTL_REG3;
res = i2c_master_send(client, databuf, 0x2);
if(res <= 0)
{
return LIS3DH_ERR_I2C;
}
return LIS3DH_SUCCESS;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_Init(struct i2c_client *client, int reset_cali)
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
int res = 0;
/*
res = LIS3DH_CheckDeviceID(client);
if(res != LIS3DH_SUCCESS)
{
return res;
}
*/
// first clear reg1
res = hwmsen_write_byte(client,LIS3DH_REG_CTL_REG1,0x07);
if(res != LIS3DH_SUCCESS)
{
return res;
}
res = LIS3DH_SetPowerMode(client, false);
if(res != LIS3DH_SUCCESS)
{
return res;
}
res = LIS3DH_SetBWRate(client, LIS3DH_BW_100HZ);//400 or 100 no other choice
if(res != LIS3DH_SUCCESS )
{
return res;
}
res = LIS3DH_SetDataFormat(client, LIS3DH_RANGE_2G);//8g or 2G no oher choise
if(res != LIS3DH_SUCCESS)
{
return res;
}
gsensor_gain.x = gsensor_gain.y = gsensor_gain.z = obj->reso->sensitivity;
res = LIS3DH_SetIntEnable(client, false);
if(res != LIS3DH_SUCCESS)
{
return res;
}
if(0 != reset_cali)
{
//reset calibration only in power on
res = LIS3DH_ResetCalibration(client);
if(res != LIS3DH_SUCCESS)
{
return res;
}
}
#ifdef CONFIG_LIS3DH_LOWPASS
memset(&obj->fir, 0x00, sizeof(obj->fir));
#endif
return LIS3DH_SUCCESS;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_ReadChipInfo(struct i2c_client *client, char *buf, int bufsize)
{
u8 databuf[10];
memset(databuf, 0, sizeof(u8)*10);
if((NULL == buf)||(bufsize<=30))
{
return -1;
}
if(NULL == client)
{
*buf = 0;
return -2;
}
sprintf(buf, "LIS3DH Chip");
return 0;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_ReadSensorData(struct i2c_client *client, char *buf, int bufsize)
{
struct lis3dh_i2c_data *obj = (struct lis3dh_i2c_data*)i2c_get_clientdata(client);
u8 databuf[20];
int acc[LIS3DH_AXES_NUM];
int res = 0;
memset(databuf, 0, sizeof(u8)*10);
if(NULL == buf)
{
return -1;
}
if(NULL == client)
{
*buf = 0;
return -2;
}
if(sensor_power == FALSE)
{
res = LIS3DH_SetPowerMode(client, true);
if(res)
{
GSE_ERR("Power on lis3dh error %d!\n", res);
}
msleep(20);
}
if((res = LIS3DH_ReadData(client, obj->data)))
{
GSE_ERR("I2C error: ret value=%d", res);
return -3;
}
else
{
obj->data[LIS3DH_AXIS_X] += obj->cali_sw[LIS3DH_AXIS_X];
obj->data[LIS3DH_AXIS_Y] += obj->cali_sw[LIS3DH_AXIS_Y];
obj->data[LIS3DH_AXIS_Z] += obj->cali_sw[LIS3DH_AXIS_Z];
/*remap coordinate*/
acc[obj->cvt.map[LIS3DH_AXIS_X]] = obj->cvt.sign[LIS3DH_AXIS_X]*obj->data[LIS3DH_AXIS_X];
acc[obj->cvt.map[LIS3DH_AXIS_Y]] = obj->cvt.sign[LIS3DH_AXIS_Y]*obj->data[LIS3DH_AXIS_Y];
acc[obj->cvt.map[LIS3DH_AXIS_Z]] = obj->cvt.sign[LIS3DH_AXIS_Z]*obj->data[LIS3DH_AXIS_Z];
//GSE_LOG("Mapped gsensor data: %d, %d, %d!\n", acc[LIS3DH_AXIS_X], acc[LIS3DH_AXIS_Y], acc[LIS3DH_AXIS_Z]);
//Out put the mg
acc[LIS3DH_AXIS_X] = acc[LIS3DH_AXIS_X] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
acc[LIS3DH_AXIS_Y] = acc[LIS3DH_AXIS_Y] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
acc[LIS3DH_AXIS_Z] = acc[LIS3DH_AXIS_Z] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
sprintf(buf, "%04x %04x %04x", acc[LIS3DH_AXIS_X], acc[LIS3DH_AXIS_Y], acc[LIS3DH_AXIS_Z]);
if(atomic_read(&obj->trace) & ADX_TRC_IOCTL)//atomic_read(&obj->trace) & ADX_TRC_IOCTL
{
GSE_LOG("gsensor data: %s!\n", buf);
dumpReg(client);
}
}
return 0;
}
/*----------------------------------------------------------------------------*/
static int LIS3DH_ReadRawData(struct i2c_client *client, char *buf)
{
struct lis3dh_i2c_data *obj = (struct lis3dh_i2c_data*)i2c_get_clientdata(client);
int res = 0;
if (!buf || !client)
{
return EINVAL;
}
if((res = LIS3DH_ReadData(client, obj->data)))
{
GSE_ERR("I2C error: ret value=%d", res);
return EIO;
}
else
{
sprintf(buf, "%04x %04x %04x", obj->data[LIS3DH_AXIS_X],
obj->data[LIS3DH_AXIS_Y], obj->data[LIS3DH_AXIS_Z]);
}
return 0;
}
/*----------------------------------------------------------------------------*/
static ssize_t show_chipinfo_value(struct device_driver *ddri, char *buf)
{
struct i2c_client *client = lis3dh_i2c_client;
char strbuf[LIS3DH_BUFSIZE];
if(NULL == client)
{
GSE_ERR("i2c client is null!!\n");
return 0;
}
LIS3DH_ReadChipInfo(client, strbuf, LIS3DH_BUFSIZE);
return snprintf(buf, PAGE_SIZE, "%s\n", strbuf);
}
/*----------------------------------------------------------------------------*/
static ssize_t show_sensordata_value(struct device_driver *ddri, char *buf)
{
struct i2c_client *client = lis3dh_i2c_client;
char strbuf[LIS3DH_BUFSIZE];
if(NULL == client)
{
GSE_ERR("i2c client is null!!\n");
return 0;
}
LIS3DH_ReadSensorData(client, strbuf, LIS3DH_BUFSIZE);
return snprintf(buf, PAGE_SIZE, "%s\n", strbuf);
}
/*----------------------------------------------------------------------------*/
static ssize_t show_cali_value(struct device_driver *ddri, char *buf)
{
struct i2c_client *client = lis3dh_i2c_client;
struct lis3dh_i2c_data *obj;
int err, len = 0, mul;
int tmp[LIS3DH_AXES_NUM];
if(NULL == client)
{
GSE_ERR("i2c client is null!!\n");
return 0;
}
obj = i2c_get_clientdata(client);
if((err = LIS3DH_ReadCalibration(client, tmp)))
{
return -EINVAL;
}
else
{
mul = obj->reso->sensitivity/lis3dh_offset_resolution.sensitivity;
len += snprintf(buf+len, PAGE_SIZE-len, "[HW ][%d] (%+3d, %+3d, %+3d) : (0x%02X, 0x%02X, 0x%02X)\n", mul,
obj->offset[LIS3DH_AXIS_X], obj->offset[LIS3DH_AXIS_Y], obj->offset[LIS3DH_AXIS_Z],
obj->offset[LIS3DH_AXIS_X], obj->offset[LIS3DH_AXIS_Y], obj->offset[LIS3DH_AXIS_Z]);
len += snprintf(buf+len, PAGE_SIZE-len, "[SW ][%d] (%+3d, %+3d, %+3d)\n", 1,
obj->cali_sw[LIS3DH_AXIS_X], obj->cali_sw[LIS3DH_AXIS_Y], obj->cali_sw[LIS3DH_AXIS_Z]);
len += snprintf(buf+len, PAGE_SIZE-len, "[ALL] (%+3d, %+3d, %+3d) : (%+3d, %+3d, %+3d)\n",
obj->offset[LIS3DH_AXIS_X]*mul + obj->cali_sw[LIS3DH_AXIS_X],
obj->offset[LIS3DH_AXIS_Y]*mul + obj->cali_sw[LIS3DH_AXIS_Y],
obj->offset[LIS3DH_AXIS_Z]*mul + obj->cali_sw[LIS3DH_AXIS_Z],
tmp[LIS3DH_AXIS_X], tmp[LIS3DH_AXIS_Y], tmp[LIS3DH_AXIS_Z]);
return len;
}
}
/*----------------------------------------------------------------------------*/
static ssize_t store_cali_value(struct device_driver *ddri, const char *buf, size_t count)
{
struct i2c_client *client = lis3dh_i2c_client;
int err, x, y, z;
int dat[LIS3DH_AXES_NUM];
if(!strncmp(buf, "rst", 3))
{
if((err = LIS3DH_ResetCalibration(client)))
{
GSE_ERR("reset offset err = %d\n", err);
}
}
else if(3 == sscanf(buf, "0x%02X 0x%02X 0x%02X", &x, &y, &z))
{
dat[LIS3DH_AXIS_X] = x;
dat[LIS3DH_AXIS_Y] = y;
dat[LIS3DH_AXIS_Z] = z;
if((err = LIS3DH_WriteCalibration(client, dat)))
{
GSE_ERR("write calibration err = %d\n", err);
}
}
else
{
GSE_ERR("invalid format\n");
}
return count;
}
/*----------------------------------------------------------------------------*/
static ssize_t show_power_status(struct device_driver *ddri, char *buf)
{
struct i2c_client *client = lis3dh_i2c_client;
struct lis3dh_i2c_data *obj;
u8 data;
if(NULL == client)
{
GSE_ERR("i2c client is null!!\n");
return 0;
}
obj = i2c_get_clientdata(client);
hwmsen_read_byte(client,LIS3DH_REG_CTL_REG1,&data);
data &= 0x08;
data = data>>3;
return snprintf(buf, PAGE_SIZE, "%x\n", data);
}
/*----------------------------------------------------------------------------*/
static ssize_t show_firlen_value(struct device_driver *ddri, char *buf)
{
#ifdef CONFIG_LIS3DH_LOWPASS
struct i2c_client *client = lis3dh_i2c_client;
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
if(atomic_read(&obj->firlen))
{
int idx, len = atomic_read(&obj->firlen);
GSE_LOG("len = %2d, idx = %2d\n", obj->fir.num, obj->fir.idx);
for(idx = 0; idx < len; idx++)
{
GSE_LOG("[%5d %5d %5d]\n", obj->fir.raw[idx][LIS3DH_AXIS_X], obj->fir.raw[idx][LIS3DH_AXIS_Y], obj->fir.raw[idx][LIS3DH_AXIS_Z]);
}
GSE_LOG("sum = [%5d %5d %5d]\n", obj->fir.sum[LIS3DH_AXIS_X], obj->fir.sum[LIS3DH_AXIS_Y], obj->fir.sum[LIS3DH_AXIS_Z]);
GSE_LOG("avg = [%5d %5d %5d]\n", obj->fir.sum[LIS3DH_AXIS_X]/len, obj->fir.sum[LIS3DH_AXIS_Y]/len, obj->fir.sum[LIS3DH_AXIS_Z]/len);
}
return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&obj->firlen));
#else
return snprintf(buf, PAGE_SIZE, "not support\n");
#endif
}
/*----------------------------------------------------------------------------*/
static ssize_t store_firlen_value(struct device_driver *ddri, const char *buf, size_t count)
{
#ifdef CONFIG_LIS3DH_LOWPASS
struct i2c_client *client = lis3dh_i2c_client;
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
int firlen;
if(1 != sscanf(buf, "%d", &firlen))
{
GSE_ERR("invallid format\n");
}
else if(firlen > C_MAX_FIR_LENGTH)
{
GSE_ERR("exceeds maximum filter length\n");
}
else
{
atomic_set(&obj->firlen, firlen);
if(0 == firlen)//yucong fix build warning
{
atomic_set(&obj->fir_en, 0);
}
else
{
memset(&obj->fir, 0x00, sizeof(obj->fir));
atomic_set(&obj->fir_en, 1);
}
}
#endif
return count;
}
/*----------------------------------------------------------------------------*/
static ssize_t show_trace_value(struct device_driver *ddri, char *buf)
{
ssize_t res;
struct lis3dh_i2c_data *obj = obj_i2c_data;
if (obj == NULL)
{
GSE_ERR("i2c_data obj is null!!\n");
return 0;
}
res = snprintf(buf, PAGE_SIZE, "0x%04X\n", atomic_read(&obj->trace));
return res;
}
/*----------------------------------------------------------------------------*/
static ssize_t store_trace_value(struct device_driver *ddri, const char *buf, size_t count)
{
struct lis3dh_i2c_data *obj = obj_i2c_data;
int trace;
if (obj == NULL)
{
GSE_ERR("i2c_data obj is null!!\n");
return 0;
}
if(1 == sscanf(buf, "0x%x", &trace))
{
atomic_set(&obj->trace, trace);
}
else
{
GSE_ERR("invalid content: '%s', length = %d\n", buf, count);
}
return count;
}
/*----------------------------------------------------------------------------*/
static ssize_t show_status_value(struct device_driver *ddri, char *buf)
{
ssize_t len = 0;
struct lis3dh_i2c_data *obj = obj_i2c_data;
if (obj == NULL)
{
GSE_ERR("i2c_data obj is null!!\n");
return 0;
}
if(obj->hw)
{
len += snprintf(buf+len, PAGE_SIZE-len, "CUST: %d %d (%d %d)\n",
obj->hw->i2c_num, obj->hw->direction, obj->hw->power_id, obj->hw->power_vol);
}
else
{
len += snprintf(buf+len, PAGE_SIZE-len, "CUST: NULL\n");
}
return len;
}
/*----------------------------------------------------------------------------*/
static DRIVER_ATTR(chipinfo, S_IRUGO, show_chipinfo_value, NULL);
static DRIVER_ATTR(sensordata, S_IRUGO, show_sensordata_value, NULL);
static DRIVER_ATTR(cali, S_IWUSR | S_IRUGO, show_cali_value, store_cali_value);
static DRIVER_ATTR(power, S_IRUGO, show_power_status, NULL);
static DRIVER_ATTR(firlen, S_IWUSR | S_IRUGO, show_firlen_value, store_firlen_value);
static DRIVER_ATTR(trace, S_IWUSR | S_IRUGO, show_trace_value, store_trace_value);
static DRIVER_ATTR(status, S_IRUGO, show_status_value, NULL);
/*----------------------------------------------------------------------------*/
static struct driver_attribute *lis3dh_attr_list[] = {
&driver_attr_chipinfo, /*chip information*/
&driver_attr_sensordata, /*dump sensor data*/
&driver_attr_cali, /*show calibration data*/
&driver_attr_power, /*show power reg*/
&driver_attr_firlen, /*filter length: 0: disable, others: enable*/
&driver_attr_trace, /*trace log*/
&driver_attr_status,
};
/*----------------------------------------------------------------------------*/
static int lis3dh_create_attr(struct device_driver *driver)
{
int idx, err = 0;
int num = (int)(sizeof(lis3dh_attr_list)/sizeof(lis3dh_attr_list[0]));
if (driver == NULL)
{
return -EINVAL;
}
for(idx = 0; idx < num; idx++)
{
if((err = driver_create_file(driver, lis3dh_attr_list[idx])))
{
GSE_ERR("driver_create_file (%s) = %d\n", lis3dh_attr_list[idx]->attr.name, err);
break;
}
}
return err;
}
/*----------------------------------------------------------------------------*/
static int lis3dh_delete_attr(struct device_driver *driver)
{
int idx ,err = 0;
int num = (int)(sizeof(lis3dh_attr_list)/sizeof(lis3dh_attr_list[0]));
if(driver == NULL)
{
return -EINVAL;
}
for(idx = 0; idx < num; idx++)
{
driver_remove_file(driver, lis3dh_attr_list[idx]);
}
return err;
}
/*----------------------------------------------------------------------------*/
int lis3dh_operate(void* self, uint32_t command, void* buff_in, int size_in,
void* buff_out, int size_out, int* actualout)
{
int err = 0;
int value, sample_delay;
struct lis3dh_i2c_data *priv = (struct lis3dh_i2c_data*)self;
hwm_sensor_data* gsensor_data;
char buff[LIS3DH_BUFSIZE];
//GSE_FUN(f);
switch (command)
{
case SENSOR_DELAY:
if((buff_in == NULL) || (size_in < sizeof(int)))
{
GSE_ERR("Set delay parameter error!\n");
err = -EINVAL;
}
else
{
value = *(int *)buff_in;
if(value <= 5)
{
sample_delay = LIS3DH_BW_200HZ;
}
else if(value <= 10)
{
sample_delay = ~LIS3DH_BW_100HZ;
}
else
{
sample_delay = ~LIS3DH_BW_50HZ;
}
err = LIS3DH_SetBWRate(priv->client, sample_delay);
if(err != LIS3DH_SUCCESS ) //0x2C->BW=100Hz
{
GSE_ERR("Set delay parameter error!\n");
}
if(value >= 50)
{
atomic_set(&priv->filter, 0);
}
else
{
priv->fir.num = 0;
priv->fir.idx = 0;
priv->fir.sum[LIS3DH_AXIS_X] = 0;
priv->fir.sum[LIS3DH_AXIS_Y] = 0;
priv->fir.sum[LIS3DH_AXIS_Z] = 0;
atomic_set(&priv->filter, 1);
}
}
break;
case SENSOR_ENABLE:
if((buff_in == NULL) || (size_in < sizeof(int)))
{
GSE_ERR("Enable sensor parameter error!\n");
err = -EINVAL;
}
else
{
value = *(int *)buff_in;
GSE_LOG("enable value=%d, sensor_power =%d\n",value,sensor_power);
if(((value == 0) && (sensor_power == false)) ||((value == 1) && (sensor_power == true)))
{
GSE_LOG("Gsensor device have updated!\n");
}
else
{
err = LIS3DH_SetPowerMode( priv->client, !sensor_power);
}
}
break;
case SENSOR_GET_DATA:
if((buff_out == NULL) || (size_out< sizeof(hwm_sensor_data)))
{
GSE_ERR("get sensor data parameter error!\n");
err = -EINVAL;
}
else
{
gsensor_data = (hwm_sensor_data *)buff_out;
LIS3DH_ReadSensorData(priv->client, buff, LIS3DH_BUFSIZE);
sscanf(buff, "%x %x %x", &gsensor_data->values[0],
&gsensor_data->values[1], &gsensor_data->values[2]);
gsensor_data->status = SENSOR_STATUS_ACCURACY_MEDIUM;
gsensor_data->value_divide = 1000;
}
break;
default:
GSE_ERR("gsensor operate function no this parameter %d!\n", command);
err = -1;
break;
}
return err;
}
/******************************************************************************
* Function Configuration
******************************************************************************/
static int lis3dh_open(struct inode *inode, struct file *file)
{
file->private_data = lis3dh_i2c_client;
if(file->private_data == NULL)
{
GSE_ERR("null pointer!!\n");
return -EINVAL;
}
return nonseekable_open(inode, file);
}
/*----------------------------------------------------------------------------*/
static int lis3dh_release(struct inode *inode, struct file *file)
{
file->private_data = NULL;
return 0;
}
/*----------------------------------------------------------------------------*/
//static int lis3dh_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
// unsigned long arg)
static long lis3dh_unlocked_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct i2c_client *client = (struct i2c_client*)file->private_data;
struct lis3dh_i2c_data *obj = (struct lis3dh_i2c_data*)i2c_get_clientdata(client);
char strbuf[LIS3DH_BUFSIZE];
void __user *data;
SENSOR_DATA sensor_data;
long err = 0;
int cali[3];
//GSE_FUN(f);
if(_IOC_DIR(cmd) & _IOC_READ)
{
err = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd));
}
else if(_IOC_DIR(cmd) & _IOC_WRITE)
{
err = !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd));
}
if(err)
{
GSE_ERR("access error: %08X, (%2d, %2d)\n", cmd, _IOC_DIR(cmd), _IOC_SIZE(cmd));
return -EFAULT;
}
switch(cmd)
{
case GSENSOR_IOCTL_INIT:
LIS3DH_Init(client, 0);
break;
case GSENSOR_IOCTL_READ_CHIPINFO:
data = (void __user *) arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
LIS3DH_ReadChipInfo(client, strbuf, LIS3DH_BUFSIZE);
if(copy_to_user(data, strbuf, strlen(strbuf)+1))
{
err = -EFAULT;
break;
}
break;
case GSENSOR_IOCTL_READ_SENSORDATA:
data = (void __user *) arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
LIS3DH_ReadSensorData(client, strbuf, LIS3DH_BUFSIZE);
if(copy_to_user(data, strbuf, strlen(strbuf)+1))
{
err = -EFAULT;
break;
}
break;
case GSENSOR_IOCTL_READ_GAIN:
data = (void __user *) arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
if(copy_to_user(data, &gsensor_gain, sizeof(GSENSOR_VECTOR3D)))
{
err = -EFAULT;
break;
}
break;
case GSENSOR_IOCTL_READ_OFFSET:
data = (void __user *) arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
if(copy_to_user(data, &gsensor_offset, sizeof(GSENSOR_VECTOR3D)))
{
err = -EFAULT;
break;
}
break;
case GSENSOR_IOCTL_READ_RAW_DATA:
data = (void __user *) arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
LIS3DH_ReadRawData(client, strbuf);
if(copy_to_user(data, &strbuf, strlen(strbuf)+1))
{
err = -EFAULT;
break;
}
break;
case GSENSOR_IOCTL_SET_CALI:
data = (void __user*)arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
if(copy_from_user(&sensor_data, data, sizeof(sensor_data)))
{
err = -EFAULT;
break;
}
if(atomic_read(&obj->suspend))
{
GSE_ERR("Perform calibration in suspend state!!\n");
err = -EINVAL;
}
else
{
cali[LIS3DH_AXIS_X] = sensor_data.x * obj->reso->sensitivity / GRAVITY_EARTH_1000;
cali[LIS3DH_AXIS_Y] = sensor_data.y * obj->reso->sensitivity / GRAVITY_EARTH_1000;
cali[LIS3DH_AXIS_Z] = sensor_data.z * obj->reso->sensitivity / GRAVITY_EARTH_1000;
err = LIS3DH_WriteCalibration(client, cali);
}
break;
case GSENSOR_IOCTL_CLR_CALI:
err = LIS3DH_ResetCalibration(client);
break;
case GSENSOR_IOCTL_GET_CALI:
data = (void __user*)arg;
if(data == NULL)
{
err = -EINVAL;
break;
}
if((err = LIS3DH_ReadCalibration(client, cali)))
{
break;
}
sensor_data.x = cali[LIS3DH_AXIS_X] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
sensor_data.y = cali[LIS3DH_AXIS_Y] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
sensor_data.z = cali[LIS3DH_AXIS_Z] * GRAVITY_EARTH_1000 / obj->reso->sensitivity;
if(copy_to_user(data, &sensor_data, sizeof(sensor_data)))
{
err = -EFAULT;
break;
}
break;
default:
GSE_ERR("unknown IOCTL: 0x%08x\n", cmd);
err = -ENOIOCTLCMD;
break;
}
return err;
}
/*----------------------------------------------------------------------------*/
static struct file_operations lis3dh_fops = {
.owner = THIS_MODULE,
.open = lis3dh_open,
.release = lis3dh_release,
//.ioctl = lis3dh_ioctl,
.unlocked_ioctl = lis3dh_unlocked_ioctl,
};
/*----------------------------------------------------------------------------*/
static struct miscdevice lis3dh_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "gsensor",
.fops = &lis3dh_fops,
};
/*----------------------------------------------------------------------------*/
#ifndef CONFIG_HAS_EARLYSUSPEND
/*----------------------------------------------------------------------------*/
static int lis3dh_suspend(struct i2c_client *client, pm_message_t msg)
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
int err = 0;
u8 dat;
GSE_FUN();
if(msg.event == PM_EVENT_SUSPEND)
{
if(obj == NULL)
{
GSE_ERR("null pointer!!\n");
return -EINVAL;
}
//read old data
if ((err = hwmsen_read_byte(client, LIS3DH_REG_CTL_REG1, &dat)))
{
GSE_ERR("write data format fail!!\n");
return err;
}
dat = dat&0b10111111;
atomic_set(&obj->suspend, 1);
if(err = hwmsen_write_byte(client, LIS3DH_REG_CTL_REG1, dat))
{
GSE_ERR("write power control fail!!\n");
return err;
}
LIS3DH_power(obj->hw, 0);
}
return err;
}
/*----------------------------------------------------------------------------*/
static int lis3dh_resume(struct i2c_client *client)
{
struct lis3dh_i2c_data *obj = i2c_get_clientdata(client);
//int err;
GSE_FUN();
if(obj == NULL)
{
GSE_ERR("null pointer!!\n");
return -EINVAL;
}
LIS3DH_power(obj->hw, 1);
#if 0
mdelay(30);//yucong add for fix g sensor resume issue
if(err = LIS3DH_Init(client, 0))
{
GSE_ERR("initialize client fail!!\n");
return err;
}
#endif
atomic_set(&obj->suspend, 0);
return 0;
}
/*----------------------------------------------------------------------------*/
#else /*CONFIG_HAS_EARLY_SUSPEND is defined*/
/*----------------------------------------------------------------------------*/
static void lis3dh_early_suspend(struct early_suspend *h)
{
struct lis3dh_i2c_data *obj = container_of(h, struct lis3dh_i2c_data, early_drv);
int err;
GSE_FUN();
if(obj == NULL)
{
GSE_ERR("null pointer!!\n");
return;
}
atomic_set(&obj->suspend, 1);
/*
if(err = hwmsen_write_byte(obj->client, LIS3DH_REG_POWER_CTL, 0x00))
{
GSE_ERR("write power control fail!!\n");
return;
}
*/
if((err = LIS3DH_SetPowerMode(obj->client, false)))
{
GSE_ERR("write power control fail!!\n");
return;
}
sensor_power = false;
LIS3DH_power(obj->hw, 0);
}
/*----------------------------------------------------------------------------*/
static void lis3dh_late_resume(struct early_suspend *h)
{
struct lis3dh_i2c_data *obj = container_of(h, struct lis3dh_i2c_data, early_drv);
//int err;
GSE_FUN();
if(obj == NULL)
{
GSE_ERR("null pointer!!\n");
return;
}
LIS3DH_power(obj->hw, 1);
#if 0
mdelay(30);//yucong add for fix g sensor resume issue
if((err = LIS3DH_Init(obj->client, 0)))
{
GSE_ERR("initialize client fail!!\n");
return;
}
#endif
atomic_set(&obj->suspend, 0);
}
/*----------------------------------------------------------------------------*/
#endif /*CONFIG_HAS_EARLYSUSPEND*/
/*----------------------------------------------------------------------------*/
/*
static int lis3dh_i2c_detect(struct i2c_client *client, int kind, struct i2c_board_info *info)
{
strcpy(info->type, LIS3DH_DEV_NAME);
return 0;
}
*/
/*----------------------------------------------------------------------------*/
static int lis3dh_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct i2c_client *new_client;
struct lis3dh_i2c_data *obj;
struct hwmsen_object sobj;
int err = 0;
GSE_FUN();
if(!(obj = kzalloc(sizeof(*obj), GFP_KERNEL)))
{
err = -ENOMEM;
goto exit;
}
memset(obj, 0, sizeof(struct lis3dh_i2c_data));
obj->hw = lis3dh_get_cust_acc_hw();
if((err = hwmsen_get_convert(obj->hw->direction, &obj->cvt)))
{
GSE_ERR("invalid direction: %d\n", obj->hw->direction);
goto exit;
}
obj_i2c_data = obj;
obj->client = client;
new_client = obj->client;
i2c_set_clientdata(new_client,obj);
atomic_set(&obj->trace, 0);
atomic_set(&obj->suspend, 0);
#ifdef CONFIG_LIS3DH_LOWPASS
if(obj->hw->firlen > C_MAX_FIR_LENGTH)
{
atomic_set(&obj->firlen, C_MAX_FIR_LENGTH);
}
else
{
atomic_set(&obj->firlen, obj->hw->firlen);
}
if(atomic_read(&obj->firlen) > 0)
{
atomic_set(&obj->fir_en, 1);
}
#endif
lis3dh_i2c_client = new_client;
if((err = LIS3DH_Init(new_client, 1)))
{
goto exit_init_failed;
}
if((err = misc_register(&lis3dh_device)))
{
GSE_ERR("lis3dh_device register failed\n");
goto exit_misc_device_register_failed;
}
if((err = lis3dh_create_attr(&(lis3dh_init_info.platform_diver_addr->driver))))
{
GSE_ERR("create attribute err = %d\n", err);
goto exit_create_attr_failed;
}
sobj.self = obj;
sobj.polling = 1;
sobj.sensor_operate = lis3dh_operate;
if((err = hwmsen_attach(ID_ACCELEROMETER, &sobj)))
{
GSE_ERR("attach fail = %d\n", err);
goto exit_kfree;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
obj->early_drv.level = EARLY_SUSPEND_LEVEL_DISABLE_FB - 1,
obj->early_drv.suspend = lis3dh_early_suspend,
obj->early_drv.resume = lis3dh_late_resume,
register_early_suspend(&obj->early_drv);
#endif
GSE_LOG("%s: OK\n", __func__);
lis3dh_init_flag = 0;
return 0;
exit_create_attr_failed:
misc_deregister(&lis3dh_device);
exit_misc_device_register_failed:
exit_init_failed:
//i2c_detach_client(new_client);
exit_kfree:
kfree(obj);
exit:
GSE_ERR("%s: err = %d\n", __func__, err);
lis3dh_init_flag = -1;
return err;
}
/*----------------------------------------------------------------------------*/
static int lis3dh_i2c_remove(struct i2c_client *client)
{
int err = 0;
if((err = lis3dh_delete_attr(&(lis3dh_init_info.platform_diver_addr->driver))))
{
GSE_ERR("lis3dh_delete_attr fail: %d\n", err);
}
if((err = misc_deregister(&lis3dh_device)))
{
GSE_ERR("misc_deregister fail: %d\n", err);
}
if((err = hwmsen_detach(ID_ACCELEROMETER)))
lis3dh_i2c_client = NULL;
i2c_unregister_device(client);
kfree(i2c_get_clientdata(client));
return 0;
}
/*----------------------------------------------------------------------------*/
#if 0
/*----------------------------------------------------------------------------*/
static int lis3dh_probe(struct platform_device *pdev)
{
struct acc_hw *hw = get_cust_acc_hw();
GSE_FUN();
LIS3DH_power(hw, 1);
//lis3dh_force[0] = hw->i2c_num;
if(i2c_add_driver(&lis3dh_i2c_driver))
{
GSE_ERR("add driver error\n");
return -1;
}
return 0;
}
/*----------------------------------------------------------------------------*/
static int lis3dh_remove(struct platform_device *pdev)
{
struct acc_hw *hw = get_cust_acc_hw();
GSE_FUN();
LIS3DH_power(hw, 0);
i2c_del_driver(&lis3dh_i2c_driver);
return 0;
}
/*----------------------------------------------------------------------------*/
static struct platform_driver lis3dh_gsensor_driver = {
.probe = lis3dh_probe,
.remove = lis3dh_remove,
.driver = {
.name = "gsensor",
.owner = THIS_MODULE,
}
};
/*----------------------------------------------------------------------------*/
#endif
/*----------------------------------------------------------------------------*/
static int lis3dh_remove(void)
{
struct acc_hw *hw = lis3dh_get_cust_acc_hw();
GSE_FUN();
LIS3DH_power(hw, 0);
i2c_del_driver(&lis3dh_i2c_driver);
return 0;
}
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
static int lis3dh_local_init(void)
{
struct acc_hw *hw = lis3dh_get_cust_acc_hw();
GSE_FUN();
LIS3DH_power(hw, 1);
if(i2c_add_driver(&lis3dh_i2c_driver))
{
GSE_ERR("add driver error\n");
return -1;
}
if(-1 == lis3dh_init_flag)
{
return -1;
}
return 0;
}
/*----------------------------------------------------------------------------*/
static int __init lis3dh_init(void)
{
GSE_FUN();
i2c_register_board_info(0, &i2c_LIS3DH, 1);
hwmsen_gsensor_add(&lis3dh_init_info);
#if 0
if(platform_driver_register(&lis3dh_gsensor_driver))
{
GSE_ERR("failed to register driver");
return -ENODEV;
}
#endif
return 0;
}
/*----------------------------------------------------------------------------*/
static void __exit lis3dh_exit(void)
{
GSE_FUN();
//platform_driver_unregister(&lis3dh_gsensor_driver);
}
/*----------------------------------------------------------------------------*/
module_init(lis3dh_init);
module_exit(lis3dh_exit);
/*----------------------------------------------------------------------------*/
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("LIS3DH I2C driver");
MODULE_AUTHOR("[email protected]");
| yevgeniy-logachev/CATB15Kernel | mediatek/custom/common/kernel/accelerometer/lis3dh_auto/lis3dh.c | C | gpl-2.0 | 49,830 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* Cairo implementation for Image_Transform package
*
* PHP versions 4 and 5
*
* @category Image
* @package Image_Transform
* @subpackage Image_Transform_Driver_Cairowrapper
* @author Christian Weiske <[email protected]>
* @copyright 2008 The PHP Group
* @license https://www.gnu.org/copyleft/lesser.html LGPL
* @version CVS: $Id: Cairowrapper.php 288112 2009-09-06 21:02:37Z cweiske $
* @link http://pear.php.net/package/Image_Transform
*/
require_once __DIR__ . '/Image/Transform.php';
/**
* Cairo implementation for Image_Transform package using pecl's cairo_wrapper
* extension.
*
* Supports png files only.
*
* @category Image
* @package Image_Transform
* @subpackage Image_Transform_Driver_Cairowrapper
* @author Christian Weiske <[email protected]>
* @copyright 2008 The PHP Group
* @license https://www.gnu.org/copyleft/lesser.html LGPL
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Transform
*/
class Image_Transform_Driver_Cairowrapper extends Image_Transform
{
public $surface = null;
/**
* Supported image types
*
* @var array
* @access protected
*/
public $_supported_image_types = [
'png' => 'rw',
];
/**
* Check settings
*/
public function Image_Transform_Driver_Cairowrapper()
{
$this->__construct();
}
/**
* Create object and check if cairo_wrapper is loaded
*/
public function __construct()
{
if (!PEAR::loadExtension('cairo_wrapper')) {
$this->isError(PEAR::raiseError('cairo_wrapper extension is not available.', IMAGE_TRANSFORM_ERROR_UNSUPPORTED));
}
}
/**
* Loads an image from file
*
* @param string $image filename
*
* @return bool|PEAR_Error TRUE or a PEAR_Error object on error
*
* @access public
*/
public function load($image)
{
$this->free();
$this->image = $image;
$result = $this->_get_image_details($image);
if (PEAR::isError($result)) {
return $result;
}
if (!$this->supportsType($this->type, 'r')) {
return PEAR::raiseError('Image type not supported for input', IMAGE_TRANSFORM_ERROR_UNSUPPORTED);
}
$this->surface = cairo_image_surface_create_from_png($this->image);
if (CAIRO_STATUS_SUCCESS != cairo_surface_status($this->surface)) {
$this->surface = null;
return PEAR::raiseError('Error while loading image file.', IMAGE_TRANSFORM_ERROR_IO);
}
return true;
}
//function load(..)
/**
* Resize the image
*
* @param int $new_x New width
* @param int $new_y New height
* @param array $options Optional parameters
*
* @return bool|PEAR_Error TRUE on success or PEAR_Error object on error
*
* @access protected
*/
public function _resize($new_x, $new_y, $options = null)
{
if (true === $this->resized) {
return PEAR::raiseError('You have already resized the image without saving it.' . ' Your previous resizing will be overwritten', null, PEAR_ERROR_TRIGGER, E_USER_NOTICE);
}
if ($this->new_x == $new_x && $this->new_y == $new_y) {
return true;
}
$xFactor = $new_x / $this->img_x;
$yFactor = $new_y / $this->img_y;
$outputSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, $new_x, $new_y);
$outputContext = cairo_create($outputSurface);
cairo_scale($outputContext, $xFactor, $yFactor);
cairo_set_source_surface($outputContext, $this->surface, 0, 0);
cairo_paint($outputContext);
cairo_destroy($outputContext);
cairo_surface_destroy($this->surface);
$this->surface = $outputSurface;
$this->new_x = $new_x;
$this->new_y = $new_y;
return true;
}
//function _resize(..)
/**
* Saves the scaled image into a file.
*
* @param string $filename The filename to save to
* @param mixed $type ignored
* @param mixed $quality ignored
*
* @return bool|PEAR_Error TRUE on success or PEAR_Error object on error
*
* @access public
*/
public function save($filename, $type = null, $quality = null)
{
cairo_surface_write_to_png($this->surface, $filename);
$this->free();
return true;
}
//function save(..)
/**
* Returns the surface of the image so it can be modified further
*
* @return resource
*
* @access public
*/
public function getHandle()
{
return $this->surface;
}
//function getHandle()
/**
* Frees cairo handles
*
*
* @access public
*/
public function free()
{
$this->resized = false;
if (is_resource($this->surface)) {
cairo_surface_destroy($this->surface);
}
$this->surface = null;
}
//function free()
/**
* Mirrors the image vertically
* Uses an affine transformation matrix to flip the image.
*/
public function flip()
{
$outputSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, $this->img_x, $this->img_y);
$outputContext = cairo_create($outputSurface);
// xx, yx, xy, yy, x0, y0
$matrix = cairo_matrix_create(1, 0, 0, -1, 0, $this->img_y);
cairo_set_matrix($outputContext, $matrix);
cairo_set_source_surface($outputContext, $this->surface, 0, 0);
cairo_paint($outputContext);
cairo_destroy($outputContext);
cairo_surface_destroy($this->surface);
$this->surface = $outputSurface;
}
//function flip()
/**
* Mirrors the image horizontally.
* Uses an affine transformation matrix to mirror the image.
*
* 123 -> 321
*/
public function mirror()
{
$outputSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, $this->img_x, $this->img_y);
$outputContext = cairo_create($outputSurface);
// xx, yx, xy, yy, x0, y0
$matrix = cairo_matrix_create(-1, 0, 0, 1, $this->img_x, 0);
cairo_set_matrix($outputContext, $matrix);
cairo_set_source_surface($outputContext, $this->surface, 0, 0);
cairo_paint($outputContext);
cairo_destroy($outputContext);
cairo_surface_destroy($this->surface);
$this->surface = $outputSurface;
}
//function mirror()
}//class Image_Transform_Driver_Cairowrapper extends Image_Transform
| mambax7/extgallery | class/pear/Image/Transform/Driver/Cairowrapper.php | PHP | gpl-2.0 | 6,761 |
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------
*
* Copyright (C) 2011 Gabriel Terejanu - [email protected]
*
* This is an application framework for solving the problem of
* predictive model selection of coupled models as presented in the
* following paper:
*
* Gabriel Terejanu, Todd Oliver, Chris Simmons (2011). Application of
* Predictive Model Selection to Coupled Models. In Proceedings of the World
* Congress on Engineering and Computer Science 2011 Vol II, WCECS 2011,
* pp. 927-932.
*
* The framework is built on top of statistical library QUESO
* (Quantification of Uncertainty for Estimation, Simulation and Optimization).
*
* 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.
*
*--------------------------------------------------------------------------
*
* coupled_OLS_SED_funcs_test.C
*
*--------------------------------------------------------------------------
*-------------------------------------------------------------------------- */
#include <cmath>
#include <map>
#include <string>
#include <iostream>
#include "uqDefines.h"
#include "uqGslVector.h"
#include "uqVectorSpace.h"
#include "uqGslMatrix.h"
#include "testsCommon.h"
#include "oscillatorLinearSpring.h"
#include "forcingSimpleExponentialDecay.h"
#include "modelForcingSimpleExponentialDecay.h"
uqFullEnvironmentClass* env;
//********************************************************************
// Definitions
//********************************************************************
bool test_OLS_SED_func();
bool test_OLS_SED_int_exact();
bool test_OLS_SED_int_energy();
//********************************************************************
// main - OLS - SED tests
//********************************************************************
int main(int argc, char* argv[])
{
MPI_Init(&argc,&argv);
env = new uqFullEnvironmentClass(MPI_COMM_WORLD,argv[1],"",NULL);
// tests OLS_SED_func
TST_MACRO( test_OLS_SED_func(),
"oscillatorLinearSpring_func",
"with forcing" );
// tests OLS_SED_int_exact
TST_MACRO( test_OLS_SED_int_exact(),
"oscillatorLinearSpring_int",
"exact solution with forcing" );
// Finalize environment
delete env;
MPI_Finalize();
// no error has been found
return 0;
}
//********************************************************************
// tests OLS_SED_func
//********************************************************************
bool test_OLS_SED_func()
{
// scenario
double scn_time = 1.0;
// params oscillator
double param_c = 2.0;
double param_k10 = param_c;
// params forcing
double param_F0 = 2.0;
double param_tau = 1.0;
// map inputs params (oscillator)
std::map<std::string, double> map_act_params;
map_act_params[ __OLS_PARAM_C ] = param_c;
map_act_params[ __OLS_PARAM_K10 ] = param_k10;
// forcing
map_act_params[ __SED_PARAM_F0 ] = param_F0;
map_act_params[ __SED_PARAM_TAU ] = param_tau;
// set coupling
map_act_params[ __SED_NAME ] = 1.0;
// outputs
double ic_y[2] = {0.5, 1.5};
double computed_f[2] = {0.0, 0.0};
double exact_f[2] =
{ ic_y[1],
param_F0*exp(-scn_time/param_tau) - param_c/__OSCILLATOR_MASS*(ic_y[0]+ic_y[1]) };
// get values
oscillatorLinearSpring_func( scn_time,
ic_y,
computed_f,
(void*)&map_act_params );
// compare the exact value with the computed one
return ( ( std::fabs( exact_f[0] - computed_f[0] ) > DOUBLE_TOL ) ||
( std::fabs( exact_f[1] - computed_f[1] ) > DOUBLE_TOL ) );
}
//********************************************************************
// tests OLS_SED_int_exact
//********************************************************************
bool test_OLS_SED_int_exact()
{
// scenario
double scn_time = 1.0;
// params oscillator
double param_c = 0.1;
double param_k10 = 0.0; // to have a linear ODE in velocity
// params forcing
double param_F0 = 2.0;
double param_tau = 1.0;
// map inputs
std::map<std::string, double> map_scn;
map_scn[ __OLS_SCN_TIME ] = scn_time;
// map params oscillator
std::map<std::string, double> map_act_params;
map_act_params[ __OLS_PARAM_C ] = param_c;
map_act_params[ __OLS_PARAM_K10 ] = param_k10;
// forcing
map_act_params[ __SED_PARAM_F0 ] = param_F0;
map_act_params[ __SED_PARAM_TAU ] = param_tau;
// set coupling
map_act_params[ __SED_NAME ] = 1.0;
// outputs
double final_y0;
double final_y1;
double time_to_rest;
double max_displacement;
double max_velocity;
// get final velocity
oscillatorLinearSpring_int( final_y0, final_y1,
time_to_rest,
max_displacement,
max_velocity,
false,
map_scn,
map_act_params );
double my_const = __OSCILLATOR_IC_X2 +
param_tau * param_F0 / (__OSCILLATOR_MASS - param_tau * param_c );
double pre_exp = param_tau * param_F0 / ( param_tau * param_c - __OSCILLATOR_MASS );
double exact_y1 = exp( -param_c/__OSCILLATOR_MASS*scn_time ) *
( pre_exp *
exp( (param_tau*param_c-__OSCILLATOR_MASS)/(__OSCILLATOR_MASS*param_tau)*scn_time )
+ my_const );
// std::cout << "final_y1 = " << final_y1 << std::endl;
// std::cout << "exact_y1 = " << exact_y1 << std::endl;
// compare the exact value with the computed one
return ( std::fabs( exact_y1 - final_y1 ) > DOUBLE_TOL ) ;
}
| terejanu/PredictiveSelectionCoupledModels | tests/coupled_OLS_SED_funcs_test.C | C++ | gpl-2.0 | 6,162 |
import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdout)
logger.addHandler(std_out_logger)
def broadcast_msg(server, ns_name, event, *args):
pkt = dict(type="event",
name=event,
args=args,
endpoint=ns_name)
for sessid, socket in server.sockets.iteritems():
socket.send_packet(pkt)
def workshops_monitor(server):
sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
broadcast_msg(server, '', "sizes", tmp)
while True:
logger.info("Participants viewing frontend:" + str(len(server.sockets)))
workshops_available = []
curr_workshops = getAvailableWorkshops()
for w in curr_workshops:
workshops_available.append([w.workshopName, w.q.qsize()])
wq = filter(lambda x: x[0] == w.workshopName, sizes)[0]
if wq[1] != w.q.qsize():
wq[1] = w.q.qsize()
logging.info("client_updater: New update being pushed to clients: " + str(wq))
broadcast_msg(server, '', 'sizes', wq)
logger.info("Workshops available:" + str(workshops_available))
time.sleep(1)
class RequestHandlerApp(object):
def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith('/socket.io'):
socketio_manage(environ, {'': QueueStatusHandler})
class QueueStatusHandler(BaseNamespace, BroadcastMixin):
def on_connect(self):
sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
self.emit('sizes', tmp)
| ARL-UTEP-OC/emubox | workshop-manager/bin/RequestHandler/client_updater.py | Python | gpl-2.0 | 2,004 |
/* Javadoc style sheet */
/*
Overall document style
*/
body {
background-color:#ffffff;
color:#353833;
font-family:Arial, Helvetica, sans-serif;
font-size:76%;
margin:0;
}
a:link, a:visited {
text-decoration:none;
color:#4c6b87;
}
a:hover, a:focus {
text-decoration:none;
color:#bb7a2a;
}
a:active {
text-decoration:none;
color:#4c6b87;
}
a[name] {
color:#353833;
}
a[name]:hover {
text-decoration:none;
color:#353833;
}
pre {
font-size:1.3em;
}
h1 {
font-size:1.8em;
}
h2 {
font-size:1.5em;
}
h3 {
font-size:1.4em;
}
h4 {
font-size:1.3em;
}
h5 {
font-size:1.2em;
}
h6 {
font-size:1.1em;
}
ul {
list-style-type:circle;
}
code, tt {
font-size:1.3em
}
dt code {
}
table tr td dt code {
font-size:1.2em;
vertical-align:top;
}
sup {
font-size:.6em;
}
/*
Document title and Copyright styles
*/
.clear {
clear:both;
height:0px;
overflow:hidden;
}
.aboutLanguage {
float:right;
padding:0px 21px;
font-size:.8em;
z-index:200;
margin-top:-7px;
}
.legalCopy {
margin-left:.5em;
}
.bar a, .bar a:link, .bar a:visited, .bar a:active {
color:#FFFFFF;
text-decoration:none;
}
.bar a:hover, .bar a:focus {
color:#bb7a2a;
}
.tab {
background-color:#0066FF;
background-image:url(resources/titlebar.gif);
background-position:left top;
background-repeat:no-repeat;
color:#ffffff;
padding:8px;
width:5em;
font-weight:bold;
}
/*
Navigation bar styles
*/
.bar {
background-image:url(resources/background.gif);
background-repeat:repeat-x;
color:#FFFFFF;
padding:.8em .5em .4em .8em;
height:auto;/*height:1.8em;*/
font-size:1em;
margin:0;
}
.topNav {
background-image:url(resources/background.gif);
background-repeat:repeat-x;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
}
.bottomNav {
margin-top:10px;
background-image:url(resources/background.gif);
background-repeat:repeat-x;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
}
.subNav {
background-color:#dee3e9;
border-bottom:1px solid #9eadc0;
float:left;
width:100%;
overflow:hidden;
}
.subNav div {
clear:left;
float:left;
padding:0 0 5px 6px;
}
ul.navList, ul.subNavList {
float:left;
margin:0 25px 0 0;
padding:0;
}
ul.navList li{
list-style:none;
float:left;
padding:3px 6px;
}
ul.subNavList li{
list-style:none;
float:left;
font-size:90%;
}
.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {
color:#FFFFFF;
text-decoration:none;
}
.topNav a:hover, .bottomNav a:hover {
text-decoration:none;
color:#bb7a2a;
}
.navBarCell1Rev {
background-image:url(resources/tab.gif);
background-color:#a88834;
color:#FFFFFF;
margin: auto 5px;
border:1px solid #c9aa44;
}
/*
Page header and footer styles
*/
.header, .footer {
clear:both;
margin:0 20px;
padding:5px 0 0 0;
}
.indexHeader {
margin:10px;
position:relative;
}
.indexHeader h1 {
font-size:1.3em;
}
.title {
color:#2c4557;
margin:10px 0;
}
.subTitle {
margin:5px 0 0 0;
}
.header ul {
margin:0 0 25px 0;
padding:0;
}
.footer ul {
margin:20px 0 5px 0;
}
.header ul li, .footer ul li {
list-style:disc;
}
/*
Heading styles
*/
div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 {
background-color:#dee3e9;
border-top:1px solid #9eadc0;
border-bottom:1px solid #9eadc0;
margin:0 0 6px -8px;
padding:2px 5px;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
background-color:#dee3e9;
border-top:1px solid #9eadc0;
border-bottom:1px solid #9eadc0;
margin:0 0 6px -8px;
padding:2px 5px;
}
ul.blockList ul.blockList li.blockList h3 {
padding:0;
margin:15px 0;
}
ul.blockList li.blockList h2 {
padding:0px 0 20px 0;
}
/*
Page layout container styles
*/
.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer {
clear:both;
padding:10px 20px;
position:relative;
}
.indexContainer {
margin:10px;
position:relative;
font-size:1.0em;
}
.indexContainer h2 {
font-size:1.1em;
padding:0 0 3px 0;
}
.indexContainer ul {
margin:0;
padding:0;
}
.indexContainer ul li {
list-style:none;
}
.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {
font-size:1.1em;
font-weight:bold;
margin:10px 0 0 0;
color:#4E4E4E;
}
.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {
margin:10px 0 10px 20px;
}
.serializedFormContainer dl.nameValue dt {
margin-left:1px;
font-size:1.1em;
display:inline;
font-weight:bold;
}
.serializedFormContainer dl.nameValue dd {
margin:0 0 0 1px;
font-size:1.1em;
display:inline;
}
/*
List styles
*/
ul.horizontal li {
display:inline;
font-size:0.9em;
}
ul.inheritance {
margin:0;
padding:0;
}
ul.inheritance li {
display:inline;
list-style:none;
}
ul.inheritance li ul.inheritance {
margin-left:15px;
padding-left:15px;
padding-top:1px;
}
ul.blockList, ul.blockListLast {
margin:10px 0 10px 0;
padding:0;
}
ul.blockList li.blockList, ul.blockListLast li.blockList {
list-style:none;
margin-bottom:25px;
}
ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {
padding:0px 20px 5px 10px;
border:1px solid #9eadc0;
background-color:#f9f9f9;
}
ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList {
padding:0 0 5px 8px;
background-color:#ffffff;
border:1px solid #9eadc0;
border-top:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockList {
margin-left:0;
padding-left:0;
padding-bottom:15px;
border:none;
border-bottom:1px solid #9eadc0;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast {
list-style:none;
border-bottom:none;
padding-bottom:0;
}
table tr td dl, table tr td dl dt, table tr td dl dd {
margin-top:0;
margin-bottom:1px;
}
/*
Table styles
*/
.contentContainer table, .classUseContainer table, .constantValuesContainer table {
border-bottom:1px solid #9eadc0;
width:100%;
}
.contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table {
width:100%;
}
.contentContainer .description table, .contentContainer .details table {
border-bottom:none;
}
.contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{
vertical-align:top;
padding-right:20px;
}
.contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast,
.contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast,
.contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne,
.contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne {
padding-right:3px;
}
.overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption {
position:relative;
text-align:left;
background-repeat:no-repeat;
color:#FFFFFF;
font-weight:bold;
clear:none;
overflow:hidden;
padding:0px;
margin:0px;
}
caption a:link, caption a:hover, caption a:active, caption a:visited {
color:#FFFFFF;
}
.overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span {
white-space:nowrap;
padding-top:8px;
padding-left:8px;
display:block;
float:left;
background-image:url(resources/titlebar.gif);
height:18px;
}
.overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd {
width:10px;
background-image:url(resources/titlebar_end.gif);
background-repeat:no-repeat;
background-position:top right;
position:relative;
float:left;
}
ul.blockList ul.blockList li.blockList table {
margin:0 0 12px 0px;
width:100%;
}
.tableSubHeadingColor {
background-color: #EEEEFF;
}
.altColor {
background-color:#eeeeef;
}
.rowColor {
background-color:#ffffff;
}
.overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td {
text-align:left;
padding:3px 3px 3px 7px;
}
th.colFirst, th.colLast, th.colOne, .constantValuesContainer th {
background:#dee3e9;
border-top:1px solid #9eadc0;
border-bottom:1px solid #9eadc0;
text-align:left;
padding:3px 3px 3px 7px;
}
td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover {
font-weight:bold;
}
td.colFirst, th.colFirst {
border-left:1px solid #9eadc0;
white-space:nowrap;
}
td.colLast, th.colLast {
border-right:1px solid #9eadc0;
}
td.colOne, th.colOne {
border-right:1px solid #9eadc0;
border-left:1px solid #9eadc0;
}
table.overviewSummary {
padding:0px;
margin-left:0px;
}
table.overviewSummary td.colFirst, table.overviewSummary th.colFirst,
table.overviewSummary td.colOne, table.overviewSummary th.colOne {
width:25%;
vertical-align:middle;
}
table.packageSummary td.colFirst, table.overviewSummary th.colFirst {
width:25%;
vertical-align:middle;
}
/*
Content styles
*/
.description pre {
margin-top:0;
}
.deprecatedContent {
margin:0;
padding:10px 0;
}
.docSummary {
padding:0;
}
/*
Formatting effect styles
*/
.sourceLineNo {
color:green;
padding:0 30px 0 0;
}
h1.hidden {
visibility:hidden;
overflow:hidden;
font-size:.9em;
}
.block {
display:block;
margin:3px 0 0 0;
}
.strong {
font-weight:bold;
}
| underplex/tickay | stylesheet_tickay.css | CSS | gpl-2.0 | 11,569 |
<?php
/**
* @file
* Contains \Drupal\Core\Lock\LockBackendInterface.
*/
namespace Drupal\Core\Lock;
/**
* @defgroup lock Locking mechanisms
* @{
* Functions to coordinate long-running operations across requests.
*
* In most environments, multiple Drupal page requests (a.k.a. threads or
* processes) will execute in parallel. This leads to potential conflicts or
* race conditions when two requests execute the same code at the same time. A
* common example of this is a rebuild like menu_router_rebuild() where we
* invoke many hook implementations to get and process data from all active
* modules, and then delete the current data in the database to insert the new
* afterwards.
*
* This is a cooperative, advisory lock system. Any long-running operation
* that could potentially be attempted in parallel by multiple requests should
* try to acquire a lock before proceeding. By obtaining a lock, one request
* notifies any other requests that a specific operation is in progress which
* must not be executed in parallel.
*
* To use this API, pick a unique name for the lock. A sensible choice is the
* name of the function performing the operation. A very simple example use of
* this API:
* @code
* function mymodule_long_operation() {
* $lock = \Drupal::lock();
* if ($lock->acquire('mymodule_long_operation')) {
* // Do the long operation here.
* // ...
* $lock->release('mymodule_long_operation');
* }
* }
* @endcode
*
* If a function acquires a lock it should always release it when the operation
* is complete by calling $lock->release(), as in the example.
*
* A function that has acquired a lock may attempt to renew a lock (extend the
* duration of the lock) by calling $lock->acquire() again during the operation.
* Failure to renew a lock is indicative that another request has acquired the
* lock, and that the current operation may need to be aborted.
*
* If a function fails to acquire a lock it may either immediately return, or
* it may call $lock->wait() if the rest of the current page request requires
* that the operation in question be complete. After $lock->wait() returns, the
* function may again attempt to acquire the lock, or may simply allow the page
* request to proceed on the assumption that a parallel request completed the
* operation.
*
* $lock->acquire() and $lock->wait() will automatically break (delete) a lock
* whose duration has exceeded the timeout specified when it was acquired.
*
* @} End of "defgroup lock".
*/
/**
* Lock backend interface.
*
* @ingroup lock
*/
interface LockBackendInterface {
/**
* Acquires a lock.
*
* @param string $name
* Lock name. Limit of name's length is 255 characters.
* @param float $timeout = 30.0
* (optional) Lock lifetime in seconds.
*
* @return bool
*/
public function acquire($name, $timeout = 30.0);
/**
* Checks if a lock is available for acquiring.
*
* @param string $name
* Lock to acquire.
*
* @return bool
*/
public function lockMayBeAvailable($name);
/**
* Waits a short amount of time before a second lock acquire attempt.
*
* While this method is subject to have a generic implementation in abstract
* backend implementation, some backends may provide non blocking or less I/O
* intensive wait mechanism: this is why this method remains on the backend
* interface.
*
* @param string $name
* Lock name currently being locked.
* @param int $delay = 30
* Milliseconds to wait for.
*
* @return bool
* TRUE if the lock holds, FALSE if it may be available. You still need to
* acquire the lock manually and it may fail again.
*/
public function wait($name, $delay = 30);
/**
* Releases the given lock.
*
* @param string $name
*/
public function release($name);
/**
* Releases all locks for the given lock token identifier.
*
* @param string $lockId
* (optional) If none given, remove all locks from the current page.
* Defaults to NULL.
*/
public function releaseAll($lockId = NULL);
/**
* Gets the unique page token for locks.
*
* Locks will be wiped out at the end of each page request on a token basis.
*
* @return string
*/
public function getLockId();
}
| acappellamaniac/eva_website | sites/all/modules/service_container/lib/Drupal/Core/Lock/LockBackendInterface.php | PHP | gpl-2.0 | 4,456 |
def freq_month(obj):
if obj is None or obj == []:
return
months = {1: 'jan',
2: 'feb',
3: 'mar',
4: 'apr',
5: 'may',
6: 'jun',
7: 'jul',
8: 'aug',
9: 'sep',
10: 'oct',
11: 'nov',
12: 'dec',
}
frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
# for i in range(0, len(obj)):
# frequencies[ obj[i] -1] += 1
for i in obj:
frequencies[ i-1 ] += 1
print "The following month(s) have a birthday celebration"
for i in range(0, len(frequencies)):
if frequencies[i] > 0:
print str(months[i+1]) + " has " + str(frequencies[i])
return frequencies
in_array = [3,6,2,7,7,7,]
print freq_month(in_array)
print freq_month([])
| bluciam/ruby_versus_python | other/dicco_numbers.py | Python | gpl-2.0 | 857 |
# -*- coding: utf-8 -*-
#
# pynag - Python Nagios plug-in and configuration environment
# Copyright (C) 2010 Drew Stinnet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""This module contains low-level Parsers for nagios configuration and status objects.
Hint: If you are looking to parse some nagios configuration data, you probably
want pynag.Model module instead.
The highlights of this module are:
class Config: For Parsing nagios local nagios configuration files
class Livestatus: To connect to MK-Livestatus
class StatusDat: To read info from status.dat (not used a lot, migrate to mk-livestatus)
class LogFiles: To read nagios log-files
class MultiSite: To talk with multiple Livestatus instances
"""
import os
import re
import time
import sys
import socket # for mk_livestatus
import stat
import pynag.Plugins
import pynag.Utils
import StringIO
import tarfile
_sentinel = object()
class Config(object):
""" Parse and write nagios config files """
# Regex for beginning of object definition
# We want everything that matches:
# define <object_type> {
__beginning_of_object = re.compile("^\s*define\s+(\w+)\s*\{?(.*)$")
def __init__(self, cfg_file=None, strict=False):
""" Constructor for :py:class:`pynag.Parsers.config` class
Args:
cfg_file (str): Full path to nagios.cfg. If None, try to
auto-discover location
strict (bool): if True, use stricter parsing which is more prone to
raising exceptions
"""
self.cfg_file = cfg_file # Main configuration file
self.strict = strict # Use strict parsing or not
# If nagios.cfg is not set, lets do some minor autodiscover.
if self.cfg_file is None:
self.cfg_file = self.guess_cfg_file()
self.data = {}
self.maincfg_values = []
self._is_dirty = False
self.reset() # Initilize misc member variables
def guess_nagios_directory(self):
""" Returns a path to the nagios configuration directory on your system
Use this function for determining the nagios config directory in your
code
Returns:
str. directory containing the nagios.cfg file
Raises:
:py:class:`pynag.Parsers.ConfigFileNotFound` if cannot guess config
file location.
"""
cfg_file = self.guess_cfg_file()
if not cfg_file:
raise ConfigFileNotFound("Could not find nagios.cfg")
return os.path.dirname(cfg_file)
def guess_nagios_binary(self):
""" Returns a path to any nagios binary found on your system
Use this function if you don't want specify path to the nagios binary
in your code and you are confident that it is located in a common
location
Checked locations are as follows:
* /usr/bin/nagios
* /usr/sbin/nagios
* /usr/local/nagios/bin/nagios
* /nagios/bin/nagios
* /usr/bin/icinga
* /usr/sbin/icinga
* /usr/bin/naemon
* /usr/sbin/naemon
* /usr/local/naemon/bin/naemon.cfg
* /usr/bin/shinken
* /usr/sbin/shinken
Returns:
str. Path to the nagios binary
None if could not find a binary in any of those locations
"""
possible_files = ('/usr/bin/nagios',
'/usr/sbin/nagios',
'/usr/local/nagios/bin/nagios',
'/nagios/bin/nagios',
'/usr/bin/icinga',
'/usr/sbin/icinga',
'/usr/bin/naemon',
'/usr/sbin/naemon',
'/usr/local/naemon/bin/naemon.cfg',
'/usr/bin/shinken',
'/usr/sbin/shinken')
possible_binaries = ('nagios', 'nagios3', 'naemon', 'icinga', 'shinken')
for i in possible_binaries:
command = ['which', i]
code, stdout, stderr = pynag.Utils.runCommand(command=command, shell=False)
if code == 0:
return stdout.splitlines()[0].strip()
return None
def guess_cfg_file(self):
""" Returns a path to any nagios.cfg found on your system
Use this function if you don't want specify path to nagios.cfg in your
code and you are confident that it is located in a common location
Checked locations are as follows:
* /etc/nagios/nagios.cfg
* /etc/nagios3/nagios.cfg
* /usr/local/nagios/etc/nagios.cfg
* /nagios/etc/nagios/nagios.cfg
* ./nagios.cfg
* ./nagios/nagios.cfg
* /etc/icinga/icinga.cfg
* /usr/local/icinga/etc/icinga.cfg
* ./icinga.cfg
* ./icinga/icinga.cfg
* /etc/naemon/naemon.cfg
* /usr/local/naemon/etc/naemon.cfg
* ./naemon.cfg
* ./naemon/naemon.cfg
* /etc/shinken/shinken.cfg
Returns:
str. Path to the nagios.cfg or equivalent file
None if couldn't find a file in any of these locations.
"""
possible_files = ('/etc/nagios/nagios.cfg',
'/etc/nagios3/nagios.cfg',
'/usr/local/nagios/etc/nagios.cfg',
'/nagios/etc/nagios/nagios.cfg',
'./nagios.cfg',
'./nagios/nagios.cfg',
'/etc/icinga/icinga.cfg',
'/usr/local/icinga/etc/icinga.cfg',
'./icinga.cfg',
'./icinga/icinga.cfg',
'/etc/naemon/naemon.cfg',
'/usr/local/naemon/etc/naemon.cfg',
'./naemon.cfg',
'./naemon/naemon.cfg',
'/etc/shinken/shinken.cfg',
)
for file_path in possible_files:
if self.isfile(file_path):
return file_path
return None
def reset(self):
""" Reinitializes the data of a parser instance to its default values.
"""
self.cfg_files = [] # List of other configuration files
self.data = {} # dict of every known object definition
self.errors = [] # List of ParserErrors
self.item_list = None
self.item_cache = None
self.maincfg_values = [] # The contents of main nagios.cfg
self._resource_values = [] # The contents of any resource_files
self.item_apply_cache = {} # This is performance tweak used by _apply_template
# This is a pure listof all the key/values in the config files. It
# shouldn't be useful until the items in it are parsed through with the proper
# 'use' relationships
self.pre_object_list = []
self.post_object_list = []
self.object_type_keys = {
'hostgroup': 'hostgroup_name',
'hostextinfo': 'host_name',
'host': 'host_name',
'service': 'name',
'servicegroup': 'servicegroup_name',
'contact': 'contact_name',
'contactgroup': 'contactgroup_name',
'timeperiod': 'timeperiod_name',
'command': 'command_name',
#'service':['host_name','description'],
}
def _has_template(self, target):
""" Determine if an item has a template associated with it
Args:
target (dict): Parsed item as parsed by :py:class:`pynag.Parsers.config`
"""
return 'use' in target
def _get_pid(self):
""" Checks the lock_file var in nagios.cfg and returns the pid from the file
If the pid file does not exist, returns None.
"""
try:
return self.open(self.get_cfg_value('lock_file'), "r").readline().strip()
except Exception:
return None
def _get_hostgroup(self, hostgroup_name):
""" Returns the hostgroup that matches the queried name.
Args:
hostgroup_name: Name of the hostgroup to be returned (string)
Returns:
Hostgroup item with hostgroup_name that matches the queried name.
"""
return self.data['all_hostgroup'].get(hostgroup_name, None)
def _get_key(self, object_type, user_key=None):
""" Return the correct 'key' for an item.
This is mainly a helper method for other methods in this class. It is
used to shorten code repetition.
Args:
object_type: Object type from which to obtain the 'key' (string)
user_key: User defined key. Default None. (string)
Returns:
Correct 'key' for the object type. (string)
"""
if not user_key and not object_type in self.object_type_keys:
raise ParserError("Unknown key for object type: %s\n" % object_type)
# Use a default key
if not user_key:
user_key = self.object_type_keys[object_type]
return user_key
def _get_item(self, item_name, item_type):
""" Return an item from a list
Creates a cache of items in self.pre_object_list and returns an element
from this cache. Looks for an item with corresponding name and type.
Args:
item_name: Name of the item to be returned (string)
item_type: Type of the item to be returned (string)
Returns:
Item with matching name and type from
:py:attr:`pynag.Parsers.config.item_cache`
"""
# create local cache for performance optimizations. TODO: Rewrite functions that call this function
if not self.item_list:
self.item_list = self.pre_object_list
self.item_cache = {}
for item in self.item_list:
if not "name" in item:
continue
name = item['name']
tmp_item_type = (item['meta']['object_type'])
if not tmp_item_type in self.item_cache:
self.item_cache[tmp_item_type] = {}
self.item_cache[tmp_item_type][name] = item
my_cache = self.item_cache.get(item_type, None)
if not my_cache:
return None
return my_cache.get(item_name, None)
def _apply_template(self, original_item):
""" Apply all attributes of item named parent_name to "original_item".
Applies all of the attributes of parents (from the 'use' field) to item.
Args:
original_item: Item 'use'-ing a parent item. The parent's attributes
will be concretely added to this item.
Returns:
original_item to which have been added all the attributes defined
in parent items.
"""
# TODO: There is space for more performance tweaks here
# If item does not inherit from anyone else, lets just return item as is.
if 'use' not in original_item:
return original_item
object_type = original_item['meta']['object_type']
raw_definition = original_item['meta']['raw_definition']
my_cache = self.item_apply_cache.get(object_type, {})
# Performance tweak, if item has been parsed. Lets not do it again
if raw_definition in my_cache:
return my_cache[raw_definition]
parent_names = original_item['use'].split(',')
parent_items = []
for parent_name in parent_names:
parent_item = self._get_item(parent_name, object_type)
if parent_item is None:
error_string = "Can not find any %s named %s\n" % (object_type, parent_name)
self.errors.append(ParserError(error_string, item=original_item))
continue
try:
# Parent item probably has use flags on its own. So lets apply to parent first
parent_item = self._apply_template(parent_item)
except RuntimeError:
t, e = sys.exc_info()[:2]
self.errors.append(ParserError("Error while parsing item: %s (it might have circular use=)" % str(e),
item=original_item))
parent_items.append(parent_item)
inherited_attributes = original_item['meta']['inherited_attributes']
template_fields = original_item['meta']['template_fields']
for parent_item in parent_items:
for k, v in parent_item.iteritems():
if k in ('use', 'register', 'meta', 'name'):
continue
if k not in inherited_attributes:
inherited_attributes[k] = v
if k not in original_item:
original_item[k] = v
template_fields.append(k)
if 'name' in original_item:
my_cache[raw_definition] = original_item
return original_item
def _get_items_in_file(self, filename):
""" Return all items in the given file
Iterates through all elements in self.data and gatehrs all the items
defined in the queried filename.
Args:
filename: file from which are defined the items that will be
returned.
Returns:
A list containing all the items in self.data that were defined in
filename
"""
return_list = []
for k in self.data.keys():
for item in self[k]:
if item['meta']['filename'] == filename:
return_list.append(item)
return return_list
def get_new_item(self, object_type, filename):
""" Returns an empty item with all necessary metadata
Creates a new item dict and fills it with usual metadata:
* object_type : object_type (arg)
* filename : filename (arg)
* template_fields = []
* needs_commit = None
* delete_me = None
* defined_attributes = {}
* inherited_attributes = {}
* raw_definition = "define %s {\\n\\n} % object_type"
Args:
object_type: type of the object to be created (string)
filename: Path to which the item will be saved (string)
Returns:
A new item with default metadata
"""
meta = {
'object_type': object_type,
'filename': filename,
'template_fields': [],
'needs_commit': None,
'delete_me': None,
'defined_attributes': {},
'inherited_attributes': {},
'raw_definition': "define %s {\n\n}" % object_type,
}
return {'meta': meta}
def _load_file(self, filename):
""" Parses filename with self.parse_filename and append results in self._pre_object_list
This function is mostly here for backwards compatibility
Args:
filename: the file to be parsed. This is supposed to a nagios object definition file
"""
for i in self.parse_file(filename):
self.pre_object_list.append(i)
def parse_file(self, filename):
""" Parses a nagios object configuration file and returns lists of dictionaries.
This is more or less a wrapper around :py:meth:`config.parse_string`,
so reading documentation there is useful.
Args:
filename: Path to the file to parse (string)
Returns:
A list containing elements parsed by :py:meth:`parse_string`
"""
try:
raw_string = self.open(filename, 'rb').read()
return self.parse_string(raw_string, filename=filename)
except IOError:
t, e = sys.exc_info()[:2]
parser_error = ParserError(e.strerror)
parser_error.filename = e.filename
self.errors.append(parser_error)
return []
def parse_string(self, string, filename='None'):
""" Parses a string, and returns all object definitions in that string
Args:
string: A string containing one or more object definitions
filename (optional): If filename is provided, it will be referenced
when raising exceptions
Examples:
>>> test_string = "define host {\\nhost_name examplehost\\n}\\n"
>>> test_string += "define service {\\nhost_name examplehost\\nservice_description example service\\n}\\n"
>>> c = config()
>>> result = c.parse_string(test_string)
>>> for i in result: print i.get('host_name'), i.get('service_description', None)
examplehost None
examplehost example service
Returns:
A list of dictionaries, that look like self.data
Raises:
:py:class:`ParserError`
"""
append = ""
current = None
in_definition = {}
tmp_buffer = []
result = []
for sequence_no, line in enumerate(string.splitlines(False)):
line_num = sequence_no + 1
# If previous line ended with backslash, treat this line as a
# continuation of previous line
if append:
line = append + line
append = None
# Cleanup and line skips
line = line.strip()
if line == "":
continue
if line[0] == "#" or line[0] == ';':
continue
# If this line ends with a backslash, continue directly to next line
if line.endswith('\\'):
append = line.strip('\\')
continue
if line.startswith('}'): # end of object definition
if not in_definition:
p = ParserError("Unexpected '}' found outside object definition in line %s" % line_num)
p.filename = filename
p.line_start = line_num
raise p
in_definition = None
current['meta']['line_end'] = line_num
# Looks to me like nagios ignores everything after the } so why shouldn't we ?
rest = line.split("}", 1)[1]
tmp_buffer.append(line)
try:
current['meta']['raw_definition'] = '\n'.join(tmp_buffer)
except Exception:
raise ParserError("Encountered Unexpected end of object definition in file '%s'." % filename)
result.append(current)
# Destroy the Nagios Object
current = None
continue
elif line.startswith('define'): # beginning of object definition
if in_definition:
msg = "Unexpected 'define' in {filename} on line {line_num}. was expecting '}}'."
msg = msg.format(**locals())
self.errors.append(ParserError(msg, item=current))
m = self.__beginning_of_object.search(line)
tmp_buffer = [line]
object_type = m.groups()[0]
if self.strict and object_type not in self.object_type_keys.keys():
raise ParserError(
"Don't know any object definition of type '%s'. it is not in a list of known object definitions." % object_type)
current = self.get_new_item(object_type, filename)
current['meta']['line_start'] = line_num
# Start off an object
in_definition = True
# Looks to me like nagios ignores everything after the {, so why shouldn't we ?
rest = m.groups()[1]
continue
else: # In the middle of an object definition
tmp_buffer.append(' ' + line)
# save whatever's left in the buffer for the next iteration
if not in_definition:
append = line
continue
# this is an attribute inside an object definition
if in_definition:
#(key, value) = line.split(None, 1)
tmp = line.split(None, 1)
if len(tmp) > 1:
(key, value) = tmp
else:
key = tmp[0]
value = ""
# Strip out in-line comments
if value.find(";") != -1:
value = value.split(";", 1)[0]
# Clean info
key = key.strip()
value = value.strip()
# Rename some old values that may be in the configuration
# This can probably be removed in the future to increase performance
if (current['meta']['object_type'] == 'service') and key == 'description':
key = 'service_description'
# Special hack for timeperiods as they are not consistent with other objects
# We will treat whole line as a key with an empty value
if (current['meta']['object_type'] == 'timeperiod') and key not in ('timeperiod_name', 'alias'):
key = line
value = ''
current[key] = value
current['meta']['defined_attributes'][key] = value
# Something is wrong in the config
else:
raise ParserError("Error: Unexpected token in file '%s'" % filename)
# Something is wrong in the config
if in_definition:
raise ParserError("Error: Unexpected EOF in file '%s'" % filename)
return result
def _locate_item(self, item):
""" This is a helper function for anyone who wishes to modify objects.
It takes "item", locates the file which is configured in, and locates
exactly the lines which contain that definition.
Returns: (tuple)
(everything_before, object_definition, everything_after, filename):
* everything_before (list of lines): Every line in filename before object was defined
* everything_after (list of lines): Every line in "filename" after object was defined
* object_definition (list of lines): Every line used to define our item in "filename"
* filename (string): file in which the object was written to
Raises:
:py:class:`ValueError` if object was not found in "filename"
"""
if "filename" in item['meta']:
filename = item['meta']['filename']
else:
raise ValueError("item does not have a filename")
# Look for our item, store it as my_item
for i in self.parse_file(filename):
if self.compareObjects(item, i):
my_item = i
break
else:
raise ValueError("We could not find object in %s\n%s" % (filename, item))
# Caller of this method expects to be returned
# several lists that describe the lines in our file.
# The splitting logic starts here.
my_file = self.open(filename)
all_lines = my_file.readlines()
my_file.close()
start = my_item['meta']['line_start'] - 1
end = my_item['meta']['line_end']
everything_before = all_lines[:start]
object_definition = all_lines[start:end]
everything_after = all_lines[end:]
# If there happen to be line continuations in the object we will edit
# We will remove them from object_definition
object_definition = self._clean_backslashes(object_definition)
return everything_before, object_definition, everything_after, filename
def _clean_backslashes(self, list_of_strings):
""" Returns list_of_strings with all all strings joined that ended with backslashes
Args:
list_of_strings: List of strings to join
Returns:
Another list of strings, which lines ending with \ joined together.
"""
tmp_buffer = ''
result = []
for i in list_of_strings:
if i.endswith('\\\n'):
tmp_buffer += i.strip('\\\n')
else:
result.append(tmp_buffer + i)
tmp_buffer = ''
return result
def _modify_object(self, item, field_name=None, new_value=None, new_field_name=None, new_item=None,
make_comments=False):
""" Locates "item" and changes the line which contains field_name.
Helper function for object_* functions. Locates "item" and changes the
line which contains field_name. If new_value and new_field_name are both
None, the attribute is removed.
Args:
item(dict): The item to be modified
field_name(str): The field_name to modify (if any)
new_field_name(str): If set, field_name will be renamed
new_value(str): If set the value of field_name will be changed
new_item(str): If set, whole object will be replaced with this
string
make_comments: If set, put pynag-branded comments where changes
have been made
Returns:
True on success
Raises:
:py:class:`ValueError` if object or field_name is not found
:py:class:`IOError` is save is unsuccessful.
"""
if item is None:
return
if field_name is None and new_item is None:
raise ValueError("either field_name or new_item must be set")
if '\n' in str(new_value):
raise ValueError("Invalid character \\n used as an attribute value.")
everything_before, object_definition, everything_after, filename = self._locate_item(item)
if new_item is not None:
# We have instruction on how to write new object, so we dont need to parse it
object_definition = [new_item]
else:
change = None
value = None
i = 0
for i in range(len(object_definition)):
tmp = object_definition[i].split(None, 1)
if len(tmp) == 0:
continue
# Hack for timeperiods, they dont work like other objects
elif item['meta']['object_type'] == 'timeperiod' and field_name not in ('alias', 'timeperiod_name'):
tmp = [object_definition[i]]
# we can't change timeperiod, so we fake a field rename
if new_value is not None:
new_field_name = new_value
new_value = None
value = ''
elif len(tmp) == 1:
value = ''
else:
value = tmp[1]
k = tmp[0].strip()
if k == field_name:
# Attribute was found, lets change this line
if new_field_name is None and new_value is None:
# We take it that we are supposed to remove this attribute
change = object_definition.pop(i)
break
elif new_field_name:
# Field name has changed
k = new_field_name
if new_value is not None:
# value has changed
value = new_value
# Here we do the actual change
change = "\t%-30s%s\n" % (k, value)
if item['meta']['object_type'] == 'timeperiod' and field_name not in ('alias', 'timeperiod_name'):
change = "\t%s\n" % new_field_name
object_definition[i] = change
break
if not change and new_value is not None:
# Attribute was not found. Lets add it
change = "\t%-30s%s\n" % (field_name, new_value)
object_definition.insert(i, change)
# Lets put a banner in front of our item
if make_comments:
comment = '# Edited by PyNag on %s\n' % time.ctime()
if len(everything_before) > 0:
last_line_before = everything_before[-1]
if last_line_before.startswith('# Edited by PyNag on'):
everything_before.pop() # remove this line
object_definition.insert(0, comment)
# Here we overwrite the config-file, hoping not to ruin anything
str_buffer = "%s%s%s" % (''.join(everything_before), ''.join(object_definition), ''.join(everything_after))
self.write(filename, str_buffer)
return True
def open(self, filename, *args, **kwargs):
""" Wrapper around global open()
Simply calls global open(filename, *args, **kwargs) and passes all arguments
as they are received. See global open() function for more details.
"""
return open(filename, *args, **kwargs)
@pynag.Utils.synchronized(pynag.Utils.rlock)
def write(self, filename, string):
""" Wrapper around open(filename).write()
Writes string to filename and closes the file handler. File handler is
openned in `'w'` mode.
Args:
filename: File where *string* will be written. This is the path to
the file. (string)
string: String to be written to file. (string)
Returns:
Return code as returned by :py:meth:`os.write`
"""
fh = self.open(filename, 'w')
return_code = fh.write(string)
fh.flush()
# os.fsync(fh)
fh.close()
self._is_dirty = True
return return_code
def item_rewrite(self, item, str_new_item):
""" Completely rewrites item with string provided.
Args:
item: Item that is to be rewritten
str_new_item: str representation of the new item
..
In the following line, every "\\n" is actually a simple line break
This is only a little patch for the generated documentation.
Examples::
item_rewrite( item, "define service {\\n name example-service \\n register 0 \\n }\\n" )
Returns:
True on success
Raises:
:py:class:`ValueError` if object is not found
:py:class:`IOError` if save fails
"""
return self._modify_object(item=item, new_item=str_new_item)
def item_remove(self, item):
""" Delete one specific item from its configuration files
Args:
item: Item that is to be rewritten
str_new_item: string representation of the new item
..
In the following line, every "\\n" is actually a simple line break
This is only a little patch for the generated documentation.
Examples::
item_remove( item, "define service {\\n name example-service \\n register 0 \\n }\\n" )
Returns:
True on success
Raises:
:py:class:`ValueError` if object is not found
:py:class:`IOError` if save fails
"""
return self._modify_object(item=item, new_item="")
def item_edit_field(self, item, field_name, new_value):
""" Modifies one field of a (currently existing) object.
Changes are immediate (i.e. there is no commit)
Args:
item: Item to be modified. Its field `field_name` will be set to
`new_value`.
field_name: Name of the field that will be modified. (str)
new_value: Value to which will be set the field `field_name`. (str)
Example usage::
edit_object( item, field_name="host_name", new_value="examplehost.example.com") # doctest: +SKIP
Returns:
True on success
Raises:
:py:class:`ValueError` if object is not found
:py:class:`IOError` if save fails
"""
return self._modify_object(item, field_name=field_name, new_value=new_value)
def item_remove_field(self, item, field_name):
""" Removes one field of a (currently existing) object.
Changes are immediate (i.e. there is no commit)
Args:
item: Item to remove field from.
field_name: Field to remove. (string)
Example usage::
item_remove_field( item, field_name="contactgroups" )
Returns:
True on success
Raises:
:py:class:`ValueError` if object is not found
:py:class:`IOError` if save fails
"""
return self._modify_object(item=item, field_name=field_name, new_value=None, new_field_name=None)
def item_rename_field(self, item, old_field_name, new_field_name):
""" Renames a field of a (currently existing) item.
Changes are immediate (i.e. there is no commit).
Args:
item: Item to modify.
old_field_name: Name of the field that will have its name changed. (string)
new_field_name: New name given to `old_field_name` (string)
Example usage::
item_rename_field(item, old_field_name="normal_check_interval", new_field_name="check_interval")
Returns:
True on success
Raises:
:py:class:`ValueError` if object is not found
:py:class:`IOError` if save fails
"""
return self._modify_object(item=item, field_name=old_field_name, new_field_name=new_field_name)
def item_add(self, item, filename):
""" Adds a new object to a specified config file.
Args:
item: Item to be created
filename: Filename that we are supposed to write the new item to.
This is the path to the file. (string)
Returns:
True on success
Raises:
:py:class:`IOError` on failed save
"""
if not 'meta' in item:
item['meta'] = {}
item['meta']['filename'] = filename
# Create directory if it does not already exist
dirname = os.path.dirname(filename)
if not self.isdir(dirname):
os.makedirs(dirname)
str_buffer = self.print_conf(item)
fh = self.open(filename, 'a')
fh.write(str_buffer)
fh.close()
return True
def edit_object(self, item, field_name, new_value):
""" Modifies a (currently existing) item.
Changes are immediate (i.e. there is no commit)
Args:
item: Item to modify.
field_name: Field that will be updated.
new_value: Updated value of field `field_name`
Example Usage:
edit_object( item, field_name="host_name", new_value="examplehost.example.com")
Returns:
True on success
.. WARNING::
THIS FUNCTION IS DEPRECATED. USE item_edit_field() instead
"""
return self.item_edit_field(item=item, field_name=field_name, new_value=new_value)
def compareObjects(self, item1, item2):
""" Compares two items. Returns true if they are equal
Compares every key: value pair for both items. If anything is different,
the items will not be considered equal.
Args:
item1, item2: Items to be compared.
Returns:
True -- Items are equal
False -- Items are not equal
"""
keys1 = item1['meta']['defined_attributes'].keys()
keys2 = item2['meta']['defined_attributes'].keys()
keys1.sort()
keys2.sort()
result = True
if keys1 != keys2:
return False
for key in keys1:
if key == 'meta':
continue
key1 = item1[key]
key2 = item2[key]
# For our purpose, 30 is equal to 30.000
if key == 'check_interval':
key1 = int(float(key1))
key2 = int(float(key2))
if str(key1) != str(key2):
result = False
if result is False:
return False
return True
def edit_service(self, target_host, service_description, field_name, new_value):
""" Edit a service's attributes
Takes a host, service_description pair to identify the service to modify
and sets its field `field_name` to `new_value`.
Args:
target_host: name of the host to which the service is attached to. (string)
service_description: Service description of the service to modify. (string)
field_name: Field to modify. (string)
new_value: Value to which the `field_name` field will be updated (string)
Returns:
True on success
Raises:
:py:class:`ParserError` if the service is not found
"""
original_object = self.get_service(target_host, service_description)
if original_object is None:
raise ParserError("Service not found")
return self.edit_object(original_object, field_name, new_value)
def _get_list(self, item, key):
""" Return a comma list from an item
Args:
item: Item from which to select value. (string)
key: Field name of the value to select and return as a list. (string)
Example::
_get_list(Foo_object, host_name)
define service {
service_description Foo
host_name larry,curly,moe
}
returns
['larry','curly','moe']
Returns:
A list of the item's values of `key`
Raises:
:py:class:`ParserError` if item is not a dict
"""
if not isinstance(item, dict):
raise ParserError("%s is not a dictionary\n" % item)
# return []
if not key in item:
return []
return_list = []
if item[key].find(",") != -1:
for name in item[key].split(","):
return_list.append(name)
else:
return_list.append(item[key])
# Alphabetize
return_list.sort()
return return_list
def delete_object(self, object_type, object_name, user_key=None):
""" Delete object from configuration files
Args:
object_type: Type of the object to delete from configuration files.
object_name: Name of the object to delete from configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
True on success.
"""
item = self.get_object(object_type=object_type, object_name=object_name, user_key=user_key)
return self.item_remove(item)
def delete_service(self, service_description, host_name):
""" Delete service from configuration files
Args:
service_description: service_description field value of the object
to delete from configuration files.
host_name: host_name field value of the object to delete from
configuration files.
Returns:
True on success.
"""
item = self.get_service(host_name, service_description)
return self.item_remove(item)
def delete_host(self, object_name, user_key=None):
""" Delete a host from its configuration files
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
True on success.
"""
return self.delete_object('host', object_name, user_key=user_key)
def delete_hostgroup(self, object_name, user_key=None):
""" Delete a hostgroup from its configuration files
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
True on success.
"""
return self.delete_object('hostgroup', object_name, user_key=user_key)
def get_object(self, object_type, object_name, user_key=None):
""" Return a complete object dictionary
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: User defined key. Default None. (string)
Returns:
The item found to match all the criterias.
None if object is not found
"""
object_key = self._get_key(object_type, user_key)
for item in self.data['all_%s' % object_type]:
if item.get(object_key, None) == object_name:
return item
return None
def get_host(self, object_name, user_key=None):
""" Return a host object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('host', object_name, user_key=user_key)
def get_servicegroup(self, object_name, user_key=None):
""" Return a Servicegroup object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('servicegroup', object_name, user_key=user_key)
def get_contact(self, object_name, user_key=None):
""" Return a Contact object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('contact', object_name, user_key=user_key)
def get_contactgroup(self, object_name, user_key=None):
""" Return a Contactgroup object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('contactgroup', object_name, user_key=user_key)
def get_timeperiod(self, object_name, user_key=None):
""" Return a Timeperiod object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('timeperiod', object_name, user_key=user_key)
def get_command(self, object_name, user_key=None):
""" Return a Command object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('command', object_name, user_key=user_key)
def get_hostgroup(self, object_name, user_key=None):
""" Return a hostgroup object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('hostgroup', object_name, user_key=user_key)
def get_servicedependency(self, object_name, user_key=None):
""" Return a servicedependency object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('servicedependency', object_name, user_key=user_key)
def get_hostdependency(self, object_name, user_key=None):
""" Return a hostdependency object
Args:
object_name: object_name field value of the object to delete from
configuration files.
user_key: user_key to pass to :py:meth:`get_object`
Returns:
The item found to match all the criterias.
"""
return self.get_object('hostdependency', object_name, user_key=user_key)
def get_service(self, target_host, service_description):
""" Return a service object
Args:
target_host: host_name field of the service to be returned. This is
the host to which is attached the service.
service_description: service_description field of the service to be
returned.
Returns:
The item found to match all the criterias.
"""
for item in self.data['all_service']:
if item.get('service_description') == service_description and item.get('host_name') == target_host:
return item
return None
def _append_use(self, source_item, name):
""" Append attributes to source_item that are inherited via 'use' attribute'
Args:
source_item: item (dict) to apply the inheritance upon
name: obsolete (discovered automatically via source_item['use'].
Here for compatibility.
Returns:
Source Item with appended attributes.
Raises:
:py:class:`ParserError` on recursion errors
"""
# Remove the 'use' key
if "use" in source_item:
del source_item['use']
for possible_item in self.pre_object_list:
if "name" in possible_item:
# Start appending to the item
for k, v in possible_item.iteritems():
try:
if k == 'use':
source_item = self._append_use(source_item, v)
except Exception:
raise ParserError("Recursion error on %s %s" % (source_item, v))
# Only add the item if it doesn't already exist
if not k in source_item:
source_item[k] = v
return source_item
def _post_parse(self):
""" Creates a few optimization tweaks and easy access lists in self.data
Creates :py:attr:`config.item_apply_cache` and fills the all_object
item lists in self.data.
"""
self.item_list = None
self.item_apply_cache = {} # This is performance tweak used by _apply_template
for raw_item in self.pre_object_list:
# Performance tweak, make sure hashmap exists for this object_type
object_type = raw_item['meta']['object_type']
if not object_type in self.item_apply_cache:
self.item_apply_cache[object_type] = {}
# Tweak ends
if "use" in raw_item:
raw_item = self._apply_template(raw_item)
self.post_object_list.append(raw_item)
# Add the items to the class lists.
for list_item in self.post_object_list:
type_list_name = "all_%s" % list_item['meta']['object_type']
if not type_list_name in self.data:
self.data[type_list_name] = []
self.data[type_list_name].append(list_item)
def commit(self):
""" Write any changes that have been made to it's appropriate file """
# Loops through ALL items
for k in self.data.keys():
for item in self[k]:
# If the object needs committing, commit it!
if item['meta']['needs_commit']:
# Create file contents as an empty string
file_contents = ""
# find any other items that may share this config file
extra_items = self._get_items_in_file(item['meta']['filename'])
if len(extra_items) > 0:
for commit_item in extra_items:
# Ignore files that are already set to be deleted:w
if commit_item['meta']['delete_me']:
continue
# Make sure we aren't adding this thing twice
if item != commit_item:
file_contents += self.print_conf(commit_item)
# This is the actual item that needs commiting
if not item['meta']['delete_me']:
file_contents += self.print_conf(item)
# Write the file
filename = item['meta']['filename']
self.write(filename, file_contents)
# Recreate the item entry without the commit flag
self.data[k].remove(item)
item['meta']['needs_commit'] = None
self.data[k].append(item)
def flag_all_commit(self):
""" Flag every item in the configuration to be committed
This should probably only be used for debugging purposes
"""
for object_type in self.data.keys():
for item in self.data[object_type]:
item['meta']['needs_commit'] = True
def print_conf(self, item):
""" Return a string that can be used in a configuration file
Args:
item: Item to be dumped as a string.
Returns:
String representation of item.
"""
output = ""
# Header, to go on all files
output += "# Configuration file %s\n" % item['meta']['filename']
output += "# Edited by PyNag on %s\n" % time.ctime()
# Some hostgroup information
if "hostgroup_list" in item['meta']:
output += "# Hostgroups: %s\n" % ",".join(item['meta']['hostgroup_list'])
# Some hostgroup information
if "service_list" in item['meta']:
output += "# Services: %s\n" % ",".join(item['meta']['service_list'])
# Some hostgroup information
if "service_members" in item['meta']:
output += "# Service Members: %s\n" % ",".join(item['meta']['service_members'])
if len(item['meta']['template_fields']) != 0:
output += "# Values from templates:\n"
for k in item['meta']['template_fields']:
output += "#\t %-30s %-30s\n" % (k, item[k])
output += "\n"
output += "define %s {\n" % item['meta']['object_type']
for k, v in item.iteritems():
if v is None:
# Skip entries with No value
continue
if k != 'meta':
if k not in item['meta']['template_fields']:
output += "\t %-30s %-30s\n" % (k, v)
output += "}\n\n"
return output
def _load_static_file(self, filename=None):
""" Load a general config file (like nagios.cfg) that has key=value config file format. Ignore comments
Arguments:
filename: name of file to parse, if none nagios.cfg will be used
Returns:
a [ (key,value), (key,value) ] list
"""
result = []
if not filename:
filename = self.cfg_file
for line in self.open(filename).readlines():
# Strip out new line characters
line = line.strip()
# Skip blank lines
if line == "":
continue
# Skip comments
if line[0] == "#" or line[0] == ';':
continue
tmp = line.split("=", 1)
if len(tmp) < 2:
continue
key, value = tmp
key = key.strip()
value = value.strip()
result.append((key, value))
return result
def _edit_static_file(self, attribute, new_value, filename=None, old_value=None, append=False):
""" Modify a general config file (like nagios.cfg) that has a key=value config file format.
Arguments:
filename: Name of config file that will be edited (i.e. nagios.cfg)
attribute: name of attribute to edit (i.e. check_external_commands)
new_value: new value for the said attribute (i.e. "1"). None deletes
the line.
old_value: Useful if multiple attributes exist (i.e. cfg_dir) and
you want to replace a specific one.
append: If true, do not overwrite current setting. Instead append
this at the end. Use this with settings that are repeated like
cfg_file.
Examples::
_edit_static_file(filename='/etc/nagios/nagios.cfg', attribute='check_external_commands', new_value='1')
_edit_static_file(filename='/etc/nagios/nagios.cfg', attribute='cfg_dir', new_value='/etc/nagios/okconfig', append=True)
"""
if filename is None:
filename = self.cfg_file
# For some specific attributes, append should be implied
if attribute in ('cfg_file', 'cfg_dir', 'broker_module'):
append = True
# If/when we make a change, new_line is what will be written
new_line = '%s=%s\n' % (attribute, new_value)
# new_value=None means line should be removed
if new_value is None:
new_line = ''
write_buffer = self.open(filename).readlines()
is_dirty = False # dirty if we make any changes
for i, line in enumerate(write_buffer):
# Strip out new line characters
line = line.strip()
# Skip blank lines
if line == "":
continue
# Skip comments
if line[0] == "#" or line[0] == ';':
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# If key does not match, we are not interested in this line
if key != attribute:
continue
# If old_value was specified, and it matches, dont have to look any further
elif value == old_value:
write_buffer[i] = new_line
is_dirty = True
break
# if current value is the same as new_value, no need to make changes
elif value == new_value:
return False
# Special so cfg_dir matches despite double-slashes, etc
elif attribute == 'cfg_dir' and new_value and os.path.normpath(value) == os.path.normpath(new_value):
return False
# We are not appending, and no old value was specified:
elif append is False and not old_value:
write_buffer[i] = new_line
is_dirty = True
break
if is_dirty is False and new_value is not None:
# If we get here, it means we read the whole file,
# and we have not yet made any changes, So we assume
# We should append to the file
write_buffer.append(new_line)
is_dirty = True
# When we get down here, it is time to write changes to file
if is_dirty is True:
str_buffer = ''.join(write_buffer)
self.write(filename, str_buffer)
return True
else:
return False
def needs_reload(self):
""" Checks if the Nagios service needs a reload.
Returns:
True if Nagios service needs reload of cfg files
False if reload not needed or Nagios is not running
"""
if not self.maincfg_values:
self.reset()
self.parse_maincfg()
new_timestamps = self.get_timestamps()
object_cache_file = self.get_cfg_value('object_cache_file')
if self._get_pid() is None:
return False
if not object_cache_file:
return True
if not self.isfile(object_cache_file):
return True
object_cache_timestamp = new_timestamps.get(object_cache_file, 0)
# Reload not needed if no object_cache file
if object_cache_file is None:
return False
for k, v in new_timestamps.items():
if not v or int(v) > object_cache_timestamp:
return True
return False
def needs_reparse(self):
""" Checks if the Nagios configuration needs to be reparsed.
Returns:
True if any Nagios configuration file has changed since last parse()
"""
# If Parse has never been run:
if self.data == {}:
return True
# If previous save operation has forced a reparse
if self._is_dirty is True:
return True
# If we get here, we check the timestamps of the configs
new_timestamps = self.get_timestamps()
if len(new_timestamps) != len(self.timestamps):
return True
for k, v in new_timestamps.items():
if self.timestamps.get(k, None) != v:
return True
return False
@pynag.Utils.synchronized(pynag.Utils.rlock)
def parse_maincfg(self):
""" Parses your main configuration (nagios.cfg) and stores it as key/value pairs in self.maincfg_values
This function is mainly used by config.parse() which also parses your
whole configuration set.
Raises:
py:class:`ConfigFileNotFound`
"""
# If nagios.cfg is not set, lets do some minor autodiscover.
if self.cfg_file is None:
raise ConfigFileNotFound('Could not find nagios.cfg')
self.maincfg_values = self._load_static_file(self.cfg_file)
@pynag.Utils.synchronized(pynag.Utils.rlock)
def parse(self):
""" Parse all objects in your nagios configuration
This functions starts by loading up your nagios.cfg ( parse_maincfg() )
then moving on to your object configuration files (as defined via
cfg_file and cfg_dir) and and your resource_file as well.
Returns:
None
Raises:
:py:class:`IOError` if unable to read any file due to permission
problems
"""
# reset
self.reset()
self.parse_maincfg()
self.cfg_files = self.get_cfg_files()
# When parsing config, we will softly fail if permission denied
# comes on resource files. If later someone tries to get them via
# get_resource, we will fail hard
try:
self._resource_values = self.get_resources()
except IOError:
t, e = sys.exc_info()[:2]
self.errors.append(str(e))
self.timestamps = self.get_timestamps()
# This loads everything into
for cfg_file in self.cfg_files:
self._load_file(cfg_file)
self._post_parse()
self._is_dirty = False
def get_resource(self, resource_name):
""" Get a single resource value which can be located in any resource.cfg file
Arguments:
resource_name: Name as it appears in resource file (i.e. $USER1$)
Returns:
String value of the resource value.
Raises:
:py:class:`KeyError` if resource is not found
:py:class:`ParserError` if resource is not found and you do not have
permissions
"""
resources = self.get_resources()
for k, v in resources:
if k == resource_name:
return v
def get_timestamps(self):
""" Returns hash map of all nagios related files and their timestamps"""
files = {}
files[self.cfg_file] = None
for k, v in self.maincfg_values:
if k in ('resource_file', 'lock_file', 'object_cache_file'):
files[v] = None
for i in self.get_cfg_files():
files[i] = None
# Now lets lets get timestamp of every file
for k, v in files.items():
if not self.isfile(k):
continue
files[k] = self.stat(k).st_mtime
return files
def isfile(self, *args, **kwargs):
""" Wrapper around os.path.isfile """
return os.path.isfile(*args, **kwargs)
def isdir(self, *args, **kwargs):
""" Wrapper around os.path.isdir """
return os.path.isdir(*args, **kwargs)
def islink(self, *args, **kwargs):
""" Wrapper around os.path.islink """
return os.path.islink(*args, **kwargs)
def readlink(selfself, *args, **kwargs):
""" Wrapper around os.readlink """
return os.readlink(*args, **kwargs)
def stat(self, *args, **kwargs):
""" Wrapper around os.stat """
return os.stat(*args, **kwargs)
def remove(self, *args, **kwargs):
""" Wrapper around os.remove """
return os.remove(*args, **kwargs)
def access(self, *args, **kwargs):
""" Wrapper around os.access """
return os.access(*args, **kwargs)
def listdir(self, *args, **kwargs):
""" Wrapper around os.listdir """
return os.listdir(*args, **kwargs)
def exists(self, *args, **kwargs):
""" Wrapper around os.path.exists """
return os.path.exists(*args, **kwargs)
def get_resources(self):
"""Returns a list of every private resources from nagios.cfg"""
resources = []
for config_object, config_value in self.maincfg_values:
if config_object == 'resource_file' and self.isfile(config_value):
resources += self._load_static_file(config_value)
return resources
def extended_parse(self):
""" This parse is used after the initial parse() command is run.
It is only needed if you want extended meta information about hosts or other objects
"""
# Do the initial parsing
self.parse()
# First, cycle through the hosts, and append hostgroup information
index = 0
for host in self.data['all_host']:
if host.get("register", None) == "0":
continue
if not "host_name" in host:
continue
if not "hostgroup_list" in self.data['all_host'][index]['meta']:
self.data['all_host'][index]['meta']['hostgroup_list'] = []
# Append any hostgroups that are directly listed in the host definition
if "hostgroups" in host:
for hostgroup_name in self._get_list(host, 'hostgroups'):
if not "hostgroup_list" in self.data['all_host'][index]['meta']:
self.data['all_host'][index]['meta']['hostgroup_list'] = []
if hostgroup_name not in self.data['all_host'][index]['meta']['hostgroup_list']:
self.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup_name)
# Append any services which reference this host
service_list = []
for service in self.data['all_service']:
if service.get("register", None) == "0":
continue
if not "service_description" in service:
continue
if host['host_name'] in self._get_active_hosts(service):
service_list.append(service['service_description'])
self.data['all_host'][index]['meta']['service_list'] = service_list
# Increment count
index += 1
# Loop through all hostgroups, appending them to their respective hosts
for hostgroup in self.data['all_hostgroup']:
for member in self._get_list(hostgroup, 'members'):
index = 0
for host in self.data['all_host']:
if not "host_name" in host:
continue
# Skip members that do not match
if host['host_name'] == member:
# Create the meta var if it doesn' exist
if not "hostgroup_list" in self.data['all_host'][index]['meta']:
self.data['all_host'][index]['meta']['hostgroup_list'] = []
if hostgroup['hostgroup_name'] not in self.data['all_host'][index]['meta']['hostgroup_list']:
self.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup['hostgroup_name'])
# Increment count
index += 1
# Expand service membership
index = 0
for service in self.data['all_service']:
# Find a list of hosts to negate from the final list
self.data['all_service'][index]['meta']['service_members'] = self._get_active_hosts(service)
# Increment count
index += 1
def _get_active_hosts(self, item):
""" Given an object, return a list of active hosts.
This will exclude hosts that are negated with a "!"
Args:
item: Item to obtain active hosts from.
Returns:
List of all the active hosts for `item`
"""
# First, generate the negation list
negate_hosts = []
# Hostgroups
if "hostgroup_name" in item:
for hostgroup_name in self._get_list(item, 'hostgroup_name'):
if hostgroup_name[0] == "!":
hostgroup_obj = self.get_hostgroup(hostgroup_name[1:])
negate_hosts.extend(self._get_list(hostgroup_obj, 'members'))
# Host Names
if "host_name" in item:
for host_name in self._get_list(item, 'host_name'):
if host_name[0] == "!":
negate_hosts.append(host_name[1:])
# Now get hosts that are actually listed
active_hosts = []
# Hostgroups
if "hostgroup_name" in item:
for hostgroup_name in self._get_list(item, 'hostgroup_name'):
if hostgroup_name[0] != "!":
active_hosts.extend(self._get_list(self.get_hostgroup(hostgroup_name), 'members'))
# Host Names
if "host_name" in item:
for host_name in self._get_list(item, 'host_name'):
if host_name[0] != "!":
active_hosts.append(host_name)
# Combine the lists
return_hosts = []
for active_host in active_hosts:
if active_host not in negate_hosts:
return_hosts.append(active_host)
return return_hosts
def get_cfg_dirs(self):
""" Parses the main config file for configuration directories
Returns:
List of all cfg directories used in this configuration
Example::
print(get_cfg_dirs())
['/etc/nagios/hosts','/etc/nagios/objects',...]
"""
cfg_dirs = []
for config_object, config_value in self.maincfg_values:
if config_object == "cfg_dir":
cfg_dirs.append(config_value)
return cfg_dirs
def get_cfg_files(self):
""" Return a list of all cfg files used in this configuration
Filenames are normalised so that if nagios.cfg specifies relative
filenames we will convert it to fully qualified filename before returning.
Returns:
List of all configurations files used in the configuration.
Example:
print(get_cfg_files())
['/etc/nagios/hosts/host1.cfg','/etc/nagios/hosts/host2.cfg',...]
"""
cfg_files = []
for config_object, config_value in self.maincfg_values:
# Add cfg_file objects to cfg file list
if config_object == "cfg_file":
config_value = self.abspath(config_value)
if self.isfile(config_value):
cfg_files.append(config_value)
# Parse all files in a cfg directory
if config_object == "cfg_dir":
config_value = self.abspath(config_value)
directories = []
raw_file_list = []
directories.append(config_value)
# Walk through every subdirectory and add to our list
while directories:
current_directory = directories.pop(0)
# Nagios doesnt care if cfg_dir exists or not, so why should we ?
if not self.isdir(current_directory):
continue
for item in self.listdir(current_directory):
# Append full path to file
item = "%s" % (os.path.join(current_directory, item.strip()))
if self.islink(item):
item = os.readlink(item)
if self.isdir(item):
directories.append(item)
if raw_file_list.count(item) < 1:
raw_file_list.append(item)
for raw_file in raw_file_list:
if raw_file.endswith('.cfg'):
if self.exists(raw_file) and not self.isdir(raw_file):
# Nagios doesnt care if cfg_file exists or not, so we will not throws errors
cfg_files.append(raw_file)
return cfg_files
def abspath(self, path):
""" Return the absolute path of a given relative path.
The current working directory is assumed to be the dirname of nagios.cfg
Args:
path: relative path to be transformed into absolute path. (string)
Returns:
Absolute path of given relative path.
Example:
>>> c = config(cfg_file="/etc/nagios/nagios.cfg")
>>> c.abspath('nagios.cfg')
'/etc/nagios/nagios.cfg'
>>> c.abspath('/etc/nagios/nagios.cfg')
'/etc/nagios/nagios.cfg'
"""
if not isinstance(path, str):
return ValueError("Path must be a string got %s instead" % type(path))
if path.startswith('/'):
return path
nagiosdir = os.path.dirname(self.cfg_file)
normpath = os.path.abspath(os.path.join(nagiosdir, path))
return normpath
def get_cfg_value(self, key):
""" Returns one specific value from your nagios.cfg file,
None if value is not found.
Arguments:
key: what attribute to fetch from nagios.cfg (example: "command_file" )
Returns:
String of the first value found for
Example:
>>> c = Config() # doctest: +SKIP
>>> log_file = c.get_cfg_value('log_file') # doctest: +SKIP
# Should return something like "/var/log/nagios/nagios.log"
"""
if not self.maincfg_values:
self.parse_maincfg()
for k, v in self.maincfg_values:
if k == key:
return v
return None
def get_object_types(self):
""" Returns a list of all discovered object types """
return map(lambda x: re.sub("all_", "", x), self.data.keys())
def cleanup(self):
""" Remove configuration files that have no configuration items """
for filename in self.cfg_files:
if not self.parse_file(filename): # parse_file returns empty list on empty files
self.remove(filename)
# If nagios.cfg specifies this file directly via cfg_file directive then...
for k, v in self.maincfg_values:
if k == 'cfg_file' and v == filename:
self._edit_static_file(k, old_value=v, new_value=None)
def __setitem__(self, key, item):
self.data[key] = item
def __getitem__(self, key):
return self.data[key]
class Livestatus(object):
""" Wrapper around MK-Livestatus
Example usage::
s = Livestatus()
for hostgroup s.get_hostgroups():
print(hostgroup['name'], hostgroup['num_hosts'])
"""
def __init__(self, livestatus_socket_path=None, nagios_cfg_file=None, authuser=None):
""" Initilize a new instance of Livestatus
Args:
livestatus_socket_path: Path to livestatus socket (if none specified,
use one specified in nagios.cfg)
nagios_cfg_file: Path to your nagios.cfg. If None then try to
auto-detect
authuser: If specified. Every data pulled is with the access rights
of that contact.
"""
self.nagios_cfg_file = nagios_cfg_file
self.error = None
if not livestatus_socket_path:
c = config(cfg_file=nagios_cfg_file)
c.parse_maincfg()
self.nagios_cfg_file = c.cfg_file
# Look for a broker_module line in the main config and parse its arguments
# One of the arguments is path to the file socket created
for k, v in c.maincfg_values:
if k == 'broker_module' and "livestatus.o" in v:
for arg in v.split()[1:]:
if arg.startswith('/') or '=' not in arg:
livestatus_socket_path = arg
break
else:
# If we get here, then we could not locate a broker_module argument
# that looked like a filename
msg = "No Livestatus socket defined. Make sure livestatus broker module is loaded."
raise ParserError(msg)
self.livestatus_socket_path = livestatus_socket_path
self.authuser = authuser
def test(self, raise_error=True):
""" Test if connection to livestatus socket is working
Args:
raise_error: If set to True, raise exception if test fails,otherwise return False
Raises:
ParserError if raise_error == True and connection fails
Returns:
True -- Connection is OK
False -- there are problems and raise_error==False
"""
try:
self.query("GET hosts")
except Exception:
t, e = sys.exc_info()[:2]
self.error = e
if raise_error:
raise ParserError("got '%s' when testing livestatus socket. error was: '%s'" % (type(e), e))
else:
return False
return True
def _get_socket(self):
""" Returns a socket.socket() instance to communicate with livestatus
Socket might be either unix filesocket or a tcp socket depenging in
the content of :py:attr:`livestatus_socket_path`
Returns:
Socket to livestatus instance (socket.socket)
Raises:
:py:class:`LivestatusNotConfiguredException` on failed connection.
:py:class:`ParserError` If could not parse configured TCP address
correctly.
"""
if not self.livestatus_socket_path:
msg = "We could not find path to MK livestatus socket file. Make sure MK livestatus is installed and configured"
raise LivestatusNotConfiguredException(msg)
try:
# If livestatus_socket_path contains a colon, then we assume that it is tcp socket instead of a local filesocket
if self.livestatus_socket_path.find(':') > 0:
address, tcp_port = self.livestatus_socket_path.split(':', 1)
if not tcp_port.isdigit():
msg = 'Could not parse host:port "%s". %s does not look like a valid port is not a valid tcp port.'
raise ParserError(msg % (self.livestatus_socket_path, tcp_port))
tcp_port = int(tcp_port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((address, tcp_port))
else:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(self.livestatus_socket_path)
return s
except IOError:
t, e = sys.exc_info()[:2]
msg = "%s while connecting to '%s'. Make sure nagios is running and mk_livestatus loaded."
raise ParserError(msg % (e, self.livestatus_socket_path))
def query(self, query, *args, **kwargs):
""" Performs LQL queries the livestatus socket
Queries are corrected and convienient default data are added to the
query before sending it to the socket.
Args:
query: Query to be passed to the livestatus socket (string)
args, kwargs: Additionnal parameters that will be sent to
:py:meth:`pynag.Utils.grep_to_livestatus`. The result will be
appended to the query.
Returns:
Answer from livestatus. It will be in python format unless specified
otherwise.
Raises:
:py:class:`ParserError` if problems connecting to livestatus.
"""
# columns parameter is here for backwards compatibility only
kwargs.pop('columns', None)
# We break query up into a list, of commands, then before sending command to the socket
# We will write it one line per item in the array
query = query.split('\n')
query += pynag.Utils.grep_to_livestatus(*args, **kwargs)
# If no response header was specified, we add fixed16
response_header = None
if not filter(lambda x: x.startswith('ResponseHeader:'), query):
query.append("ResponseHeader: fixed16")
response_header = "fixed16"
# If no specific outputformat is requested, we will return in python format
python_format = False
if not filter(lambda x: x.startswith('OutputFormat:'), query):
query.append("OutputFormat: python")
python_format = True
# There is a bug in livestatus where if requesting Stats, then no column headers are sent from livestatus
# In later version, the headers are sent, but the output is corrupted.
#
# We maintain consistency by clinging on to the old bug, and if there are Stats in the output
# we will not ask for column headers
doing_stats = len(filter(lambda x: x.startswith('Stats:'), query)) > 0
if not filter(lambda x: x.startswith('Stats:'), query) and not filter(
lambda x: x.startswith('ColumnHeaders: on'), query):
query.append("ColumnHeaders: on")
# Check if we need to add authuser to the query
if not filter(lambda x: x.startswith('AuthUser:'), query) and self.authuser not in (None, ''):
query.append("AuthUser: %s" % self.authuser)
# When we reach here, we are done adding options to the query, so we convert to the string that will
# be sent to the livestatus socket
query = '\n'.join(query) + '\n'
self.last_query = query
#
# Lets create a socket and see if we can write to it
#
s = self._get_socket()
try:
s.send(query)
except IOError:
msg = "Could not write to socket '%s'. Make sure you have the right permissions"
raise ParserError(msg % self.livestatus_socket_path)
s.shutdown(socket.SHUT_WR)
tmp = s.makefile()
# Read the response header from livestatus
if response_header == "fixed16":
response_data = tmp.readline()
if len(response_data) == 0:
return []
return_code = response_data.split()[0]
if not return_code.startswith('2'):
error_message = tmp.readline().strip()
raise ParserError("Error '%s' from livestatus: %s" % (return_code, error_message))
answer = tmp.read()
# We are done with the livestatus socket. lets close it
s.close()
if answer == '':
return []
# If something other than python format was requested, we return the answer as is
if python_format is False:
return answer
# If we reach down here, it means we are supposed to parse the output before returning it
try:
answer = eval(answer)
except Exception:
raise ParserError("Error, could not parse response from livestatus.\n%s" % answer)
# Workaround for livestatus bug, where column headers are not provided even if we asked for them
if doing_stats is True and len(answer) == 1:
return answer[0]
columns = answer.pop(0)
# Lets throw everything into a hashmap before we return
result = []
for line in answer:
tmp = {}
for i, column in enumerate(line):
column_name = columns[i]
tmp[column_name] = column
result.append(tmp)
return result
def get(self, table, *args, **kwargs):
""" Same as self.query('GET %s' % (table,))
Extra arguments will be appended to the query.
Args:
table: Table from which the data will be retrieved
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Example::
get('contacts', 'Columns: name alias')
Returns:
Answer from livestatus in python format.
"""
return self.query('GET %s' % (table,), *args, **kwargs)
def get_host(self, host_name):
""" Performs a GET query for a particular host
This performs::
'''GET hosts
Filter: host_name = %s''' % host_name
Args:
host_name: name of the host to obtain livestatus data from
Returns:
Answer from livestatus in python format.
"""
return self.query('GET hosts', 'Filter: host_name = %s' % host_name)[0]
def get_service(self, host_name, service_description):
""" Performs a GET query for a particular service
This performs::
'''GET services
Filter: host_name = %s
Filter: service_description = %s''' % (host_name, service_description)
Args:
host_name: name of the host the target service is attached to.
service_description: Description of the service to obtain livestatus
data from.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET services', 'Filter: host_name = %s' % host_name,
'Filter: description = %s' % service_description)[0]
def get_hosts(self, *args, **kwargs):
""" Performs a GET query for all hosts
This performs::
'''GET hosts %s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET hosts', *args, **kwargs)
def get_services(self, *args, **kwargs):
""" Performs a GET query for all services
This performs::
'''GET services
%s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET services', *args, **kwargs)
def get_hostgroups(self, *args, **kwargs):
""" Performs a GET query for all hostgroups
This performs::
'''GET hostgroups
%s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET hostgroups', *args, **kwargs)
def get_servicegroups(self, *args, **kwargs):
""" Performs a GET query for all servicegroups
This performs::
'''GET servicegroups
%s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET servicegroups', *args, **kwargs)
def get_contactgroups(self, *args, **kwargs):
""" Performs a GET query for all contactgroups
This performs::
'''GET contactgroups
%s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET contactgroups', *args, **kwargs)
def get_contacts(self, *args, **kwargs):
""" Performs a GET query for all contacts
This performs::
'''GET contacts
%s %s''' % (*args, **kwargs)
Args:
args, kwargs: These will be appendend to the end of the query to
perform additionnal instructions.
Returns:
Answer from livestatus in python format.
"""
return self.query('GET contacts', *args, **kwargs)
def get_contact(self, contact_name):
""" Performs a GET query for a particular contact
This performs::
'''GET contacts
Filter: contact_name = %s''' % contact_name
Args:
contact_name: name of the contact to obtain livestatus data from
Returns:
Answer from livestatus in python format.
"""
return self.query('GET contacts', 'Filter: contact_name = %s' % contact_name)[0]
def get_servicegroup(self, name):
""" Performs a GET query for a particular servicegroup
This performs::
'''GET servicegroups
Filter: servicegroup_name = %s''' % servicegroup_name
Args:
servicegroup_name: name of the servicegroup to obtain livestatus data from
Returns:
Answer from livestatus in python format.
"""
return self.query('GET servicegroups', 'Filter: name = %s' % name)[0]
def get_hostgroup(self, name):
""" Performs a GET query for a particular hostgroup
This performs::
'''GET hostgroups
Filter: hostgroup_name = %s''' % hostgroup_name
Args:
hostgroup_name: name of the hostgroup to obtain livestatus data from
Returns:
Answer from livestatus in python format.
"""
return self.query('GET hostgroups', 'Filter: name = %s' % name)[0]
def get_contactgroup(self, name):
""" Performs a GET query for a particular contactgroup
This performs::
'''GET contactgroups
Filter: contactgroup_name = %s''' % contactgroup_name
Args:
contactgroup_name: name of the contactgroup to obtain livestatus data from
Returns:
Answer from livestatus in python format.
"""
return self.query('GET contactgroups', 'Filter: name = %s' % name)[0]
class RetentionDat(object):
""" Easy way to parse the content of retention.dat
After calling parse() contents of retention.dat are kept in self.data
Example Usage::
r = retention()
r.parse()
print r
print r.data['info']
"""
def __init__(self, filename=None, cfg_file=None):
""" Initilize a new instance of retention.dat
Args (you only need to provide one of these):
filename: path to your retention.dat file
cfg_file: path to your nagios.cfg file, path to retention.dat will
be looked up in this file
"""
# If filename is not provided, lets try to discover it from
# nagios.cfg
if filename is None:
c = config(cfg_file=cfg_file)
for key, value in c._load_static_file():
if key == "state_retention_file":
filename = value
self.filename = filename
self.data = None
def parse(self):
""" Parses your status.dat file and stores in a dictionary under self.data
Returns:
None
Raises:
:py:class:`ParserError`: if problem arises while reading status.dat
:py:class:`ParserError`: if status.dat is not found
:py:class:`IOError`: if status.dat cannot be read
"""
self.data = {}
status = {} # Holds all attributes of a single item
key = None # if within definition, store everything before =
value = None # if within definition, store everything after =
if not self.filename:
raise ParserError("status.dat file not found")
lines = open(self.filename, 'rb').readlines()
for sequence_no, line in enumerate(lines):
line_num = sequence_no + 1
# Cleanup and line skips
line = line.strip()
if line == "":
pass
elif line[0] == "#" or line[0] == ';':
pass
elif line.find("{") != -1:
status = {}
status['meta'] = {}
status['meta']['type'] = line.split("{")[0].strip()
elif line.find("}") != -1:
# Status definition has finished, lets add it to
# self.data
if status['meta']['type'] not in self.data:
self.data[status['meta']['type']] = []
self.data[status['meta']['type']].append(status)
else:
tmp = line.split("=", 1)
if len(tmp) == 2:
(key, value) = line.split("=", 1)
status[key] = value
elif key == "long_plugin_output":
# special hack for long_output support. We get here if:
# * line does not contain {
# * line does not contain }
# * line does not contain =
# * last line parsed started with long_plugin_output=
status[key] += "\n" + line
else:
raise ParserError("Error on %s:%s: Could not parse line: %s" % (self.filename, line_num, line))
def __setitem__(self, key, item):
self.data[key] = item
def __getitem__(self, key):
return self.data[key]
def __str__(self):
if not self.data:
self.parse()
str_buffer = "# Generated by pynag"
for datatype, datalist in self.data.items():
for item in datalist:
str_buffer += "%s {\n" % datatype
for attr, value in item.items():
str_buffer += "%s=%s\n" % (attr, value)
str_buffer += "}\n"
return str_buffer
class StatusDat(RetentionDat):
""" Easy way to parse status.dat file from nagios
After calling parse() contents of status.dat are kept in status.data
Example usage::
>>> s = status()
>>> s.parse()
>>> keys = s.data.keys()
>>> 'info' in keys
True
>>> 'programstatus' in keys
True
>>> for service in s.data.get('servicestatus',[]):
... host_name=service.get('host_name', None)
... description=service.get('service_description',None)
"""
def __init__(self, filename=None, cfg_file=None):
""" Initilize a new instance of status
Args (you only need to provide one of these):
filename: path to your status.dat file
cfg_file: path to your nagios.cfg file, path to status.dat will be
looked up in this file
"""
# If filename is not provided, lets try to discover it from
# nagios.cfg
if filename is None:
c = config(cfg_file=cfg_file)
for key, value in c._load_static_file():
if key == "status_file":
filename = value
self.filename = filename
self.data = None
def get_contactstatus(self, contact_name):
""" Returns a dictionary derived from status.dat for one particular contact
Args:
contact_name: `contact_name` field of the contact's status.dat data
to parse and return as a dict.
Returns:
dict derived from status.dat for the contact.
Raises:
ValueError if object is not found
Example:
>>> s = status()
>>> s.get_contactstatus(contact_name='invalid_contact')
ValueError('invalid_contact',)
>>> first_contact = s.data['contactstatus'][0]['contact_name']
>>> s.get_contactstatus(first_contact)['contact_name'] == first_contact
True
"""
if self.data is None:
self.parse()
for i in self.data['contactstatus']:
if i.get('contact_name') == contact_name:
return i
return ValueError(contact_name)
def get_hoststatus(self, host_name):
""" Returns a dictionary derived from status.dat for one particular contact
Args:
host_name: `host_name` field of the host's status.dat data
to parse and return as a dict.
Returns:
dict derived from status.dat for the host.
Raises:
ValueError if object is not found
"""
if self.data is None:
self.parse()
for i in self.data['hoststatus']:
if i.get('host_name') == host_name:
return i
raise ValueError(host_name)
def get_servicestatus(self, host_name, service_description):
""" Returns a dictionary derived from status.dat for one particular service
Args:
service_name: `service_name` field of the host's status.dat data
to parse and return as a dict.
Returns:
dict derived from status.dat for the service.
Raises:
ValueError if object is not found
"""
if self.data is None:
self.parse()
for i in self.data['servicestatus']:
if i.get('host_name') == host_name:
if i.get('service_description') == service_description:
return i
raise ValueError(host_name, service_description)
class ObjectCache(Config):
""" Loads the configuration as it appears in objects.cache file """
def get_cfg_files(self):
for k, v in self.maincfg_values:
if k == 'object_cache_file':
return [v]
class ParserError(Exception):
""" ParserError is used for errors that the Parser has when parsing config.
Typical usecase when there is a critical error while trying to read configuration.
"""
filename = None
line_start = None
message = None
def __init__(self, message, item=None):
""" Creates an instance of ParserError
Args:
message: Message to be printed by the error
item: Pynag item who caused the error
"""
self.message = message
if item is None:
return
self.item = item
self.filename = item['meta']['filename']
self.line_start = item['meta'].get('line_start')
def __str__(self):
message = self.message
if self.filename and self.line_start:
message = '%s in %s, line %s' % (message, self.filename, self.line_start)
return repr(message)
class ConfigFileNotFound(ParserError):
""" This exception is thrown if we cannot locate any nagios.cfg-style config file. """
pass
class LivestatusNotConfiguredException(ParserError):
""" This exception is raised if we tried to autodiscover path to livestatus and failed """
class LogFiles(object):
""" Parses Logfiles defined in nagios.cfg and allows easy access to its content
Content is stored in python-friendly arrays of dicts. Output should be more
or less compatible with mk_livestatus log output
"""
def __init__(self, maincfg=None):
self.config = config(maincfg)
self.log_file = self.config.get_cfg_value('log_file')
self.log_archive_path = self.config.get_cfg_value('log_archive_path')
def get_log_entries(self, start_time=None, end_time=None, strict=True, search=None, **kwargs):
""" Get Parsed log entries for given timeperiod.
Args:
start_time: unix timestamp. if None, return all entries from today
end_time: If specified, only fetch log entries older than this (unix
timestamp)
strict: If True, only return entries between start_time and
end_time, if False, then return entries that belong to same log
files as given timeset
search: If provided, only return log entries that contain this
string (case insensitive)
kwargs: All extra arguments are provided as filter on the log
entries. f.e. host_name="localhost"
Returns:
List of dicts
"""
now = time.time()
if end_time is None:
end_time = now
if start_time is None:
if 'filename' in kwargs:
start_time = 1
else:
seconds_in_a_day = 60 * 60 * 24
seconds_today = end_time % seconds_in_a_day # midnight of today
start_time = end_time - seconds_today
start_time = int(start_time)
end_time = int(end_time)
logfiles = self.get_logfiles()
if 'filename' in kwargs:
logfiles = filter(lambda x: x == kwargs.get('filename'), logfiles)
# If start time was provided, skip all files that we last modified
# before start_time
if start_time:
logfiles = filter(lambda x: start_time <= os.stat(x).st_mtime, logfiles)
# Log entries are returned in ascending order, which is the opposite of
# what get_logfiles returns.
logfiles.reverse()
result = []
for log_file in logfiles:
entries = self._parse_log_file(filename=log_file)
if len(entries) == 0:
continue
first_entry = entries[0]
last_entry = entries[-1]
if first_entry['time'] > end_time:
continue
# If strict, filter entries to only include the ones in the timespan
if strict is True:
entries = [x for x in entries if x['time'] >= start_time and x['time'] <= end_time]
# If search string provided, filter the string
if search is not None:
entries = [x for x in entries if x['message'].lower().find(search.lower()) > -1]
for k, v in kwargs.items():
entries = [x for x in entries if x.get(k) == v]
result += entries
if start_time is None or int(start_time) >= int(first_entry.get('time')):
continue
# Now, logfiles should in MOST cases come sorted for us.
# However we rely on modification time of files and if it is off,
# We want to make sure log entries are coming in the correct order.
# The following sort should not impact performance in the typical use case.
result.sort(key=lambda x: x.get('time'))
return result
def get_logfiles(self):
""" Returns a list with the fullpath to every log file used by nagios.
Lists are sorted by modification times. Newest logfile is at the front
of the list so usually nagios.log comes first, followed by archivelogs
Returns:
List of strings
"""
logfiles = []
for filename in os.listdir(self.log_archive_path):
full_path = "%s/%s" % (self.log_archive_path, filename)
logfiles.append(full_path)
logfiles.append(self.log_file)
# Sort the logfiles by modification time, newest file at the front
compare_mtime = lambda a, b: os.stat(a).st_mtime < os.stat(b).st_mtime
logfiles.sort(key=lambda x: int(os.stat(x).st_mtime))
# Newest logfiles go to the front of the list
logfiles.reverse()
return logfiles
def get_flap_alerts(self, **kwargs):
""" Same as :py:meth:`get_log_entries`, except return timeperiod transitions.
Takes same parameters.
"""
return self.get_log_entries(class_name="timeperiod transition", **kwargs)
def get_notifications(self, **kwargs):
""" Same as :py:meth:`get_log_entries`, except return only notifications.
Takes same parameters.
"""
return self.get_log_entries(class_name="notification", **kwargs)
def get_state_history(self, start_time=None, end_time=None, host_name=None, strict=True, service_description=None):
""" Returns a list of dicts, with the state history of hosts and services.
Args:
start_time: unix timestamp. if None, return all entries from today
end_time: If specified, only fetch log entries older than this (unix
timestamp)
host_name: If provided, only return log entries that contain this
string (case insensitive)
service_description: If provided, only return log entries that contain this
string (case insensitive)
Returns:
List of dicts with state history of hosts and services
"""
log_entries = self.get_log_entries(start_time=start_time, end_time=end_time, strict=strict, class_name='alerts')
result = []
last_state = {}
now = time.time()
for line in log_entries:
if 'state' not in line:
continue
line['duration'] = now - int(line.get('time'))
if host_name is not None and host_name != line.get('host_name'):
continue
if service_description is not None and service_description != line.get('service_description'):
continue
if start_time is None:
start_time = int(line.get('time'))
short_name = "%s/%s" % (line['host_name'], line['service_description'])
if short_name in last_state:
last = last_state[short_name]
last['end_time'] = line['time']
last['duration'] = last['end_time'] - last['time']
line['previous_state'] = last['state']
last_state[short_name] = line
if strict is True:
if start_time is not None and int(start_time) > int(line.get('time')):
continue
if end_time is not None and int(end_time) < int(line.get('time')):
continue
result.append(line)
return result
def _parse_log_file(self, filename=None):
""" Parses one particular nagios logfile into arrays of dicts.
Args:
filename: Log file to be parsed. If is None, then log_file from
nagios.cfg is used.
Returns:
A list of dicts containing all data from the log file
"""
if filename is None:
filename = self.log_file
result = []
for line in open(filename).readlines():
parsed_entry = self._parse_log_line(line)
if parsed_entry != {}:
parsed_entry['filename'] = filename
result.append(parsed_entry)
return result
def _parse_log_line(self, line):
""" Parse one particular line in nagios logfile and return a dict.
Args:
line: Line of the log file to be parsed.
Returns:
dict containing the information from the log file line.
"""
host = None
service_description = None
state = None
check_attempt = None
plugin_output = None
contact = None
m = re.search('^\[(.*?)\] (.*?): (.*)', line)
if m is None:
return {}
line = line.strip()
timestamp, logtype, options = m.groups()
result = {}
try:
timestamp = int(timestamp)
except ValueError:
timestamp = 0
result['time'] = int(timestamp)
result['type'] = logtype
result['options'] = options
result['message'] = line
result['class'] = 0 # unknown
result['class_name'] = 'unclassified'
if logtype in ('CURRENT HOST STATE', 'CURRENT SERVICE STATE', 'SERVICE ALERT', 'HOST ALERT'):
result['class'] = 1
result['class_name'] = 'alerts'
if logtype.find('HOST') > -1:
# This matches host current state:
m = re.search('(.*?);(.*?);(.*);(.*?);(.*)', options)
if m is None:
return result
host, state, hard, check_attempt, plugin_output = m.groups()
service_description = None
if logtype.find('SERVICE') > -1:
m = re.search('(.*?);(.*?);(.*?);(.*?);(.*?);(.*)', options)
if m is None:
return result
host, service_description, state, hard, check_attempt, plugin_output = m.groups()
result['host_name'] = host
result['service_description'] = service_description
result['state'] = int(pynag.Plugins.state[state])
result['check_attempt'] = check_attempt
result['plugin_output'] = plugin_output
result['text'] = plugin_output
elif "NOTIFICATION" in logtype:
result['class'] = 3
result['class_name'] = 'notification'
if logtype == 'SERVICE NOTIFICATION':
m = re.search('(.*?);(.*?);(.*?);(.*?);(.*?);(.*)', options)
if m is None:
return result
contact, host, service_description, state, command, plugin_output = m.groups()
elif logtype == 'HOST NOTIFICATION':
m = re.search('(.*?);(.*?);(.*?);(.*?);(.*)', options)
if m is None:
return result
contact, host, state, command, plugin_output = m.groups()
service_description = None
result['contact_name'] = contact
result['host_name'] = host
result['service_description'] = service_description
try:
result['state'] = int(pynag.Plugins.state[state])
except Exception:
result['state'] = -1
result['plugin_output'] = plugin_output
result['text'] = plugin_output
elif logtype == "EXTERNAL COMMAND":
result['class'] = 5
result['class_name'] = 'command'
m = re.search('(.*?);(.*)', options)
if m is None:
return result
command_name, text = m.groups()
result['command_name'] = command_name
result['text'] = text
elif logtype in ('PASSIVE SERVICE CHECK', 'PASSIVE HOST CHECK'):
result['class'] = 4
result['class_name'] = 'passive'
if logtype.find('HOST') > -1:
# This matches host current state:
m = re.search('(.*?);(.*?);(.*)', options)
if m is None:
return result
host, state, plugin_output = m.groups()
service_description = None
if logtype.find('SERVICE') > -1:
m = re.search('(.*?);(.*?);(.*?);(.*)', options)
if m is None:
return result
host, service_description, state, plugin_output = m.groups()
result['host_name'] = host
result['service_description'] = service_description
result['state'] = state
result['plugin_output'] = plugin_output
result['text'] = plugin_output
elif logtype in ('SERVICE FLAPPING ALERT', 'HOST FLAPPING ALERT'):
result['class_name'] = 'flapping'
elif logtype == 'TIMEPERIOD TRANSITION':
result['class_name'] = 'timeperiod_transition'
elif logtype == 'Warning':
result['class_name'] = 'warning'
result['state'] = "1"
result['text'] = options
if 'text' not in result:
result['text'] = result['options']
result['log_class'] = result['class'] # since class is a python keyword
return result
class ExtraOptsParser(object):
""" Get Nagios Extra-Opts from a config file as specified by http://nagiosplugins.org/extra-opts
We could ALMOST use pythons ConfParser but nagios plugin team thought it would be a
good idea to support multiple values per key, so a dict datatype no longer works.
Its a shame because we have to make our own "ini" parser as a result
Usage::
# cat /etc/nagios/plugins.ini
[main]
host_name = localhost
[other section]
host_name = example.com
# EOF
e = ExtraOptsParser(section_name='main', config_file='/etc/nagios/plugins.ini')
e.get('host_name') # returns "localhost"
e.get_values() # Returns a dict of all the extra opts
e.getlist('host_name') # returns all values of host_name (if more than one were specified) in a list
"""
standard_locations = [
"/etc/nagios/plugins.ini",
"/usr/local/nagios/etc/plugins.ini",
"/usr/local/etc/nagios/plugins.ini",
"/etc/opt/nagios/plugins.ini",
"/etc/nagios-plugins.ini",
"/usr/local/etc/nagios-plugins.ini",
"/etc/opt/nagios-plugins.ini",
]
def __init__(self, section_name=None, config_file=None):
if not section_name:
section_name = self.get_default_section_name()
if not config_file:
config_file = self.get_default_config_file()
self.section_name = section_name
self.config_file = config_file
self._all_options = self.parse_file(filename=config_file) or {}
def get_values(self):
""" Returns a dict with all extra-options with the granted section_name and config_file
Results are in the form of::
{
'key': ["possible","values"]
}
"""
return self._all_options.get(self.section_name, {})
def get_default_section_name(self):
""" According to extra-opts standard, the default should be filename of check script being run """
return os.path.basename(sys.argv[0])
def get_default_config_file(self):
""" Return path to first readable extra-opt config-file found
According to the nagiosplugins extra-opts spec the search method is as follows:
1. Search for nagios.ini or nagios-plugins.ini in : splitted variable NAGIOS_CONFIG_PATH
2. Search in a predefined list of files
3. Return None if no config file is found
The method works as follows:
To quote the spec on NAGIOS_CONFIG_PATH:
*"To use a custom location, set a NAGIOS_CONFIG_PATH environment
variable to the set of directories that should be checked (this is a
colon-separated list just like PATH). The first plugins.ini or
nagios-plugins.ini file found in these directories will be used."*
"""
search_path = []
nagios_config_path = os.environ.get('NAGIOS_CONFIG_PATH', '')
for path in nagios_config_path.split(':'):
search_path.append(os.path.join(path, 'plugins.ini'))
search_path.append(os.path.join(path, 'nagios-plugins.ini'))
search_path += self.standard_locations
self.search_path = search_path
for path in search_path:
if os.path.isfile(path):
return path
return None
def get(self, option_name, default=_sentinel):
""" Return the value of one specific option
Args:
option_name: The value set to this option will be returned
Returns:
The value of `option_name`
Raises:
:py:class:`ValueError` when `option_name` cannot be found in options
"""
result = self.getlist(option_name, default)
# If option was not found, raise error
if result == _sentinel:
raise ValueError("Option named %s was not found" % (option_name))
elif result == default:
return result
elif not result:
# empty list
return result
else:
return result[0]
def getlist(self, option_name, default=_sentinel):
""" Return a list of all values for option_name
Args:
option_name: All the values set to this option will be returned
Returns:
List containing all the options set to `option_name`
Raises:
:py:class:`ValueError` when `option_name` cannot be found in options
"""
result = self.get_values().get(option_name, default)
if result == _sentinel:
raise ValueError("Option named %s was not found" % (option_name))
return result
def parse_file(self, filename):
""" Parses an ini-file and returns a dict of the ini values.
The datatype returned is a list of sections where each section is a
dict of values.
Args:
filename: Full path to the ini-file to be parsed.
Example the following the file::
[main]
name = this is a name
key = value
key = value2
Would return::
[
{'main':
{
'name': ['this is a name'],
'key': [value, value2]
}
},
]
"""
if filename is None:
return {}
f = open(filename)
try:
data = f.read()
return self.parse_string(data)
finally:
f.close()
def parse_string(self, string):
""" Parses a string that is supposed to be ini-style format.
See :py:meth:`parse_file` for more info
Args:
string: String to be parsed. Should be in ini-file format.
Returns:
Dictionnary containing all the sections of the ini-file and their
respective data.
Raises:
:py:class:`ParserError` when line does not follow the ini format.
"""
sections = {}
# When parsing inside a section, the name of it stored here.
section_name = None
current_section = pynag.Utils.defaultdict(dict)
for line_no, line, in enumerate(string.splitlines()):
line = line.strip()
# skip empty lines
if not line or line[0] in ('#', ';'):
continue
# Check if this is a new section
if line.startswith('[') and line.endswith(']'):
section_name = line.strip('[').strip(']').strip()
current_section = pynag.Utils.defaultdict(list)
sections[section_name] = current_section
continue
# All entries should have key=value format
if not '=' in line:
error = "Line %s should be in the form of key=value format (got '%s' instead)" % (line_no, line)
raise ParserError(error)
# If we reach here, we parse current line into key and a value section
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
sections[section_name][key].append(value)
return sections
class SshConfig(Config):
""" Parse object configuration files from remote host via ssh
Uses python-paramiko for ssh connections.
"""
def __init__(self, host, username, password=None, cfg_file=None):
""" Creates a SshConfig instance
Args:
host: Host to connect to
username: User to connect with
password: Password for `username`
cfg_file: Nagios main cfg file
"""
import paramiko
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(host, username=username, password=password)
self.ftp = self.ssh.open_sftp()
import cStringIO
c = cStringIO.StringIO()
self.tar = tarfile.open(mode='w', fileobj=c)
self.cached_stats = {}
super(SshConfig, self).__init__(cfg_file=cfg_file)
def open(self, filename, *args, **kwargs):
""" Behaves like file.open only, via ssh connection """
return self.tar.extractfile(filename)
tarinfo = self._get_file(filename)
string = tarinfo.tobuf()
print string
return StringIO.StringIO(string)
return self.tar.extractfile(tarinfo)
def add_to_tar(self, path):
"""
"""
print "Taring ", path
command = "find '{path}' -type f | tar -c -T - --to-stdout --absolute-names"
command = command.format(path=path)
print command
stdin, stdout, stderr = self.ssh.exec_command(command, bufsize=50000)
tar = tarfile.open(fileobj=stdout, mode='r|')
if not self.tar:
self.tar = tar
# return
else:
for i in tar:
self.tar.addfile(i)
def is_cached(self, filename):
if not self.tar:
return False
return filename in self.tar.getnames()
def _get_file(self, filename):
""" Download filename and return the TarInfo object """
if filename not in self.tar.getnames():
self.add_to_tar(filename)
return self.tar.getmember(filename)
def get_cfg_files(self):
cfg_files = []
for config_object, config_value in self.maincfg_values:
# Add cfg_file objects to cfg file list
if config_object == "cfg_file":
config_value = self.abspath(config_value)
if self.isfile(config_value):
cfg_files.append(config_value)
elif config_object == "cfg_dir":
absolut_path = self.abspath(config_value)
command = "find '%s' -type f -iname \*cfg" % (absolut_path)
stdin, stdout, stderr = self.ssh.exec_command(command)
raw_filelist = stdout.read().splitlines()
cfg_files += raw_filelist
else:
continue
if not self.is_cached(config_value):
self.add_to_tar(config_value)
return cfg_files
def isfile(self, path):
""" Behaves like os.path.isfile only, via ssh connection """
try:
copy = self._get_file(path)
return copy.isfile()
except IOError:
return False
def isdir(self, path):
""" Behaves like os.path.isdir only, via ssh connection """
try:
file_stat = self.stat(path)
return stat.S_ISDIR(file_stat.st_mode)
except IOError:
return False
def islink(self, path):
""" Behaves like os.path.islink only, via ssh connection """
try:
file_stat = self.stat(path)
return stat.S_ISLNK(file_stat.st_mode)
except IOError:
return False
def readlink(self, path):
""" Behaves like os.readlink only, via ssh connection """
return self.ftp.readlink(path)
def stat(self, *args, **kwargs):
""" Wrapper around os.stat only, via ssh connection """
path = args[0]
if not self.is_cached(path):
self.add_to_tar(path)
if path not in self.tar.getnames():
raise IOError("No such file or directory %s" % path)
member = self.tar.getmember(path)
member.st_mode = member.mode
member.st_mtime = member.mtime
return member
def access(self, *args, **kwargs):
""" Wrapper around os.access only, via ssh connection """
return os.access(*args, **kwargs)
def exists(self, path):
""" Wrapper around os.path.exists only, via ssh connection """
try:
self.ftp.stat(path)
return True
except IOError:
return False
def listdir(self, *args, **kwargs):
""" Wrapper around os.listdir but via ssh connection """
stats = self.ftp.listdir_attr(*args, **kwargs)
for i in stats:
self.cached_stats[args[0] + "/" + i.filename] = i
files = map(lambda x: x.filename, stats)
return files
class MultiSite(Livestatus):
""" Wrapps around multiple Livesatus instances and aggregates the results
of queries.
Example:
>>> m = MultiSite()
>>> m.add_backend(path='/var/spool/nagios/livestatus.socket', name='local')
>>> m.add_backend(path='127.0.0.1:5992', name='remote')
"""
def __init__(self, *args, **kwargs):
super(MultiSite, self).__init__(*args, **kwargs)
self.backends = {}
def add_backend(self, path, name):
""" Add a new livestatus backend to this instance.
Arguments:
path (str): Path to file socket or remote address
name (str): Friendly shortname for this backend
"""
backend = Livestatus(
livestatus_socket_path=path,
nagios_cfg_file=self.nagios_cfg_file,
authuser=self.authuser
)
self.backends[name] = backend
def get_backends(self):
""" Returns a list of mk_livestatus instances
Returns:
list. List of mk_livestatus instances
"""
return self.backends
def get_backend(self, backend_name):
""" Return one specific backend that has previously been added
"""
if not backend_name:
return self.backends.values()[0]
try:
return self.backends[backend_name]
except KeyError:
raise ParserError("No backend found with name='%s'" % backend_name)
def query(self, query, *args, **kwargs):
""" Behaves like mk_livestatus.query() except results are aggregated from multiple backends
Arguments:
backend (str): If specified, fetch only data from this backend (see add_backend())
*args: Passed directly to mk_livestatus.query()
**kwargs: Passed directly to mk_livestatus.query()
"""
result = []
backend = kwargs.pop('backend', None)
# Special hack, if 'Stats' argument was provided to livestatus
# We have to maintain compatibility with old versions of livestatus
# and return single list with all results instead of a list of dicts
doing_stats = any(map(lambda x: x.startswith('Stats:'), args + (query,)))
# Iterate though all backends and run the query
# TODO: Make this multithreaded
for name, backend_instance in self.backends.items():
# Skip if a specific backend was requested and this is not it
if backend and backend != name:
continue
query_result = backend_instance.query(query, *args, **kwargs)
if doing_stats:
result = self._merge_statistics(result, query_result)
else:
for row in query_result:
row['backend'] = name
result.append(row)
return result
def _merge_statistics(self, list1, list2):
""" Merges multiple livestatus results into one result
Arguments:
list1 (list): List of integers
list2 (list): List of integers
Returns:
list. Aggregated results of list1 + list2
Example:
>>> result1 = [1,1,1,1]
>>> result2 = [2,2,2,2]
>>> MultiSite()._merge_statistics(result1, result2)
[3, 3, 3, 3]
"""
if not list1:
return list2
if not list2:
return list1
number_of_columns = len(list1)
result = [0] * number_of_columns
for row in (list1, list2):
for i, column in enumerate(row):
result[i] += column
return result
def get_host(self, host_name, backend=None):
""" Same as Livestatus.get_host() """
backend = self.get_backend(backend)
return backend.get_host(host_name)
def get_service(self, host_name, service_description, backend=None):
""" Same as Livestatus.get_service() """
backend = self.get_backend(backend)
return backend.get_service(host_name, service_description)
def get_contact(self, contact_name, backend=None):
""" Same as Livestatus.get_contact() """
backend = self.get_backend(backend)
return backend.get_contact(contact_name)
def get_contactgroup(self, contactgroup_name, backend=None):
""" Same as Livestatus.get_contact() """
backend = self.get_backend(backend)
return backend.get_contactgroup(contactgroup_name)
def get_servicegroup(self, servicegroup_name, backend=None):
""" Same as Livestatus.get_servicegroup() """
backend = self.get_backend(backend)
return backend.get_servicegroup(servicegroup_name)
def get_hostgroup(self, hostgroup_name, backend=None):
""" Same as Livestatus.get_hostgroup() """
backend = self.get_backend(backend)
return backend.get_hostgroup(hostgroup_name)
class config(Config):
""" This class is here only for backwards compatibility. Use Config instead. """
class mk_livestatus(Livestatus):
""" This class is here only for backwards compatibility. Use Livestatus instead. """
class object_cache(ObjectCache):
""" This class is here only for backwards compatibility. Use ObjectCache instead. """
class status(StatusDat):
""" This class is here only for backwards compatibility. Use StatusDat instead. """
class retention(RetentionDat):
""" This class is here only for backwards compatibility. Use RetentionDat instead. """
if __name__ == '__main__':
import time
start = time.time()
ssh = SshConfig(host='status.adagios.org', username='palli')
ssh.ssh.get_transport().window_size = 3 * 1024 * 1024
ssh.ssh.get_transport().use_compression()
# ssh.add_to_tar('/etc/nagios')
# sys.exit()
# ssh.ssh.exec_command("/bin/ls")
print "before reset"
ssh.parse()
end = time.time()
print "duration=", end - start
bland = ssh.tar.getmember('/etc/nagios/okconfig/hosts/web-servers/bland.is-http.cfg')
print bland.tobuf()
sys.exit(0)
print "ssh up"
ssh_conn = FastTransport(('status.adagios.org', 22))
ssh_conn.connect(username='palli')
ftp = paramiko.SFTPClient.from_transport(ssh_conn)
print "connected" \
""
ssh.ssh = ssh_conn
ssh.ftp = ftp
print "starting parse"
print "done parsing"
| kaji-project/pynag | pynag/Parsers/__init__.py | Python | gpl-2.0 | 129,457 |
/*
FILE
tTemplate source code of unxsISP.cgi
Built by mysqlRAD2.cgi (C) Gary Wallis and Hugo Urquiza 2001-2009
svn ID removed
PURPOSE
Schema dependent RAD generated file.
Program app functionality in ttemplatefunc.h while
RAD is still to be used.
*/
#include "mysqlrad.h"
//Table Variables
//Table Variables
//uTemplate: Primary Key
static unsigned uTemplate=0;
//cLabel: Short label
static char cLabel[33]={""};
//uTemplateSet: Short label
static unsigned uTemplateSet=0;
static char cuTemplateSetPullDown[256]={""};
//uTemplateType: Short label
static unsigned uTemplateType=0;
static char cuTemplateTypePullDown[256]={""};
//cComment: About the template
static char *cComment={""};
//cTemplate: Template itself
static char *cTemplate={""};
//uOwner: Record owner
static unsigned uOwner=0;
//uCreatedBy: uClient for last insert
static unsigned uCreatedBy=0;
#define ISM3FIELDS
//uCreatedDate: Unix seconds date last insert
static time_t uCreatedDate=0;
//uModBy: uClient for last update
static unsigned uModBy=0;
//uModDate: Unix seconds date last update
static time_t uModDate=0;
#define VAR_LIST_tTemplate "tTemplate.uTemplate,tTemplate.cLabel,tTemplate.uTemplateSet,tTemplate.uTemplateType,tTemplate.cComment,tTemplate.cTemplate,tTemplate.uOwner,tTemplate.uCreatedBy,tTemplate.uCreatedDate,tTemplate.uModBy,tTemplate.uModDate"
//Local only
void Insert_tTemplate(void);
void Update_tTemplate(char *cRowid);
void ProcesstTemplateListVars(pentry entries[], int x);
//In tTemplatefunc.h file included below
void ExtProcesstTemplateVars(pentry entries[], int x);
void ExttTemplateCommands(pentry entries[], int x);
void ExttTemplateButtons(void);
void ExttTemplateNavBar(void);
void ExttTemplateGetHook(entry gentries[], int x);
void ExttTemplateSelect(void);
void ExttTemplateSelectRow(void);
void ExttTemplateListSelect(void);
void ExttTemplateListFilter(void);
void ExttTemplateAuxTable(void);
#include "ttemplatefunc.h"
//Table Variables Assignment Function
void ProcesstTemplateVars(pentry entries[], int x)
{
register int i;
for(i=0;i<x;i++)
{
if(!strcmp(entries[i].name,"uTemplate"))
sscanf(entries[i].val,"%u",&uTemplate);
else if(!strcmp(entries[i].name,"cLabel"))
sprintf(cLabel,"%.32s",entries[i].val);
else if(!strcmp(entries[i].name,"uTemplateSet"))
sscanf(entries[i].val,"%u",&uTemplateSet);
else if(!strcmp(entries[i].name,"cuTemplateSetPullDown"))
{
sprintf(cuTemplateSetPullDown,"%.255s",entries[i].val);
uTemplateSet=ReadPullDown("tTemplateSet","cLabel",cuTemplateSetPullDown);
}
else if(!strcmp(entries[i].name,"uTemplateType"))
sscanf(entries[i].val,"%u",&uTemplateType);
else if(!strcmp(entries[i].name,"cuTemplateTypePullDown"))
{
sprintf(cuTemplateTypePullDown,"%.255s",entries[i].val);
uTemplateType=ReadPullDown("tTemplateType","cLabel",cuTemplateTypePullDown);
}
else if(!strcmp(entries[i].name,"cComment"))
cComment=entries[i].val;
else if(!strcmp(entries[i].name,"cTemplate"))
cTemplate=entries[i].val;
else if(!strcmp(entries[i].name,"uOwner"))
sscanf(entries[i].val,"%u",&uOwner);
else if(!strcmp(entries[i].name,"uCreatedBy"))
sscanf(entries[i].val,"%u",&uCreatedBy);
else if(!strcmp(entries[i].name,"uCreatedDate"))
sscanf(entries[i].val,"%lu",&uCreatedDate);
else if(!strcmp(entries[i].name,"uModBy"))
sscanf(entries[i].val,"%u",&uModBy);
else if(!strcmp(entries[i].name,"uModDate"))
sscanf(entries[i].val,"%lu",&uModDate);
}
//After so we can overwrite form data if needed.
ExtProcesstTemplateVars(entries,x);
}//ProcesstTemplateVars()
void ProcesstTemplateListVars(pentry entries[], int x)
{
register int i;
for(i=0;i<x;i++)
{
if(!strncmp(entries[i].name,"ED",2))
{
sscanf(entries[i].name+2,"%u",&uTemplate);
guMode=2002;
tTemplate("");
}
}
}//void ProcesstTemplateListVars(pentry entries[], int x)
int tTemplateCommands(pentry entries[], int x)
{
ProcessControlVars(entries,x);
ExttTemplateCommands(entries,x);
if(!strcmp(gcFunction,"tTemplateTools"))
{
if(!strcmp(gcFind,LANG_NB_LIST))
{
tTemplateList();
}
//Default
ProcesstTemplateVars(entries,x);
tTemplate("");
}
else if(!strcmp(gcFunction,"tTemplateList"))
{
ProcessControlVars(entries,x);
ProcesstTemplateListVars(entries,x);
tTemplateList();
}
return(0);
}//tTemplateCommands()
void tTemplate(const char *cResult)
{
MYSQL_RES *res;
MYSQL_RES *res2;
MYSQL_ROW field;
//Internal skip reloading
if(!cResult[0])
{
if(guMode)
ExttTemplateSelectRow();
else
ExttTemplateSelect();
mysql_query(&gMysql,gcQuery);
if(mysql_errno(&gMysql))
{
if(strstr(mysql_error(&gMysql)," doesn't exist"))
{
CreatetTemplate();
unxsISP("New tTemplate table created");
}
else
{
htmlPlainTextError(mysql_error(&gMysql));
}
}
res=mysql_store_result(&gMysql);
if((guI=mysql_num_rows(res)))
{
if(guMode==6)
{
sprintf(gcQuery,"SELECT _rowid FROM tTemplate WHERE uTemplate=%u"
,uTemplate);
mysql_query(&gMysql,gcQuery);
res2=mysql_store_result(&gMysql);
field=mysql_fetch_row(res2);
sscanf(field[0],"%lu",&gluRowid);
gluRowid++;
}
PageMachine("",0,"");
if(!guMode) mysql_data_seek(res,gluRowid-1);
field=mysql_fetch_row(res);
sscanf(field[0],"%u",&uTemplate);
sprintf(cLabel,"%.32s",field[1]);
sscanf(field[2],"%u",&uTemplateSet);
sscanf(field[3],"%u",&uTemplateType);
cComment=field[4];
cTemplate=field[5];
sscanf(field[6],"%u",&uOwner);
sscanf(field[7],"%u",&uCreatedBy);
sscanf(field[8],"%lu",&uCreatedDate);
sscanf(field[9],"%u",&uModBy);
sscanf(field[10],"%lu",&uModDate);
}
}//Internal Skip
Header_ism3(":: tTemplate",1);
printf("<table width=100%% cellspacing=0 cellpadding=0>\n");
printf("<tr><td colspan=2 align=right valign=center>");
printf("<input type=hidden name=gcFunction value=tTemplateTools>");
printf("<input type=hidden name=gluRowid value=%lu>",gluRowid);
if(guI)
{
if(guMode==6)
//printf(" Found");
printf(LANG_NBR_FOUND);
else if(guMode==5)
//printf(" Modified");
printf(LANG_NBR_MODIFIED);
else if(guMode==4)
//printf(" New");
printf(LANG_NBR_NEW);
printf(LANG_NBRF_SHOWING,gluRowid,guI);
}
else
{
if(!cResult[0])
//printf(" No records found");
printf(LANG_NBR_NORECS);
}
if(cResult[0]) printf("%s",cResult);
printf("</td></tr>");
printf("<tr><td valign=top width=25%%>");
ExttTemplateButtons();
printf("</td><td valign=top>");
//
OpenFieldSet("tTemplate Record Data",100);
if(guMode==2000 || guMode==2002)
tTemplateInput(1);
else
tTemplateInput(0);
//
CloseFieldSet();
//Bottom table
printf("<tr><td colspan=2>");
ExttTemplateAuxTable();
Footer_ism3();
}//end of tTemplate();
void tTemplateInput(unsigned uMode)
{
//uTemplate
OpenRow(LANG_FL_tTemplate_uTemplate,"black");
printf("<input title='%s' type=text name=uTemplate value=%u size=16 maxlength=10 "
,LANG_FT_tTemplate_uTemplate,uTemplate);
if(guPermLevel>=20 && uMode)
{
printf("></td></tr>\n");
}
else
{
printf("disabled></td></tr>\n");
printf("<input type=hidden name=uTemplate value=%u >\n",uTemplate);
}
//cLabel
OpenRow(LANG_FL_tTemplate_cLabel,"black");
printf("<input title='%s' type=text name=cLabel value=\"%s\" size=40 maxlength=32 "
,LANG_FT_tTemplate_cLabel,EncodeDoubleQuotes(cLabel));
if(guPermLevel>=7 && uMode)
{
printf("></td></tr>\n");
}
else
{
printf("disabled></td></tr>\n");
printf("<input type=hidden name=cLabel value=\"%s\">\n",EncodeDoubleQuotes(cLabel));
}
//uTemplateSet
OpenRow(LANG_FL_tTemplate_uTemplateSet,"black");
if(guPermLevel>=7 && uMode)
tTablePullDown("tTemplateSet;cuTemplateSetPullDown","cLabel","cLabel",uTemplateSet,1);
else
tTablePullDown("tTemplateSet;cuTemplateSetPullDown","cLabel","cLabel",uTemplateSet,0);
//uTemplateType
OpenRow(LANG_FL_tTemplate_uTemplateType,"black");
if(guPermLevel>=7 && uMode)
tTablePullDown("tTemplateType;cuTemplateTypePullDown","cLabel","cLabel",uTemplateType,1);
else
tTablePullDown("tTemplateType;cuTemplateTypePullDown","cLabel","cLabel",uTemplateType,0);
//cComment
OpenRow(LANG_FL_tTemplate_cComment,"black");
printf("<textarea title='%s' cols=80 wrap=hard rows=16 name=cComment "
,LANG_FT_tTemplate_cComment);
if(guPermLevel>=7 && uMode)
{
printf(">%s</textarea></td></tr>\n",cComment);
}
else
{
printf("disabled>%s</textarea></td></tr>\n",cComment);
printf("<input type=hidden name=cComment value=\"%s\" >\n",EncodeDoubleQuotes(cComment));
}
//cTemplate
OpenRow(LANG_FL_tTemplate_cTemplate,"black");
printf("<textarea title='%s' cols=80 wrap=off rows=16 name=cTemplate "
,LANG_FT_tTemplate_cTemplate);
if(guPermLevel>=7 && uMode)
{
printf(">%s</textarea></td></tr>\n",cTemplate);
}
else
{
printf("disabled>%s</textarea></td></tr>\n",cTemplate);
printf("<input type=hidden name=cTemplate value=\"%s\" >\n",EncodeDoubleQuotes(cTemplate));
}
//uOwner
OpenRow(LANG_FL_tTemplate_uOwner,"black");
if(guPermLevel>=20 && uMode)
{
printf("%s<input type=hidden name=uOwner value=%u >\n",ForeignKey(TCLIENT,"cLabel",uOwner),uOwner);
}
else
{
printf("%s<input type=hidden name=uOwner value=%u >\n",ForeignKey(TCLIENT,"cLabel",uOwner),uOwner);
}
//uCreatedBy
OpenRow(LANG_FL_tTemplate_uCreatedBy,"black");
if(guPermLevel>=20 && uMode)
{
printf("%s<input type=hidden name=uCreatedBy value=%u >\n",ForeignKey(TCLIENT,"cLabel",uCreatedBy),uCreatedBy);
}
else
{
printf("%s<input type=hidden name=uCreatedBy value=%u >\n",ForeignKey(TCLIENT,"cLabel",uCreatedBy),uCreatedBy);
}
//uCreatedDate
OpenRow(LANG_FL_tTemplate_uCreatedDate,"black");
if(uCreatedDate)
printf("%s\n\n",ctime(&uCreatedDate));
else
printf("---\n\n");
printf("<input type=hidden name=uCreatedDate value=%lu >\n",uCreatedDate);
//uModBy
OpenRow(LANG_FL_tTemplate_uModBy,"black");
if(guPermLevel>=20 && uMode)
{
printf("%s<input type=hidden name=uModBy value=%u >\n",ForeignKey(TCLIENT,"cLabel",uModBy),uModBy);
}
else
{
printf("%s<input type=hidden name=uModBy value=%u >\n",ForeignKey(TCLIENT,"cLabel",uModBy),uModBy);
}
//uModDate
OpenRow(LANG_FL_tTemplate_uModDate,"black");
if(uModDate)
printf("%s\n\n",ctime(&uModDate));
else
printf("---\n\n");
printf("<input type=hidden name=uModDate value=%lu >\n",uModDate);
printf("</tr>\n");
}//void tTemplateInput(unsigned uMode)
void NewtTemplate(unsigned uMode)
{
register int i=0;
MYSQL_RES *res;
sprintf(gcQuery,"SELECT uTemplate FROM tTemplate\
WHERE uTemplate=%u"
,uTemplate);
mysql_query(&gMysql,gcQuery);
if(mysql_errno(&gMysql)) htmlPlainTextError(mysql_error(&gMysql));
res=mysql_store_result(&gMysql);
i=mysql_num_rows(res);
if(i)
//tTemplate("<blink>Record already exists");
tTemplate(LANG_NBR_RECEXISTS);
//insert query
Insert_tTemplate();
if(mysql_errno(&gMysql)) htmlPlainTextError(mysql_error(&gMysql));
//sprintf(gcQuery,"New record %u added");
uTemplate=mysql_insert_id(&gMysql);
#ifdef ISM3FIELDS
uCreatedDate=luGetCreatedDate("tTemplate",uTemplate);
unxsISPLog(uTemplate,"tTemplate","New");
#endif
if(!uMode)
{
sprintf(gcQuery,LANG_NBR_NEWRECADDED,uTemplate);
tTemplate(gcQuery);
}
}//NewtTemplate(unsigned uMode)
void DeletetTemplate(void)
{
#ifdef ISM3FIELDS
sprintf(gcQuery,"DELETE FROM tTemplate WHERE uTemplate=%u AND ( uOwner=%u OR %u>9 )"
,uTemplate,guLoginClient,guPermLevel);
#else
sprintf(gcQuery,"DELETE FROM tTemplate WHERE uTemplate=%u"
,uTemplate);
#endif
mysql_query(&gMysql,gcQuery);
if(mysql_errno(&gMysql)) htmlPlainTextError(mysql_error(&gMysql));
//tTemplate("Record Deleted");
if(mysql_affected_rows(&gMysql)>0)
{
#ifdef ISM3FIELDS
unxsISPLog(uTemplate,"tTemplate","Del");
#endif
tTemplate(LANG_NBR_RECDELETED);
}
else
{
#ifdef ISM3FIELDS
unxsISPLog(uTemplate,"tTemplate","DelError");
#endif
tTemplate(LANG_NBR_RECNOTDELETED);
}
}//void DeletetTemplate(void)
void Insert_tTemplate(void)
{
//insert query
sprintf(gcQuery,"INSERT INTO tTemplate SET uTemplate=%u,cLabel='%s',uTemplateSet=%u,uTemplateType=%u,cComment='%s',cTemplate='%s',uOwner=%u,uCreatedBy=%u,uCreatedDate=UNIX_TIMESTAMP(NOW())",
uTemplate
,TextAreaSave(cLabel)
,uTemplateSet
,uTemplateType
,TextAreaSave(cComment)
,TextAreaSave(cTemplate)
,uOwner
,uCreatedBy
);
mysql_query(&gMysql,gcQuery);
}//void Insert_tTemplate(void)
void Update_tTemplate(char *cRowid)
{
//update query
sprintf(gcQuery,"UPDATE tTemplate SET uTemplate=%u,cLabel='%s',uTemplateSet=%u,uTemplateType=%u,cComment='%s',cTemplate='%s',uModBy=%u,uModDate=UNIX_TIMESTAMP(NOW()) WHERE _rowid=%s",
uTemplate
,TextAreaSave(cLabel)
,uTemplateSet
,uTemplateType
,TextAreaSave(cComment)
,TextAreaSave(cTemplate)
,uModBy
,cRowid);
mysql_query(&gMysql,gcQuery);
}//void Update_tTemplate(void)
void ModtTemplate(void)
{
register int i=0;
MYSQL_RES *res;
MYSQL_ROW field;
#ifdef ISM3FIELDS
unsigned uPreModDate=0;
sprintf(gcQuery,"SELECT uTemplate,uModDate FROM tTemplate WHERE uTemplate=%u"
,uTemplate);
#else
sprintf(gcQuery,"SELECT uTemplate FROM tTemplate\
WHERE uTemplate=%u"
,uTemplate);
#endif
mysql_query(&gMysql,gcQuery);
if(mysql_errno(&gMysql)) htmlPlainTextError(mysql_error(&gMysql));
res=mysql_store_result(&gMysql);
i=mysql_num_rows(res);
//if(i<1) tTemplate("<blink>Record does not exist");
if(i<1) tTemplate(LANG_NBR_RECNOTEXIST);
//if(i>1) tTemplate("<blink>Multiple rows!");
if(i>1) tTemplate(LANG_NBR_MULTRECS);
field=mysql_fetch_row(res);
#ifdef ISM3FIELDS
sscanf(field[1],"%u",&uPreModDate);
if(uPreModDate!=uModDate) tTemplate(LANG_NBR_EXTMOD);
#endif
Update_tTemplate(field[0]);
if(mysql_errno(&gMysql)) htmlPlainTextError(mysql_error(&gMysql));
//sprintf(query,"record %s modified",field[0]);
sprintf(gcQuery,LANG_NBRF_REC_MODIFIED,field[0]);
#ifdef ISM3FIELDS
uModDate=luGetModDate("tTemplate",uTemplate);
unxsISPLog(uTemplate,"tTemplate","Mod");
#endif
tTemplate(gcQuery);
}//ModtTemplate(void)
void tTemplateList(void)
{
MYSQL_RES *res;
MYSQL_ROW field;
ExttTemplateListSelect();
mysql_query(&gMysql,gcQuery);
if(mysql_error(&gMysql)[0]) htmlPlainTextError(mysql_error(&gMysql));
res=mysql_store_result(&gMysql);
guI=mysql_num_rows(res);
PageMachine("tTemplateList",1,"");//1 is auto header list guMode. Opens table!
//Filter select drop down
ExttTemplateListFilter();
printf("<input type=text size=16 name=gcCommand maxlength=98 value=\"%s\" >",gcCommand);
printf("</table>\n");
printf("<table bgcolor=#9BC1B3 border=0 width=100%%>\n");
printf("<tr bgcolor=black><td><font face=arial,helvetica color=white>uTemplate<td><font face=arial,helvetica color=white>cLabel<td><font face=arial,helvetica color=white>uTemplateSet<td><font face=arial,helvetica color=white>uTemplateType<td><font face=arial,helvetica color=white>cComment<td><font face=arial,helvetica color=white>cTemplate<td><font face=arial,helvetica color=white>uOwner<td><font face=arial,helvetica color=white>uCreatedBy<td><font face=arial,helvetica color=white>uCreatedDate<td><font face=arial,helvetica color=white>uModBy<td><font face=arial,helvetica color=white>uModDate</tr>");
mysql_data_seek(res,guStart-1);
for(guN=0;guN<(guEnd-guStart+1);guN++)
{
field=mysql_fetch_row(res);
if(!field)
{
printf("<tr><td><font face=arial,helvetica>End of data</table>");
Footer_ism3();
}
if(guN % 2)
printf("<tr bgcolor=#BBE1D3>");
else
printf("<tr>");
time_t luTime8=strtoul(field[8],NULL,10);
char cBuf8[32];
if(luTime8)
ctime_r(&luTime8,cBuf8);
else
sprintf(cBuf8,"---");
time_t luTime10=strtoul(field[10],NULL,10);
char cBuf10[32];
if(luTime10)
ctime_r(&luTime10,cBuf10);
else
sprintf(cBuf10,"---");
printf("<td><input type=submit name=ED%s value=Edit> %s<td>%s<td>%s<td>%s<td><textarea disabled>%s</textarea><td><textarea disabled>%s</textarea><td>%s<td>%s<td>%s<td>%s<td>%s</tr>"
,field[0]
,field[0]
,field[1]
,ForeignKey("tTemplateSet","cLabel",strtoul(field[2],NULL,10))
,ForeignKey("tTemplateType","cLabel",strtoul(field[3],NULL,10))
,field[4]
,field[5]
,ForeignKey(TCLIENT,"cLabel",strtoul(field[6],NULL,10))
,ForeignKey(TCLIENT,"cLabel",strtoul(field[7],NULL,10))
,cBuf8
,ForeignKey(TCLIENT,"cLabel",strtoul(field[9],NULL,10))
,cBuf10
);
}
printf("</table></form>\n");
Footer_ism3();
}//tTemplateList()
void CreatetTemplate(void)
{
sprintf(gcQuery,"CREATE TABLE IF NOT EXISTS tTemplate ( uTemplate INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, cLabel VARCHAR(32) NOT NULL DEFAULT '', uOwner INT UNSIGNED NOT NULL DEFAULT 0,index (uOwner), uCreatedBy INT UNSIGNED NOT NULL DEFAULT 0, uCreatedDate INT UNSIGNED NOT NULL DEFAULT 0, uModBy INT UNSIGNED NOT NULL DEFAULT 0, uModDate INT UNSIGNED NOT NULL DEFAULT 0, cComment TEXT NOT NULL DEFAULT '', cTemplate TEXT NOT NULL DEFAULT '', uTemplateSet INT UNSIGNED NOT NULL DEFAULT 0, uTemplateType INT UNSIGNED NOT NULL DEFAULT 0 )");
mysql_query(&gMysql,gcQuery);
if(mysql_errno(&gMysql))
htmlPlainTextError(mysql_error(&gMysql));
}//CreatetTemplate()
| unxs0/unxsVZ | unxsISP/ttemplate.c | C | gpl-2.0 | 17,292 |
<?php
/**
* also_purchased_products.php
*
* @package modules
* @copyright Copyright 2003-2006 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: also_purchased_products.php 5369 2006-12-23 10:55:52Z drbyte $
* Modified by Anne (Picaflor-Azul.com) Dover Fine v1.0
*/
if (!defined('IS_ADMIN_FLAG')) {
die('Illegal Access');
}
if (isset($_GET['products_id']) && SHOW_PRODUCT_INFO_COLUMNS_ALSO_PURCHASED_PRODUCTS > 0 && MIN_DISPLAY_ALSO_PURCHASED > 0) {
$also_purchased_products = $db->Execute(sprintf(SQL_ALSO_PURCHASED, (int)$_GET['products_id'], (int)$_GET['products_id']));
$num_products_ordered = $also_purchased_products->RecordCount();
$row = 0;
$col = 0;
$list_box_contents = array();
$title = '';
// show only when 1 or more and equal to or greater than minimum set in admin
if ($num_products_ordered >= MIN_DISPLAY_ALSO_PURCHASED && $num_products_ordered > 0) {
if ($num_products_ordered < SHOW_PRODUCT_INFO_COLUMNS_ALSO_PURCHASED_PRODUCTS) {
$col_width = floor(100/$num_products_ordered);
} else {
$col_width = floor(100/SHOW_PRODUCT_INFO_COLUMNS_ALSO_PURCHASED_PRODUCTS);
}
while (!$also_purchased_products->EOF) {
$also_purchased_products->fields['products_name'] = zen_get_products_name($also_purchased_products->fields['products_id']);
$list_box_contents[$row][$col] = array('params' => 'class="centerBoxContentsAlsoPurch"' . ' ' . 'style="width:' . $col_width . '%;"',
'text' => (($also_purchased_products->fields['products_image'] == '' and PRODUCTS_IMAGE_NO_IMAGE_STATUS == 0) ? '' : '<a href="' . zen_href_link(zen_get_info_page($also_purchased_products->fields['products_id']), 'products_id=' . $also_purchased_products->fields['products_id']) . '">' . zen_image(DIR_WS_IMAGES . $also_purchased_products->fields['products_image'], $also_purchased_products->fields['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><h3 class="itemTitle">') . '<a href="' . zen_href_link(zen_get_info_page($also_purchased_products->fields['products_id']), 'products_id=' . $also_purchased_products->fields['products_id']) . '">' . $also_purchased_products->fields['products_name'] . '</a></h3>');
$col ++;
if ($col > (SHOW_PRODUCT_INFO_COLUMNS_ALSO_PURCHASED_PRODUCTS - 1)) {
$col = 0;
$row ++;
}
$also_purchased_products->MoveNext();
}
}
if ($also_purchased_products->RecordCount() > 0 && $also_purchased_products->RecordCount() >= MIN_DISPLAY_ALSO_PURCHASED) {
$title = '<h2 class="centerBoxHeading">' . TEXT_ALSO_PURCHASED_PRODUCTS . '</h2>';
$zc_show_also_purchased = true;
}
}
?> | picaflor-azul/dover_fine | dover_fine/files/includes/modules/dover_fine/also_purchased_products.php | PHP | gpl-2.0 | 2,803 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Css\PreProcessor\File\FileList;
use Magento\Framework\View\File\FileList\CollateInterface;
/**
* File list collator
*/
class Collator implements CollateInterface
{
/**
* Collate source files
*
* @param \Magento\Framework\View\File[] $files
* @param \Magento\Framework\View\File[] $filesOrigin
* @return \Magento\Framework\View\File[]
*/
public function collate($files, $filesOrigin)
{
foreach ($files as $file) {
$fileId = substr($file->getFileIdentifier(), strpos($file->getFileIdentifier(), '|'));
foreach (array_keys($filesOrigin) as $identifier) {
if (false !== strpos($identifier, $fileId)) {
unset($filesOrigin[$identifier]);
}
}
$filesOrigin[$file->getFileIdentifier()] = $file;
}
return $filesOrigin;
}
}
| kunj1988/Magento2 | lib/internal/Magento/Framework/Css/PreProcessor/File/FileList/Collator.php | PHP | gpl-2.0 | 1,020 |
package org.lastbamboo.common.util.mina.decode.binary;
import org.littleshoot.mina.common.ByteBuffer;
import org.littleshoot.mina.filter.codec.ProtocolDecoderOutput;
import org.littleshoot.util.mina.DecodingState;
/**
* Decoding state for reading a single unsigned int.
*/
public abstract class UnsignedIntDecodingState implements DecodingState
{
public DecodingState decode(final ByteBuffer in,
final ProtocolDecoderOutput out) throws Exception
{
if (in.remaining() > 3)
{
final long decoded = in.getUnsignedInt();
return finishDecode(decoded, out);
}
else
{
return this;
}
}
/**
* Called on the subclass when the unsigned int has been successfully
* decoded.
*
* @param decodedShort The decoded unsigned int.
* @param out The decoder output.
* @return The next state.
* @throws Exception If any unexpected error occurs.
*/
protected abstract DecodingState finishDecode(final long decodedShort,
final ProtocolDecoderOutput out) throws Exception;
}
| adamfisk/littleshoot-client | common/util/mina/src/main/java/org/lastbamboo/common/util/mina/decode/binary/UnsignedIntDecodingState.java | Java | gpl-2.0 | 1,151 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.config.datacollection;
import java.io.Reader;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.Validator;
import org.opennms.core.xml.ValidateUsing;
/**
* a MIB object
*
* @version $Revision$ $Date$
*/
@XmlRootElement(name="mibObj", namespace="http://xmlns.opennms.org/xsd/config/datacollection")
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(propOrder={"oid", "instance", "alias", "type", "maxval", "minval"})
@ValidateUsing("datacollection-config.xsd")
public class MibObj implements java.io.Serializable {
private static final long serialVersionUID = -7831201614734695268L;
/**
* object identifier
*/
private String m_oid;
/**
* instance identifier. Only valid instance identifier
* values are a positive integer value or the keyword
* "ifIndex" which
* indicates that the ifIndex of the interface is to be
* substituted for
* the instance value for each interface the oid is retrieved
* for.
*/
private String m_instance;
/**
* a human readable name for the object (such as
* "ifOctetsIn"). NOTE: This value is used as the RRD file
* name and
* data source name. RRD only supports data source names up to
* 19 chars
* in length. If the SNMP data collector encounters an alias
* which
* exceeds 19 characters it will be truncated.
*/
private String m_alias;
/**
* SNMP data type SNMP supported types: counter, gauge,
* timeticks, integer, octetstring, string. The SNMP type is
* mapped to
* one of two RRD supported data types COUNTER or GAUGE, or
* the
* string.properties file. The mapping is as follows: SNMP
* counter
* -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring
* ->
* RRD GAUGE; SNMP string -> String properties file
*/
private String m_type;
/**
* Maximum Value. In order to correctly manage counter
* wraps, it is possible to add a maximum value for a
* collection. For
* example, a 32-bit counter would have a max value of
* 4294967295.
*/
private String m_maxval;
/**
* Minimum Value. For completeness, adding the ability
* to use a minimum value.
*/
private String m_minval;
public MibObj() {
super();
}
public MibObj(final String oid, final String instance, final String alias, final String type) {
super();
m_oid = oid;
m_instance = instance;
m_alias = alias;
m_type = type;
}
/**
* Overrides the java.lang.Object.equals method.
*
* @param obj
* @return true if the objects are equal.
*/
@Override()
public boolean equals(final java.lang.Object obj) {
if ( this == obj )
return true;
if (obj instanceof MibObj) {
final MibObj temp = (MibObj)obj;
if (m_oid != null) {
if (temp.m_oid == null) return false;
else if (!(m_oid.equals(temp.m_oid)))
return false;
}
else if (temp.m_oid != null)
return false;
if (m_instance != null) {
if (temp.m_instance == null) return false;
else if (!(m_instance.equals(temp.m_instance)))
return false;
}
else if (temp.m_instance != null)
return false;
if (m_alias != null) {
if (temp.m_alias == null) return false;
else if (!(m_alias.equals(temp.m_alias)))
return false;
}
else if (temp.m_alias != null)
return false;
if (m_type != null) {
if (temp.m_type == null) return false;
else if (!(m_type.equals(temp.m_type)))
return false;
}
else if (temp.m_type != null)
return false;
if (m_maxval != null) {
if (temp.m_maxval == null) return false;
else if (!(m_maxval.equals(temp.m_maxval)))
return false;
}
else if (temp.m_maxval != null)
return false;
if (m_minval != null) {
if (temp.m_minval == null) return false;
else if (!(m_minval.equals(temp.m_minval)))
return false;
}
else if (temp.m_minval != null)
return false;
return true;
}
return false;
}
/**
* Returns the value of field 'alias'. The field 'alias' has
* the following description: a human readable name for the
* object (such as
* "ifOctetsIn"). NOTE: This value is used as the RRD file
* name and
* data source name. RRD only supports data source names up to
* 19 chars
* in length. If the SNMP data collector encounters an alias
* which
* exceeds 19 characters it will be truncated.
*
* @return the value of field 'Alias'.
*/
@XmlAttribute(name="alias", required=true)
public String getAlias() {
return m_alias;
}
/**
* Returns the value of field 'instance'. The field 'instance'
* has the following description: instance identifier. Only
* valid instance identifier
* values are a positive integer value or the keyword
* "ifIndex" which
* indicates that the ifIndex of the interface is to be
* substituted for
* the instance value for each interface the oid is retrieved
* for.
*
* @return the value of field 'Instance'.
*/
@XmlAttribute(name="instance", required=true)
public String getInstance() {
return m_instance;
}
/**
* Returns the value of field 'maxval'. The field 'maxval' has
* the following description: Maximum Value. In order to
* correctly manage counter
* wraps, it is possible to add a maximum value for a
* collection. For
* example, a 32-bit counter would have a max value of
* 4294967295.
*
* @return the value of field 'Maxval'.
*/
@XmlAttribute(name="maxval", required=false)
public String getMaxval() {
return m_maxval;
}
/**
* Returns the value of field 'minval'. The field 'minval' has
* the following description: Minimum Value. For completeness,
* adding the ability
* to use a minimum value.
*
* @return the value of field 'Minval'.
*/
@XmlAttribute(name="minval", required=false)
public String getMinval() {
return m_minval;
}
/**
* Returns the value of field 'oid'. The field 'oid' has the
* following description: object identifier
*
* @return the value of field 'Oid'.
*/
@XmlAttribute(name="oid", required=true)
public String getOid() {
return m_oid;
}
/**
* Returns the value of field 'type'. The field 'type' has the
* following description: SNMP data type SNMP supported types:
* counter, gauge,
* timeticks, integer, octetstring, string. The SNMP type is
* mapped to
* one of two RRD supported data types COUNTER or GAUGE, or
* the
* string.properties file. The mapping is as follows: SNMP
* counter
* -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring
* ->
* RRD GAUGE; SNMP string -> String properties file
*
* @return the value of field 'Type'.
*/
@XmlAttribute(name="type", required=true)
public String getType() {
return m_type;
}
/**
* Overrides the java.lang.Object.hashCode method.
* <p>
* The following steps came from <b>Effective Java Programming
* Language Guide</b> by Joshua Bloch, Chapter 3
*
* @return a hash code value for the object.
*/
public int hashCode() {
int result = 17;
if (m_oid != null) {
result = 37 * result + m_oid.hashCode();
}
if (m_instance != null) {
result = 37 * result + m_instance.hashCode();
}
if (m_alias != null) {
result = 37 * result + m_alias.hashCode();
}
if (m_type != null) {
result = 37 * result + m_type.hashCode();
}
if (m_maxval != null) {
result = 37 * result + m_maxval.hashCode();
}
if (m_minval != null) {
result = 37 * result + m_minval.hashCode();
}
return result;
}
/**
* Method isValid.
*
* @return true if this object is valid according to the schema
*/
@Deprecated
public boolean isValid() {
try {
validate();
} catch (ValidationException vex) {
return false;
}
return true;
}
/**
*
*
* @param out
* @throws MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws ValidationException if this
* object is an invalid instance according to the schema
*/
@Deprecated
public void marshal(final java.io.Writer out)
throws MarshalException, ValidationException {
Marshaller.marshal(this, out);
}
/**
*
*
* @param handler
* @throws java.io.IOException if an IOException occurs during
* marshaling
* @throws ValidationException if this
* object is an invalid instance according to the schema
* @throws MarshalException if object is
* null or if any SAXException is thrown during marshaling
*/
@Deprecated
public void marshal(final org.xml.sax.ContentHandler handler)
throws java.io.IOException, MarshalException, ValidationException {
Marshaller.marshal(this, handler);
}
/**
* Sets the value of field 'alias'. The field 'alias' has the
* following description: a human readable name for the object
* (such as
* "ifOctetsIn"). NOTE: This value is used as the RRD file
* name and
* data source name. RRD only supports data source names up to
* 19 chars
* in length. If the SNMP data collector encounters an alias
* which
* exceeds 19 characters it will be truncated.
*
* @param alias the value of field 'alias'.
*/
public void setAlias(final String alias) {
m_alias = alias.intern();
}
/**
* Sets the value of field 'instance'. The field 'instance' has
* the following description: instance identifier. Only valid
* instance identifier
* values are a positive integer value or the keyword
* "ifIndex" which
* indicates that the ifIndex of the interface is to be
* substituted for
* the instance value for each interface the oid is retrieved
* for.
*
* @param instance the value of field 'instance'.
*/
public void setInstance(final String instance) {
m_instance = instance.intern();
}
/**
* Sets the value of field 'maxval'. The field 'maxval' has the
* following description: Maximum Value. In order to correctly
* manage counter
* wraps, it is possible to add a maximum value for a
* collection. For
* example, a 32-bit counter would have a max value of
* 4294967295.
*
* @param maxval the value of field 'maxval'.
*/
public void setMaxval(final String maxval) {
m_maxval = maxval.intern();
}
/**
* Sets the value of field 'minval'. The field 'minval' has the
* following description: Minimum Value. For completeness,
* adding the ability
* to use a minimum value.
*
* @param minval the value of field 'minval'.
*/
public void setMinval(final String minval) {
m_minval = minval.intern();
}
/**
* Sets the value of field 'oid'. The field 'oid' has the
* following description: object identifier
*
* @param oid the value of field 'oid'.
*/
public void setOid(final String oid) {
m_oid = oid.intern();
}
/**
* Sets the value of field 'type'. The field 'type' has the
* following description: SNMP data type SNMP supported types:
* counter, gauge,
* timeticks, integer, octetstring, string. The SNMP type is
* mapped to
* one of two RRD supported data types COUNTER or GAUGE, or
* the
* string.properties file. The mapping is as follows: SNMP
* counter
* -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring
* ->
* RRD GAUGE; SNMP string -> String properties file
*
* @param type the value of field 'type'.
*/
public void setType(final String type) {
m_type = type.intern();
}
/**
* Method unmarshal.
*
* @param reader
* @throws MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws ValidationException if this
* object is an invalid instance according to the schema
* @return the unmarshaled
* MibObj
*/
@Deprecated
public static MibObj unmarshal(final Reader reader) throws MarshalException, ValidationException {
return (MibObj)Unmarshaller.unmarshal(MibObj.class, reader);
}
/**
*
*
* @throws ValidationException if this
* object is an invalid instance according to the schema
*/
public void validate() throws ValidationException {
Validator validator = new Validator();
validator.validate(this);
}
}
| vishwaAbhinav/OpenNMS | opennms-config/src/main/java/org/opennms/netmgt/config/datacollection/MibObj.java | Java | gpl-2.0 | 15,302 |
<?php
/**
* @author Antonio Durán Terrés
* @package Joomdle
* @license GNU/GPL
*
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
// Import Joomla! libraries
jimport( 'joomla.application.component.view');
require_once( JPATH_COMPONENT.'/helpers/content.php' );
require_once( JPATH_COMPONENT.'/helpers/profiletypes.php' );
class JoomdleViewCustomprofiletypes extends JViewLegacy {
protected $items;
protected $pagination;
protected $state;
function display($tpl = null) {
$mainframe = JFactory::getApplication();
$params = JComponentHelper::getParams( 'com_joomdle' );
$this->sidebar = JHtmlSidebar::render();
if (!$params->get( 'use_profiletypes' ))
{
JToolbarHelper::title(JText::_('COM_JOOMDLE_VIEW_PROFILETYPES_TITLE'), 'customprofiletypes');
$this->message = JText::_('COM_JOOMDLE_PROFILE_TYPES_INTEGRATION_NOT_ENABLED');
$tpl = "disabled";
parent::display($tpl);
return;
}
/* List of profiletypes */
$this->profiletypes = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
$this->addToolbar();
parent::display($tpl);
}
protected function addToolbar()
{
JToolbarHelper::title(JText::_('COM_JOOMDLE_VIEW_PROFILETYPES_TITLE'), 'customprofiletypes');
JToolBarHelper::custom( 'create_profiletype_on_moodle', 'publish', 'publish', 'COM_JOOMDLE_CREATE_ON_MOODLE', true, false );
JToolBarHelper::custom( 'dont_create_profiletype_on_moodle', 'unpublish', 'unpublish', 'COM_JOOMDLE_NOT_CREATE_ON_MOODLE', true, false );
JHtmlSidebar::setAction('index.php?option=com_joomdle&view=customprofiletypes');
JHtmlSidebar::addFilter(
JText::_('COM_JOOMDLE_SELECT_STATE'),
'filter_state',
JHtml::_('select.options', JoomdleHelperProfiletypes::getStateOptions(), 'value', 'text', $this->state->get('filter.state'))
);
}
}
?>
| LauraRey/oacfdc | administrator/components/com_joomdle/views/customprofiletypes/view.html.php | PHP | gpl-2.0 | 2,060 |
/*
* CUnit - A Unit testing framework library for C.
* Copyright (C) 2004-2006 Jerry St.Clair
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Support for unit tests of CUnit framework
*
* 12-Aug-2004 Initial implementation. (JDS)
*
* 02-May-2006 Added internationalization hooks. (JDS)
*/
/** @file
* CUnit internal testingfunctions (implementation).
*/
/** @addtogroup Internal
@{
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../../Headers/CUnit.h"
#include "../../Headers/MyMem.h"
#include "../../Headers/Util.h"
#include "../../Headers/CUnit_intl.h"
#include "test_cunit.h"
static unsigned int f_nTests = 0;
static unsigned int f_nFailures = 0;
static unsigned int f_nTests_stored = 0;
static unsigned int f_nFails_stored = 0;
static clock_t f_start_time;
static void test_cunit_initialize(void);
static void test_cunit_report_results(void);
int main()
{
/* No line buffering. */
setbuf(stdout, NULL);
test_cunit_initialize();
fprintf(stdout, "\n%s", _("Testing CUnit internals..."));
/* individual module test functions go here */
test_cunit_CUError();
test_cunit_MyMem();
test_cunit_TestDB();
test_cunit_TestRun();
test_cunit_Util();
test_cunit_report_results();
CU_cleanup_registry();
return 0;
}
void test_cunit_start_tests(const char* strName)
{
fprintf(stdout, _("\n testing %s ... "), strName);
f_nTests_stored = f_nTests;
f_nFails_stored = f_nFailures;
}
void test_cunit_end_tests(void)
{
fprintf(stdout, _("%d assertions, %d failures"),
f_nTests - f_nTests_stored,
f_nFailures - f_nFails_stored);
}
void test_cunit_add_test(void)
{
++f_nTests;
}
void test_cunit_add_failure(void)
{
++f_nFailures;
}
unsigned int test_cunit_test_count(void)
{
return f_nTests;
}
unsigned int test_cunit_failure_count(void)
{
return f_nFailures;
}
void test_cunit_initialize(void)
{
f_nTests = 0;
f_nFailures = 0;
f_start_time = clock();
}
void test_cunit_report_results(void)
{
fprintf(stdout,
"\n\n---------------------------"
"\n%s"
"\n---------------------------"
"\n %s%d"
"\n %s%d"
"\n %s%d"
"\n\n%s%8.3f%s\n",
_("CUnit Internal Test Results"),
_("Total Number of Assertions: "),
f_nTests,
_("Successes: "),
f_nTests-f_nFailures,
_("Failures: "),
f_nFailures,
_("Total test time = "),
((double)clock() - (double)f_start_time)/(double)CLOCKS_PER_SEC,
_(" seconds."));
}
CU_BOOL test_cunit_assert_impl(CU_BOOL value,
const char* condition,
const char* file,
unsigned int line)
{
test_cunit_add_test();
if (CU_FALSE == value) {
test_cunit_add_failure();
printf(_("\nTEST FAILED: File '%s', Line %d, Condition '%s.'\n"),
file, line, condition);
}
return value;
}
| zxgyy/QiNiuBatchUpload | BatchupLoad/qiniu/CUnit/CUnit/Sources/Test/test_cunit.c | C | gpl-2.0 | 3,772 |
/*
File: pdisksel.h
Copyright (C) 2014 Christophe GRENIER <[email protected]>
This software 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 the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _PDISKSEL_H
#define _PDISKSEL_H
#ifdef __cplusplus
extern "C" {
#endif
/*@
@ requires valid_read_string(cmd_device);
@ requires \valid_read(list_disk);
@ requires valid_disk(list_disk->disk);
@ requires \valid(list_search_space);
@ requires \separated(cmd_device, list_disk, list_search_space);
@ ensures valid_disk(\result);
@*/
disk_t *photorec_disk_selection_cli(const char *cmd_device, const list_disk_t *list_disk, alloc_data_t *list_search_space);
#ifdef __cplusplus
} /* closing brace for extern "C" */
#endif
#endif
| cgsecurity/testdisk | src/pdisksel.h | C | gpl-2.0 | 1,370 |
/***************************************************************************
* Copyright 2007 Robert Gruber <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "test_cvs.h"
#include <QtTest/QtTest>
#include <QUrl>
#include <KIO/DeleteJob>
#include <cvsjob.h>
#include <cvsproxy.h>
#include <tests/autotestshell.h>
#include <tests/testcore.h>
#define CVSTEST_BASEDIR "/tmp/kdevcvs_testdir/"
#define CVS_REPO CVSTEST_BASEDIR "repo/"
#define CVS_IMPORT CVSTEST_BASEDIR "import/"
#define CVS_TESTFILE_NAME "testfile"
#define CVS_CHECKOUT CVSTEST_BASEDIR "working/"
// we need to add this since it is declared in cvsplugin.cpp which we don't compile here
Q_LOGGING_CATEGORY(PLUGIN_CVS, "kdevplatform.plugins.cvs")
void TestCvs::initTestCase()
{
KDevelop::AutoTestShell::init();
KDevelop::TestCore::initialize(KDevelop::Core::NoUi);
m_proxy = new CvsProxy;
// If the basedir for this cvs test exists from a
// previous run; remove it...
cleanup();
}
void TestCvs::cleanupTestCase()
{
KDevelop::TestCore::shutdown();
delete m_proxy;
}
void TestCvs::init()
{
// Now create the basic directory structure
QDir tmpdir("/tmp");
tmpdir.mkdir(CVSTEST_BASEDIR);
tmpdir.mkdir(CVS_REPO);
tmpdir.mkdir(CVS_IMPORT);
}
void TestCvs::cleanup()
{
if ( QFileInfo::exists(CVSTEST_BASEDIR) )
KIO::del(QUrl::fromLocalFile(QString(CVSTEST_BASEDIR)))->exec();
}
void TestCvs::repoInit()
{
// make job that creates the local repository
CvsJob* j = new CvsJob(0);
QVERIFY( j );
j->setDirectory(CVSTEST_BASEDIR);
*j << "cvs" << "-d" << CVS_REPO << "init";
// try to start the job
QVERIFY( j->exec() );
//check if the CVSROOT directory in the new local repository exists now
QVERIFY( QFileInfo::exists(QString(CVS_REPO "/CVSROOT")) );
}
void TestCvs::importTestData()
{
// create a file so we don't import an empty dir
QFile f(CVS_IMPORT "" CVS_TESTFILE_NAME);
if(f.open(QIODevice::WriteOnly)) {
QTextStream input( &f );
input << "HELLO WORLD";
}
f.flush();
CvsJob* j = m_proxy->import(QUrl::fromLocalFile(CVS_IMPORT), CVS_REPO,
"test", "vendor", "release",
"test import message");
QVERIFY( j );
// try to start the job
QVERIFY( j->exec() );
//check if the directory has been added to the repository
QString testdir(CVS_REPO "/test");
QVERIFY( QFileInfo::exists(testdir) );
//check if the file has been added to the repository
QString testfile(CVS_REPO "/test/" CVS_TESTFILE_NAME ",v");
QVERIFY( QFileInfo::exists(testfile) );
}
void TestCvs::checkoutTestData()
{
CvsJob* j = m_proxy->checkout(QUrl::fromLocalFile(CVS_CHECKOUT), CVS_REPO, "test");
QVERIFY( j );
// try to start the job
QVERIFY( j->exec() );
//check if the directory is there
QString testdir(CVS_CHECKOUT);
QVERIFY( QFileInfo::exists(testdir) );
//check if the file is there
QString testfile(CVS_CHECKOUT "" CVS_TESTFILE_NAME);
QVERIFY( QFileInfo::exists(testfile) );
}
void TestCvs::testInitAndImport()
{
repoInit();
importTestData();
checkoutTestData();
}
void TestCvs::testLogFolder()
{
repoInit();
importTestData();
checkoutTestData();
QString testdir(CVS_CHECKOUT);
KDevelop::VcsRevision rev = KDevelop::VcsRevision::createSpecialRevision(KDevelop::VcsRevision::Head);
CvsJob* job = m_proxy->log(QUrl::fromLocalFile(testdir), rev);
QVERIFY(job);
}
QTEST_MAIN(TestCvs)
| mali/kdevplatform | plugins/cvs/tests/test_cvs.cpp | C++ | gpl-2.0 | 4,139 |
/*
Copyright (c) 2004 The Regents of the University of Michigan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <dirent.h>
#include "gssd.h"
#include "err_util.h"
#include "nfslib.h"
extern struct pollfd *pollarray;
extern unsigned long pollsize;
#define POLL_MILLISECS 500
static volatile int dir_changed = 1;
static void dir_notify_handler(__attribute__((unused))int sig)
{
dir_changed = 1;
}
static void
scan_poll_results(int ret)
{
int i;
struct clnt_info *clp;
for (clp = clnt_list.tqh_first; clp != NULL; clp = clp->list.tqe_next)
{
i = clp->gssd_poll_index;
if (i >= 0 && pollarray[i].revents) {
if (pollarray[i].revents & POLLHUP) {
clp->gssd_close_me = 1;
dir_changed = 1;
}
if (pollarray[i].revents & POLLIN)
handle_gssd_upcall(clp);
pollarray[clp->gssd_poll_index].revents = 0;
ret--;
if (!ret)
break;
}
i = clp->krb5_poll_index;
if (i >= 0 && pollarray[i].revents) {
if (pollarray[i].revents & POLLHUP) {
clp->krb5_close_me = 1;
dir_changed = 1;
}
if (pollarray[i].revents & POLLIN)
handle_krb5_upcall(clp);
pollarray[clp->krb5_poll_index].revents = 0;
ret--;
if (!ret)
break;
}
}
}
static int
topdirs_add_entry(struct dirent *dent)
{
struct topdirs_info *tdi;
tdi = calloc(sizeof(struct topdirs_info), 1);
if (tdi == NULL) {
printerr(0, "ERROR: Couldn't allocate struct topdirs_info\n");
return -1;
}
tdi->dirname = malloc(PATH_MAX);
if (tdi->dirname == NULL) {
printerr(0, "ERROR: Couldn't allocate directory name\n");
free(tdi);
return -1;
}
snprintf(tdi->dirname, PATH_MAX, "%s/%s", pipefs_dir, dent->d_name);
tdi->fd = open(tdi->dirname, O_RDONLY);
if (tdi->fd == -1) {
printerr(0, "ERROR: failed to open %s\n", tdi->dirname);
free(tdi);
return -1;
}
fcntl(tdi->fd, F_SETSIG, DNOTIFY_SIGNAL);
fcntl(tdi->fd, F_NOTIFY, DN_CREATE|DN_DELETE|DN_MODIFY|DN_MULTISHOT);
TAILQ_INSERT_HEAD(&topdirs_list, tdi, list);
return 0;
}
static void
topdirs_free_list(void)
{
struct topdirs_info *tdi;
TAILQ_FOREACH(tdi, &topdirs_list, list) {
free(tdi->dirname);
if (tdi->fd != -1)
close(tdi->fd);
TAILQ_REMOVE(&topdirs_list, tdi, list);
free(tdi);
}
}
static int
topdirs_init_list(void)
{
DIR *pipedir;
struct dirent *dent;
int ret;
TAILQ_INIT(&topdirs_list);
pipedir = opendir(pipefs_dir);
if (pipedir == NULL) {
printerr(0, "ERROR: could not open rpc_pipefs directory '%s': "
"%s\n", pipefs_dir, strerror(errno));
return -1;
}
for (dent = readdir(pipedir); dent != NULL; dent = readdir(pipedir)) {
if (dent->d_type != DT_DIR ||
strcmp(dent->d_name, ".") == 0 ||
strcmp(dent->d_name, "..") == 0) {
continue;
}
ret = topdirs_add_entry(dent);
if (ret)
goto out_err;
}
closedir(pipedir);
return 0;
out_err:
topdirs_free_list();
return -1;
}
#ifdef HAVE_PPOLL
static void gssd_poll(struct pollfd *fds, unsigned long nfds)
{
sigset_t emptyset;
int ret;
sigemptyset(&emptyset);
ret = ppoll(fds, nfds, NULL, &emptyset);
if (ret < 0) {
if (errno != EINTR)
printerr(0, "WARNING: error return from poll\n");
} else if (ret == 0) {
printerr(0, "WARNING: unexpected timeout\n");
} else {
scan_poll_results(ret);
}
}
#else /* !HAVE_PPOLL */
static void gssd_poll(struct pollfd *fds, unsigned long nfds)
{
int ret;
/* race condition here: dir_changed could be set before we
* enter the poll, and we'd never notice if it weren't for the
* timeout. */
ret = poll(fds, nfds, POLL_MILLISECS);
if (ret < 0) {
if (errno != EINTR)
printerr(0, "WARNING: error return from poll\n");
} else if (ret == 0) {
/* timeout */
} else { /* ret > 0 */
scan_poll_results(ret);
}
}
#endif /* !HAVE_PPOLL */
void
gssd_run()
{
struct sigaction dn_act = {
.sa_handler = dir_notify_handler
};
sigset_t set;
sigemptyset(&dn_act.sa_mask);
sigaction(DNOTIFY_SIGNAL, &dn_act, NULL);
/* just in case the signal is blocked... */
sigemptyset(&set);
sigaddset(&set, DNOTIFY_SIGNAL);
sigprocmask(SIG_UNBLOCK, &set, NULL);
if (topdirs_init_list() != 0)
return;
init_client_list();
printerr(1, "beginning poll\n");
while (1) {
while (dir_changed) {
dir_changed = 0;
if (update_client_list()) {
/* Error msg is already printed */
exit(1);
}
/* release the parent after the initial dir scan */
release_parent(pipefds);
}
gssd_poll(pollarray, pollsize);
}
topdirs_free_list();
return;
}
| greearb/nfs-utils-ct | utils/gssd/gssd_main_loop.c | C | gpl-2.0 | 6,223 |
#!/usr/bin/env python
import unittest
from werkzeug.exceptions import NotFound, Forbidden
from tests.logic_t.layer.LogicLayer.util import generate_ll
class TaskPrioritizeBeforeLogicLayerTest(unittest.TestCase):
def setUp(self):
self.ll = generate_ll()
self.pl = self.ll.pl
def test_add_prioritize_before_adds_prioritize_before(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# when
results = self.ll.do_add_prioritize_before_to_task(t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_if_already_added_still_succeeds(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
t1.prioritize_before.append(t2)
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# when
results = self.ll.do_add_prioritize_before_to_task(t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_null_ids_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_before_to_task,
None, t2.id, user)
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_before_to_task,
t1.id, None, user)
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_before_to_task,
None, None, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
def test_null_user_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_before_to_task,
t1.id, t2.id, None)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
def test_user_not_authorized_for_task_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# expect
self.assertRaises(Forbidden, self.ll.do_add_prioritize_before_to_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
def test_user_not_authorized_for_prioritize_before_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# expect
self.assertRaises(Forbidden, self.ll.do_add_prioritize_before_to_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
def test_task_not_found_raises_exception(self):
# given
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNone(self.pl.get_task(t2.id + 1))
# expect
self.assertRaises(NotFound, self.ll.do_add_prioritize_before_to_task,
t2.id + 1, t2.id, user)
# then
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNone(self.pl.get_task(t2.id+1))
def test_prioritize_before_not_found_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertIsNone(self.pl.get_task(t1.id + 1))
# expect
self.assertRaises(NotFound, self.ll.do_add_prioritize_before_to_task,
t1.id, t1.id + 1, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertIsNone(self.pl.get_task(t1.id + 1))
def test_remove_prioritize_before_removes_prioritize_before(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_before.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# when
results = self.ll.do_remove_prioritize_before_from_task(t1.id, t2.id,
user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_if_prioritize_before_already_removed_still_succeeds(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
# when
results = self.ll.do_remove_prioritize_before_from_task(t1.id, t2.id,
user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_remove_prioritize_before_with_null_ids_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_before.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_before_from_task,
None, t2.id, user)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_before_from_task,
t1.id, None, user)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_before_from_task,
None, None, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
def test_remove_prioritize_before_with_null_user_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_before.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_before_from_task,
t1.id, t2.id, None)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
def test_remove_prioritize_before_user_unauthd_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
t1.prioritize_before.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# note that this situation shouldn't happen anyways. a task shouldn't
# be prioritized before another task unless both share a common set of
# one or more authorized users
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# expect
self.assertRaises(Forbidden,
self.ll.do_remove_prioritize_before_from_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
def test_remove_user_not_authd_for_prioritizebefore_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t1.prioritize_before.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# note that this situation shouldn't happen anyways. a task shouldn't
# be prioritized before another task unless both share a common set of
# one or more authorized users
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
# expect
self.assertRaises(Forbidden,
self.ll.do_remove_prioritize_before_from_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(1, len(t1.prioritize_before))
self.assertEqual(1, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertTrue(t2 in t1.prioritize_before)
self.assertTrue(t1 in t2.prioritize_after)
def test_remove_prioritize_before_task_not_found_raises_exception(self):
# given
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNone(self.pl.get_task(t2.id + 1))
# expect
self.assertRaises(NotFound,
self.ll.do_remove_prioritize_before_from_task,
t2.id + 1, t2.id, user)
# then
self.assertEqual(0, len(t2.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertIsNone(self.pl.get_task(t2.id+1))
def test_remove_prioritize_before_when_not_found_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertIsNone(self.pl.get_task(t1.id + 1))
# expect
self.assertRaises(NotFound,
self.ll.do_remove_prioritize_before_from_task,
t1.id, t1.id + 1, user)
# then
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t1.prioritize_before))
self.assertIsNone(self.pl.get_task(t1.id + 1))
class TaskPrioritizeAfterLogicLayerTest(unittest.TestCase):
def setUp(self):
self.ll = generate_ll()
self.pl = self.ll.pl
def test_add_prioritize_after_adds_prioritize_after(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# when
results = self.ll.do_add_prioritize_after_to_task(t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_if_already_added_still_succeeds(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
t1.prioritize_after.append(t2)
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# when
results = self.ll.do_add_prioritize_after_to_task(t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_null_ids_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_after_to_task,
None, t2.id, user)
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_after_to_task,
t1.id, None, user)
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_after_to_task,
None, None, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
def test_null_user_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# expect
self.assertRaises(ValueError, self.ll.do_add_prioritize_after_to_task,
t1.id, t2.id, None)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
def test_user_not_authorized_for_task_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# expect
self.assertRaises(Forbidden, self.ll.do_add_prioritize_after_to_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
def test_user_not_authorized_for_prioritize_after_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# expect
self.assertRaises(Forbidden, self.ll.do_add_prioritize_after_to_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
def test_task_not_found_raises_exception(self):
# given
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNone(self.pl.get_task(t2.id + 1))
# expect
self.assertRaises(NotFound, self.ll.do_add_prioritize_after_to_task,
t2.id + 1, t2.id, user)
# then
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNone(self.pl.get_task(t2.id+1))
def test_prioritize_after_not_found_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertIsNone(self.pl.get_task(t1.id + 1))
# expect
self.assertRaises(NotFound, self.ll.do_add_prioritize_after_to_task,
t1.id, t1.id + 1, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertIsNone(self.pl.get_task(t1.id + 1))
def test_remove_prioritize_after_removes_prioritize_after(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_after.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# when
results = self.ll.do_remove_prioritize_after_from_task(t1.id, t2.id,
user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_if_prioritize_after_already_removed_still_succeeds(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
# when
results = self.ll.do_remove_prioritize_after_from_task(t1.id, t2.id,
user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNotNone(results)
self.assertEqual([t1, t2], list(results))
def test_remove_prioritize_after_with_null_ids_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_after.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_after_from_task,
None, t2.id, user)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_after_from_task,
t1.id, None, user)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_after_from_task,
None, None, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
def test_remove_prioritize_after_with_null_user_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t2.users.append(user)
t1.prioritize_after.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# expect
self.assertRaises(ValueError,
self.ll.do_remove_prioritize_after_from_task,
t1.id, t2.id, None)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
def test_rem_prioritize_after_user_unauthd_for_task_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
t1.prioritize_after.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# note that this situation shouldn't happen anyways. a task shouldn't
# be prioritized before another task unless both share a common set of
# one or more authorized users
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# expect
self.assertRaises(Forbidden,
self.ll.do_remove_prioritize_after_from_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
def test_remove_user_not_authd_for_prioritize_after_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
t1.prioritize_after.append(t2)
self.pl.add(t1)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# note that this situation shouldn't happen anyways. a task shouldn't
# be prioritized before another task unless both share a common set of
# one or more authorized users
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
# expect
self.assertRaises(Forbidden,
self.ll.do_remove_prioritize_after_from_task,
t1.id, t2.id, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(1, len(t1.prioritize_after))
self.assertEqual(1, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertTrue(t2 in t1.prioritize_after)
self.assertTrue(t1 in t2.prioritize_before)
def test_remove_prioritize_after_task_not_found_raises_exception(self):
# given
t2 = self.pl.create_task('t2')
user = self.pl.create_user('[email protected]')
t2.users.append(user)
self.pl.add(t2)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNone(self.pl.get_task(t2.id + 1))
# expect
self.assertRaises(NotFound,
self.ll.do_remove_prioritize_after_from_task,
t2.id + 1, t2.id, user)
# then
self.assertEqual(0, len(t2.prioritize_before))
self.assertEqual(0, len(t2.prioritize_after))
self.assertIsNone(self.pl.get_task(t2.id+1))
def test_remove_prioritize_after_when_not_found_raises_exception(self):
# given
t1 = self.pl.create_task('t1')
user = self.pl.create_user('[email protected]')
t1.users.append(user)
self.pl.add(t1)
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertIsNone(self.pl.get_task(t1.id + 1))
# expect
self.assertRaises(NotFound,
self.ll.do_remove_prioritize_after_from_task,
t1.id, t1.id + 1, user)
# then
self.assertEqual(0, len(t1.prioritize_before))
self.assertEqual(0, len(t1.prioritize_after))
self.assertIsNone(self.pl.get_task(t1.id + 1))
| izrik/tudor | tests/logic_t/layer/LogicLayer/test_task_prioritize.py | Python | gpl-2.0 | 36,403 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Bundle\EzPublishLegacyBundle\Controller;
use eZ\Bundle\EzPublishLegacyBundle\LegacyResponse\LegacyResponseManager;
use eZ\Publish\Core\MVC\Legacy\Kernel\URIHelper;
use eZ\Publish\Core\MVC\Legacy\Templating\LegacyHelper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use eZ\Publish\Core\MVC\ConfigResolverInterface;
use ezpKernelRedirect;
use Symfony\Component\Routing\RouterInterface;
/**
* Controller embedding legacy kernel.
*/
class LegacyKernelController
{
/**
* @var \Closure
*/
private $kernelClosure;
/**
* @var \eZ\Publish\Core\MVC\ConfigResolverInterface
*/
private $configResolver;
/**
* Template declaration to wrap legacy responses in a Twig pagelayout (optional)
* Either a template declaration string or null/false to use legacy pagelayout
* Default is null.
*
* @var mixed
*/
private $legacyLayout;
/**
* @var \eZ\Publish\Core\MVC\Legacy\Kernel\URIHelper
*/
private $uriHelper;
/**
* @var \eZ\Bundle\EzPublishLegacyBundle\LegacyResponse\LegacyResponseManager
*/
private $legacyResponseManager;
/**
* @var \eZ\Publish\Core\MVC\Legacy\Templating\LegacyHelper
*/
private $legacyHelper;
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
private $router;
public function __construct(
\Closure $kernelClosure,
ConfigResolverInterface $configResolver,
URIHelper $uriHelper,
LegacyResponseManager $legacyResponseManager,
LegacyHelper $legacyHelper,
RouterInterface $router
) {
$this->kernelClosure = $kernelClosure;
$this->legacyLayout = $configResolver->getParameter('module_default_layout', 'ezpublish_legacy');
$this->configResolver = $configResolver;
$this->uriHelper = $uriHelper;
$this->legacyResponseManager = $legacyResponseManager;
$this->legacyHelper = $legacyHelper;
$this->router = $router;
}
/**
* Base fallback action.
* Will be basically used for every legacy module.
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \eZ\Bundle\EzPublishLegacyBundle\LegacyResponse
*/
public function indexAction(Request $request)
{
$kernelClosure = $this->kernelClosure;
/** @var \eZ\Publish\Core\MVC\Legacy\Kernel $kernel */
$kernel = $kernelClosure();
$legacyMode = $this->configResolver->getParameter('legacy_mode');
$kernel->setUseExceptions(false);
// Fix up legacy URI with current request since we can be in a sub-request here.
$this->uriHelper->updateLegacyURI($request);
// If we have a layout for legacy AND we're not in legacy mode, we ask the legacy kernel not to generate layout.
if (isset($this->legacyLayout) && !$legacyMode) {
$kernel->setUsePagelayout(false);
}
$result = $kernel->run();
$kernel->setUseExceptions(true);
if ($result instanceof ezpKernelRedirect) {
return $this->legacyResponseManager->generateRedirectResponse($result);
}
$this->legacyHelper->loadDataFromModuleResult($result->getAttribute('module_result'));
$response = $this->legacyResponseManager->generateResponseFromModuleResult($result);
$this->legacyResponseManager->mapHeaders(headers_list(), $response);
return $response;
}
/**
* Generates a RedirectResponse to the appropriate login route.
*
* @return RedirectResponse
*/
public function loginAction()
{
return new RedirectResponse($this->router->generate('login'));
}
/**
* Generates a RedirectResponse to the appropriate logout route.
*
* @return RedirectResponse
*/
public function logoutAction()
{
return new RedirectResponse($this->router->generate('logout'));
}
}
| ezsystems/LegacyBridge | bundle/Controller/LegacyKernelController.php | PHP | gpl-2.0 | 4,198 |
/*
* Universal power supply monitor class
*
* Copyright © 2007 Anton Vorontsov <[email protected]>
* Copyright © 2004 Szabolcs Gyurko
* Copyright © 2003 Ian Molton <[email protected]>
*
* Modified: 2004, Oct Szabolcs Gyurko
*
* You may use this code as per GPL version 2
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/notifier.h>
#include <linux/err.h>
#include <linux/power_supply.h>
#include <linux/thermal.h>
#include "power_supply.h"
/* exported for the APM Power driver, APM emulation */
struct class *power_supply_class;
EXPORT_SYMBOL_GPL(power_supply_class);
ATOMIC_NOTIFIER_HEAD(power_supply_notifier);
EXPORT_SYMBOL_GPL(power_supply_notifier);
static struct device_type power_supply_dev_type;
static bool __power_supply_is_supplied_by(struct power_supply *supplier,
struct power_supply *supply)
{
int i;
if (!supply->supplied_from && !supplier->supplied_to)
return false;
/* Support both supplied_to and supplied_from modes */
if (supply->supplied_from) {
if (!supplier->name)
return false;
for (i = 0; i < supply->num_supplies; i++)
if (!strcmp(supplier->name, supply->supplied_from[i]))
return true;
} else {
if (!supply->name)
return false;
for (i = 0; i < supplier->num_supplicants; i++)
if (!strcmp(supplier->supplied_to[i], supply->name))
return true;
}
return false;
}
/**
* power_supply_set_current_limit - set current limit
* @psy: the power supply to control
* @limit: current limit in uA from the power supply.
* 0 will disable the power supply.
*
* This function will set a maximum supply current from a source
* and it will disable the charger when limit is 0.
*/
int power_supply_set_current_limit(struct power_supply *psy, int limit)
{
const union power_supply_propval ret = {limit,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_CURRENT_MAX,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_current_limit);
/**
* power_supply_set_charging_enabled - enable or disable charging
* @psy: the power supply to control
* @enable: sets enable property of power supply
*/
int power_supply_set_charging_enabled(struct power_supply *psy, bool enable)
{
const union power_supply_propval ret = {enable,};
if (psy->set_property)
return psy->set_property(psy,
POWER_SUPPLY_PROP_CHARGING_ENABLED,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_charging_enabled);
/**
* power_supply_set_present - set present state of the power supply
* @psy: the power supply to control
* @enable: sets present property of power supply
*/
int power_supply_set_present(struct power_supply *psy, bool enable)
{
const union power_supply_propval ret = {enable,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_PRESENT,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_present);
/**
* power_supply_set_online - set online state of the power supply
* @psy: the power supply to control
* @enable: sets online property of power supply
*/
int power_supply_set_online(struct power_supply *psy, bool enable)
{
const union power_supply_propval ret = {enable,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_ONLINE,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_online);
/** power_supply_set_health_state - set health state of the power supply
* @psy: the power supply to control
* @health: sets health property of power supply
*/
int power_supply_set_health_state(struct power_supply *psy, int health)
{
const union power_supply_propval ret = {health,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_HEALTH,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL(power_supply_set_health_state);
/**
* power_supply_set_scope - set scope of the power supply
* @psy: the power supply to control
* @scope: value to set the scope property to, should be from
* the SCOPE enum in power_supply.h
*/
int power_supply_set_scope(struct power_supply *psy, int scope)
{
const union power_supply_propval ret = {scope, };
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_SCOPE,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_scope);
/**
* power_supply_set_supply_type - set type of the power supply
* @psy: the power supply to control
* @supply_type: sets type property of power supply
*/
int power_supply_set_supply_type(struct power_supply *psy,
enum power_supply_type supply_type)
{
const union power_supply_propval ret = {supply_type,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_TYPE,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_supply_type);
/**
* power_supply_set_charge_type - set charge type of the power supply
* @psy: the power supply to control
* @enable: sets charge type property of power supply
*/
int power_supply_set_charge_type(struct power_supply *psy, int charge_type)
{
const union power_supply_propval ret = {charge_type,};
if (psy->set_property)
return psy->set_property(psy, POWER_SUPPLY_PROP_CHARGE_TYPE,
&ret);
return -ENXIO;
}
EXPORT_SYMBOL_GPL(power_supply_set_charge_type);
static int __power_supply_changed_work(struct device *dev, void *data)
{
struct power_supply *psy = (struct power_supply *)data;
struct power_supply *pst = dev_get_drvdata(dev);
if (__power_supply_is_supplied_by(psy, pst)) {
if (pst->external_power_changed)
pst->external_power_changed(pst);
}
return 0;
}
static void power_supply_changed_work(struct work_struct *work)
{
unsigned long flags;
struct power_supply *psy = container_of(work, struct power_supply,
changed_work);
dev_dbg(psy->dev, "%s\n", __func__);
spin_lock_irqsave(&psy->changed_lock, flags);
if (psy->changed) {
psy->changed = false;
spin_unlock_irqrestore(&psy->changed_lock, flags);
class_for_each_device(power_supply_class, NULL, psy,
__power_supply_changed_work);
power_supply_update_leds(psy);
atomic_notifier_call_chain(&power_supply_notifier,
PSY_EVENT_PROP_CHANGED, psy);
kobject_uevent(&psy->dev->kobj, KOBJ_CHANGE);
spin_lock_irqsave(&psy->changed_lock, flags);
}
/*
* Dependent power supplies (e.g. battery) may have changed state
* as a result of this event, so poll again and hold the
* wakeup_source until all events are processed.
*/
if (!psy->changed)
pm_relax(psy->dev);
spin_unlock_irqrestore(&psy->changed_lock, flags);
}
void power_supply_changed(struct power_supply *psy)
{
unsigned long flags;
dev_dbg(psy->dev, "%s\n", __func__);
spin_lock_irqsave(&psy->changed_lock, flags);
psy->changed = true;
pm_stay_awake(psy->dev);
spin_unlock_irqrestore(&psy->changed_lock, flags);
schedule_work(&psy->changed_work);
}
EXPORT_SYMBOL_GPL(power_supply_changed);
#ifdef CONFIG_OF
#include <linux/of.h>
static int __power_supply_populate_supplied_from(struct device *dev,
void *data)
{
struct power_supply *psy = (struct power_supply *)data;
struct power_supply *epsy = dev_get_drvdata(dev);
struct device_node *np;
int i = 0;
do {
np = of_parse_phandle(psy->of_node, "power-supplies", i++);
if (!np)
continue;
if (np == epsy->of_node) {
dev_info(psy->dev, "%s: Found supply : %s\n",
psy->name, epsy->name);
psy->supplied_from[i-1] = (char *)epsy->name;
psy->num_supplies++;
of_node_put(np);
break;
}
of_node_put(np);
} while (np);
return 0;
}
static int power_supply_populate_supplied_from(struct power_supply *psy)
{
int error;
error = class_for_each_device(power_supply_class, NULL, psy,
__power_supply_populate_supplied_from);
dev_dbg(psy->dev, "%s %d\n", __func__, error);
return error;
}
static int __power_supply_find_supply_from_node(struct device *dev,
void *data)
{
struct device_node *np = (struct device_node *)data;
struct power_supply *epsy = dev_get_drvdata(dev);
/* return error breaks out of class_for_each_device loop */
if (epsy->of_node == np)
return -EINVAL;
return 0;
}
static int power_supply_find_supply_from_node(struct device_node *supply_node)
{
int error;
struct device *dev;
struct class_dev_iter iter;
/*
* Use iterator to see if any other device is registered.
* This is required since class_for_each_device returns 0
* if there are no devices registered.
*/
class_dev_iter_init(&iter, power_supply_class, NULL, NULL);
dev = class_dev_iter_next(&iter);
if (!dev)
return -EPROBE_DEFER;
/*
* We have to treat the return value as inverted, because if
* we return error on not found, then it won't continue looking.
* So we trick it by returning error on success to stop looking
* once the matching device is found.
*/
error = class_for_each_device(power_supply_class, NULL, supply_node,
__power_supply_find_supply_from_node);
return error ? 0 : -EPROBE_DEFER;
}
static int power_supply_check_supplies(struct power_supply *psy)
{
struct device_node *np;
int cnt = 0;
/* If there is already a list honor it */
if (psy->supplied_from && psy->num_supplies > 0)
return 0;
/* No device node found, nothing to do */
if (!psy->of_node)
return 0;
do {
int ret;
np = of_parse_phandle(psy->of_node, "power-supplies", cnt++);
if (!np)
continue;
ret = power_supply_find_supply_from_node(np);
if (ret) {
dev_dbg(psy->dev, "Failed to find supply, defer!\n");
of_node_put(np);
return -EPROBE_DEFER;
}
of_node_put(np);
} while (np);
/* All supplies found, allocate char ** array for filling */
psy->supplied_from = devm_kzalloc(psy->dev, sizeof(psy->supplied_from),
GFP_KERNEL);
if (!psy->supplied_from) {
dev_err(psy->dev, "Couldn't allocate memory for supply list\n");
return -ENOMEM;
}
*psy->supplied_from = devm_kzalloc(psy->dev, sizeof(char *) * cnt,
GFP_KERNEL);
if (!*psy->supplied_from) {
dev_err(psy->dev, "Couldn't allocate memory for supply list\n");
return -ENOMEM;
}
return power_supply_populate_supplied_from(psy);
}
#else
static inline int power_supply_check_supplies(struct power_supply *psy)
{
return 0;
}
#endif
static int __power_supply_am_i_supplied(struct device *dev, void *data)
{
union power_supply_propval ret = {0,};
struct power_supply *psy = (struct power_supply *)data;
struct power_supply *epsy = dev_get_drvdata(dev);
if (__power_supply_is_supplied_by(epsy, psy))
if (!epsy->get_property(epsy, POWER_SUPPLY_PROP_ONLINE, &ret)) {
if (ret.intval)
return ret.intval;
}
return 0;
}
int power_supply_am_i_supplied(struct power_supply *psy)
{
int error;
error = class_for_each_device(power_supply_class, NULL, psy,
__power_supply_am_i_supplied);
dev_dbg(psy->dev, "%s %d\n", __func__, error);
return error;
}
EXPORT_SYMBOL_GPL(power_supply_am_i_supplied);
static int __power_supply_is_system_supplied(struct device *dev, void *data)
{
union power_supply_propval ret = {0,};
struct power_supply *psy = dev_get_drvdata(dev);
unsigned int *count = data;
(*count)++;
if (psy->type != POWER_SUPPLY_TYPE_BATTERY) {
if (psy->get_property(psy, POWER_SUPPLY_PROP_ONLINE, &ret))
return 0;
if (ret.intval)
return ret.intval;
}
return 0;
}
int power_supply_is_system_supplied(void)
{
int error;
unsigned int count = 0;
error = class_for_each_device(power_supply_class, NULL, &count,
__power_supply_is_system_supplied);
/*
* If no power class device was found at all, most probably we are
* running on a desktop system, so assume we are on mains power.
*/
if (count == 0)
return 1;
return error;
}
EXPORT_SYMBOL_GPL(power_supply_is_system_supplied);
int power_supply_set_battery_charged(struct power_supply *psy)
{
if (psy->type == POWER_SUPPLY_TYPE_BATTERY && psy->set_charged) {
psy->set_charged(psy);
return 0;
}
return -EINVAL;
}
EXPORT_SYMBOL_GPL(power_supply_set_battery_charged);
static int power_supply_match_device_by_name(struct device *dev, const void *data)
{
const char *name = data;
struct power_supply *psy = dev_get_drvdata(dev);
return strcmp(psy->name, name) == 0;
}
struct power_supply *power_supply_get_by_name(const char *name)
{
struct device *dev = class_find_device(power_supply_class, NULL, name,
power_supply_match_device_by_name);
return dev ? dev_get_drvdata(dev) : NULL;
}
EXPORT_SYMBOL_GPL(power_supply_get_by_name);
#ifdef CONFIG_OF
static int power_supply_match_device_node(struct device *dev, const void *data)
{
return dev->parent && dev->parent->of_node == data;
}
struct power_supply *power_supply_get_by_phandle(struct device_node *np,
const char *property)
{
struct device_node *power_supply_np;
struct device *dev;
power_supply_np = of_parse_phandle(np, property, 0);
if (!power_supply_np)
return ERR_PTR(-ENODEV);
dev = class_find_device(power_supply_class, NULL, power_supply_np,
power_supply_match_device_node);
of_node_put(power_supply_np);
return dev ? dev_get_drvdata(dev) : NULL;
}
EXPORT_SYMBOL_GPL(power_supply_get_by_phandle);
#endif /* CONFIG_OF */
int power_supply_powers(struct power_supply *psy, struct device *dev)
{
return sysfs_create_link(&psy->dev->kobj, &dev->kobj, "powers");
}
EXPORT_SYMBOL_GPL(power_supply_powers);
static void power_supply_dev_release(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
kfree(dev);
}
int power_supply_reg_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&power_supply_notifier, nb);
}
EXPORT_SYMBOL_GPL(power_supply_reg_notifier);
void power_supply_unreg_notifier(struct notifier_block *nb)
{
atomic_notifier_chain_unregister(&power_supply_notifier, nb);
}
EXPORT_SYMBOL_GPL(power_supply_unreg_notifier);
#ifdef CONFIG_THERMAL
static int power_supply_read_temp(struct thermal_zone_device *tzd,
unsigned long *temp)
{
struct power_supply *psy;
union power_supply_propval val;
int ret;
WARN_ON(tzd == NULL);
psy = tzd->devdata;
ret = psy->get_property(psy, POWER_SUPPLY_PROP_TEMP, &val);
/* Convert tenths of degree Celsius to milli degree Celsius. */
if (!ret)
*temp = val.intval * 100;
return ret;
}
static struct thermal_zone_device_ops psy_tzd_ops = {
.get_temp = power_supply_read_temp,
};
static int psy_register_thermal(struct power_supply *psy)
{
int i;
/* Register battery zone device psy reports temperature */
for (i = 0; i < psy->num_properties; i++) {
if (psy->properties[i] == POWER_SUPPLY_PROP_TEMP) {
psy->tzd = thermal_zone_device_register(psy->name, 0, 0,
psy, &psy_tzd_ops, NULL, 0, 0);
if (IS_ERR(psy->tzd))
return PTR_ERR(psy->tzd);
break;
}
}
return 0;
}
static void psy_unregister_thermal(struct power_supply *psy)
{
if (IS_ERR_OR_NULL(psy->tzd))
return;
thermal_zone_device_unregister(psy->tzd);
}
/* thermal cooling device callbacks */
static int ps_get_max_charge_cntl_limit(struct thermal_cooling_device *tcd,
unsigned long *state)
{
struct power_supply *psy;
union power_supply_propval val;
int ret;
psy = tcd->devdata;
ret = psy->get_property(psy,
POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX, &val);
if (!ret)
*state = val.intval;
return ret;
}
static int ps_get_cur_chrage_cntl_limit(struct thermal_cooling_device *tcd,
unsigned long *state)
{
struct power_supply *psy;
union power_supply_propval val;
int ret;
psy = tcd->devdata;
ret = psy->get_property(psy,
POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);
if (!ret)
*state = val.intval;
return ret;
}
static int ps_set_cur_charge_cntl_limit(struct thermal_cooling_device *tcd,
unsigned long state)
{
struct power_supply *psy;
union power_supply_propval val;
int ret;
psy = tcd->devdata;
val.intval = state;
ret = psy->set_property(psy,
POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);
return ret;
}
static struct thermal_cooling_device_ops psy_tcd_ops = {
.get_max_state = ps_get_max_charge_cntl_limit,
.get_cur_state = ps_get_cur_chrage_cntl_limit,
.set_cur_state = ps_set_cur_charge_cntl_limit,
};
static int psy_register_cooler(struct power_supply *psy)
{
int i;
/* Register for cooling device if psy can control charging */
for (i = 0; i < psy->num_properties; i++) {
if (psy->properties[i] ==
POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT) {
psy->tcd = thermal_cooling_device_register(
(char *)psy->name,
psy, &psy_tcd_ops);
if (IS_ERR(psy->tcd))
return PTR_ERR(psy->tcd);
break;
}
}
return 0;
}
static void psy_unregister_cooler(struct power_supply *psy)
{
if (IS_ERR_OR_NULL(psy->tcd))
return;
thermal_cooling_device_unregister(psy->tcd);
}
#else
static int psy_register_thermal(struct power_supply *psy)
{
return 0;
}
static void psy_unregister_thermal(struct power_supply *psy)
{
}
static int psy_register_cooler(struct power_supply *psy)
{
return 0;
}
static void psy_unregister_cooler(struct power_supply *psy)
{
}
#endif
int power_supply_register(struct device *parent, struct power_supply *psy)
{
struct device *dev;
int rc;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
device_initialize(dev);
dev->class = power_supply_class;
dev->type = &power_supply_dev_type;
dev->parent = parent;
dev->release = power_supply_dev_release;
dev_set_drvdata(dev, psy);
psy->dev = dev;
rc = dev_set_name(dev, "%s", psy->name);
if (rc)
goto dev_set_name_failed;
INIT_WORK(&psy->changed_work, power_supply_changed_work);
rc = power_supply_check_supplies(psy);
if (rc) {
dev_info(dev, "Not all required supplies found, defer probe\n");
goto check_supplies_failed;
}
spin_lock_init(&psy->changed_lock);
rc = device_init_wakeup(dev, true);
if (rc)
goto wakeup_init_failed;
rc = device_add(dev);
if (rc)
goto device_add_failed;
rc = psy_register_thermal(psy);
if (rc)
goto register_thermal_failed;
rc = psy_register_cooler(psy);
if (rc)
goto register_cooler_failed;
rc = power_supply_create_triggers(psy);
if (rc)
goto create_triggers_failed;
power_supply_changed(psy);
goto success;
create_triggers_failed:
psy_unregister_cooler(psy);
register_cooler_failed:
psy_unregister_thermal(psy);
register_thermal_failed:
device_del(dev);
device_add_failed:
wakeup_init_failed:
check_supplies_failed:
dev_set_name_failed:
put_device(dev);
success:
return rc;
}
EXPORT_SYMBOL_GPL(power_supply_register);
void power_supply_unregister(struct power_supply *psy)
{
cancel_work_sync(&psy->changed_work);
sysfs_remove_link(&psy->dev->kobj, "powers");
power_supply_remove_triggers(psy);
psy_unregister_cooler(psy);
psy_unregister_thermal(psy);
device_init_wakeup(psy->dev, false);
device_unregister(psy->dev);
}
EXPORT_SYMBOL_GPL(power_supply_unregister);
static int __init power_supply_class_init(void)
{
power_supply_class = class_create(THIS_MODULE, "power_supply");
if (IS_ERR(power_supply_class))
return PTR_ERR(power_supply_class);
power_supply_class->dev_uevent = power_supply_uevent;
power_supply_init_attrs(&power_supply_dev_type);
return 0;
}
static void __exit power_supply_class_exit(void)
{
class_destroy(power_supply_class);
}
subsys_initcall(power_supply_class_init);
module_exit(power_supply_class_exit);
MODULE_DESCRIPTION("Universal power supply monitor class");
MODULE_AUTHOR("Ian Molton <[email protected]>, "
"Szabolcs Gyurko, "
"Anton Vorontsov <[email protected]>");
MODULE_LICENSE("GPL");
| titusece/linux_imx | drivers/power/power_supply_core.c | C | gpl-2.0 | 19,435 |
<?php
/**
* @file
* Default theme implementation to display a single Drupal page.
*
* The doctype, html, head and body tags are not in this template. Instead they
* can be found in the html.tpl.php template in this directory.
*
* Available variables:
*
* General utility variables:
* - $base_path: The base URL path of the Drupal installation. At the very
* least, this will always default to /.
* - $directory: The directory the template is located in, e.g. modules/system
* or themes/bartik.
* - $is_front: TRUE if the current page is the front page.
* - $logged_in: TRUE if the user is registered and signed in.
* - $is_admin: TRUE if the user has permission to access administration pages.
*
* Site identity:
* - $front_page: The URL of the front page. Use this instead of $base_path,
* when linking to the front page. This includes the language domain or
* prefix.
* - $logo: The path to the logo image, as defined in theme configuration.
* - $site_name: The name of the site, empty when display has been disabled
* in theme settings.
* - $site_slogan: The slogan of the site, empty when display has been disabled
* in theme settings.
*
* Navigation:
* - $main_menu (array): An array containing the Main menu links for the
* site, if they have been configured.
* - $secondary_menu (array): An array containing the Secondary menu links for
* the site, if they have been configured.
* - $breadcrumb: The breadcrumb trail for the current page.
*
* Page content (in order of occurrence in the default page.tpl.php):
* - $title_prefix (array): An array containing additional output populated by
* modules, intended to be displayed in front of the main title tag that
* appears in the template.
* - $title: The page title, for use in the actual HTML content.
* - $title_suffix (array): An array containing additional output populated by
* modules, intended to be displayed after the main title tag that appears in
* the template.
* - $messages: HTML for status and error messages. Should be displayed
* prominently.
* - $tabs (array): Tabs linking to any sub-pages beneath the current page
* (e.g., the view and edit tabs when displaying a node).
* - $action_links (array): Actions local to the page, such as 'Add menu' on the
* menu administration interface.
* - $feed_icons: A string of all feed icons for the current page.
* - $node: The node object, if there is an automatically-loaded node
* associated with the page, and the node ID is the second argument
* in the page's path (e.g. node/12345 and node/12345/revisions, but not
* comment/reply/12345).
*
* Regions:
* - $page['help']: Dynamic help text, mostly for admin pages.
* - $page['highlighted']: Items for the highlighted content region.
* - $page['content']: The main content of the current page.
* - $page['sidebar_first']: Items for the first sidebar.
* - $page['sidebar_second']: Items for the second sidebar.
* - $page['header']: Items for the header region.
* - $page['footer']: Items for the footer region.
*
* @see template_preprocess()
* @see template_preprocess_page()
* @see template_process()
* @see html.tpl.php
*
* @ingroup themeable
*/
?>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
<![endif]-->
<?php
$path = "";
if(theme_get_setting('default_logo', 'md_leaders')) {
$path = $logo;
}else{
if(theme_get_setting('logo_normal_upload','md_leaders')) {
$file_upload = theme_get_setting('logo_normal_upload','md_leaders');
if($file_upload['fid'] != 0) {
$file = file_load($file_upload['fid']);
if($file) {
$path = file_create_url($file->uri);
}
} else {
$path = '';
}
}
}
?>
<div id="header" class="color_section">
<div class="container"><div class="row">
<a class="navbar-brand" href="<?php print $front_page; ?>" title="<?php print $site_name; ?>">
<img src="<?php print $path; ?>" alt="<?php print $site_name; ?>" />
</a>
<?php if (theme_get_setting('toggle_name') || theme_get_setting('toggle_slogan')): ?>
<div id="name-and-slogan">
<?php if (theme_get_setting('toggle_name')): ?>
<?php if ($title): ?>
<div id="site-name"><strong>
<a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
</strong></div>
<?php else: /* Use h1 when the content title is empty */ ?>
<h1 id="site-name">
<a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
</h1>
<?php endif; ?>
<?php endif; ?>
<?php if (theme_get_setting('toggle_slogan')): ?>
<div id="site-slogan"><?php print $site_slogan; ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php print render($page['header']); ?>
<?php print render($page['menu']); ?>
</div></div>
</div>
<?php print render($page['mainslider']); ?>
<?php print $messages; ?>
<!--<section class="darkgrey_section" id="abovecontent">
<div class="container"><div class="row">
<div class="block col-sm-12">
print $breadcrumb;
</div>
</div></div>
</section>-->
<section class="grey_section" id="middle">
<div class="container">
<?php print render($page['content']); ?>
</div>
</section>
<section class="light_section" id="copyright">
<div class="container">
<div class="row to_animate_child_blocks">
<div class="col-sm-12 text-center"><a href="/terms-conditions">Terms & Conditions</a></div>
</div>
</div>
</section>
<?php if (isset($preload)): ?>
<div class="preloader">
<div class="preloaderimg"></div>
</div>
<?php endif; ?>
| toniabhi/hclcausefight | sites/all/themes/md_leaders/templates/page--comment--reply.tpl.php | PHP | gpl-2.0 | 6,117 |
# zabbix-slack
Zabbix alert script for sending notifications to a Slack webhook (python requests)
| mortn/zabbix-slack | README.md | Markdown | gpl-2.0 | 98 |
<?php
/**
* @package Surveyforce
* @version 1.1-modified
* @copyright JooPlce Team, 臺北市政府資訊局, Copyright (C) 2016. All rights reserved.
* @license GPL-2.0+
* @author JooPlace Team, 臺北市政府資訊局- http://doit.gov.taipei/
*/
defined('_JEXEC') or die('Restricted access');
/**
* Surveyforce Component Controller
*/
class SurveyforceController extends JControllerLegacy {
/**
* display task
*
* @return void
*/
public function __construct($config = array()){
parent::__construct($config);
}
public function display($cachable = false, $urlparams = array()){
$app = JFactory::getApplication();
$view = JFactory::getApplication()->input->getCmd('view', 'surveys');
switch($view){
case "surveys":
case "survey":
case "questions":
case "question":
case "review":
case "import":
case "result":
case "resultnote":
case "export":
case "getip":
case "autocheck":
case "print":
case "lottery":
case "addend":
case "analyzes":
case "analyze":
case "voted":
break;
default:
$app->redirect("index.php?option=com_surveyforce&view=surveys"); // 直接進入議題管理
}
JFactory::getApplication()->input->set('view', $view);
parent::display($cachable);
}
public function get_options(){
if(!class_exists('SfAppPlugins')){
include_once JPATH_COMPONENT_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'app_plugin.php';
$appsLib = SfAppPlugins::getInstance();
$appsLib->loadApplications();
}
$type = SurveyforceHelper::getQuestionType(JFactory::getApplication()->input->getCmd('sf_qtype'));
$data['quest_type'] = $type->sf_plg_name;
$data['quest_id'] = JFactory::getApplication()->input->get('quest_id');
$data['sf_qtype'] = JFactory::getApplication()->input->getCmd('sf_qtype');
$appsLib->triggerEvent('onGetAdminQuestionOptions', $data);
}
// 投票測試
public function testvote(){
$db = JFactory::getDBO();
$config = JFactory::getConfig();
$testsite_link = $config->get('testsite_link', false);
$app = JFactory::getApplication();
$survey_id = $app->input->getInt('test_survey_id', 0);
$api_request_url = $config->get('testsite_link', '') . "api/server_survey.php";
// 先刪除資料
$api_request_parameters = array('survey_id' => $survey_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$api_request_url .= '?' . http_build_query($api_request_parameters);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $api_request_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$api_response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$message = curl_error($ch);
curl_close($ch);
if($code == 200){
$result_data = json_decode($api_response);
if($result_data->status == 0){
echo "無法匯入資料,請聯絡系統管理員。";
JHtml::_('utility.recordLog', "api_log.php", "投票測試無法刪除資料", JLog::ERROR);
jexit();
}
}else{ // 無法連線API
echo "無法連線API,請聯絡系統管理員。";
JHtml::_('utility.recordLog', "api_log.php", sprintf("Url:%s, Code:%d, Msg:%s", $api_request_url, $code, $message), JLog::ERROR);
jexit();
}
// 再新增資料
// 依序取得議題、題目、選項的資料
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__survey_force_survs_release');
$query->where('id = ' . $db->quote($survey_id));
$db->setQuery($query);
$survey_row = $db->loadAssoc();
// 取得題目
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__survey_force_quests');
$query->where('sf_survey = ' . $db->quote($survey_id));
$db->setQuery($query);
$question_rows = $db->loadAssocList();
unset($options_rows);
$options_rows = array();
unset($sub_options_rows);
$sub_options_rows = array();
unset($cats_rows);
$cats_rows = array();
if($question_rows){
$question_ids = array();
foreach($question_rows as $question_row){
$question_ids[] = $question_row["id"];
}
// 取得選項
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__survey_force_fields');
$query->where('quest_id IN (' . implode(",", $question_ids) . ')');
$db->setQuery($query);
$options_rows = $db->loadAssocList();
// 取得子選項
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__survey_force_sub_fields');
$query->where('quest_id IN (' . implode(",", $question_ids) . ')');
$db->setQuery($query);
$sub_options_rows = $db->loadAssocList();
// 取得分類
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__survey_force_quests_cat');
$query->where('question_id IN (' . implode(",", $question_ids) . ')');
$db->setQuery($query);
$cats_rows = $db->loadAssocList();
}
// assign_summary
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__assign_summary');
$query->where('survey_id = ' . $db->quote($survey_id));
$db->setQuery($query);
$assign_summary_rows = $db->loadAssocList();
// 寫至測試站台中,再將網頁導向測試站台
$api_request_parameters = array('survey_id' => $survey_id, 'survey_row' => json_encode($survey_row), 'question_rows' => json_encode($question_rows), 'options_rows' => json_encode($options_rows), 'sub_options_rows' => json_encode($sub_options_rows), 'assign_summary_rows' => json_encode($assign_summary_rows), 'cats_rows' => json_encode($cats_rows));
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $api_request_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$api_response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$message = curl_error($ch);
curl_close($ch);
if($code == 200){
$result_data = json_decode($api_response);
if($result_data->status == 0){
echo "無法匯入議題資料,請聯絡系統管理員。";
JHtml::_('utility.recordLog', "api_log.php", "投票測試無法新增資料", JLog::ERROR);
jexit();
}else{
header("Location:" . $testsite_link . "index.php?option=com_surveyforce&view=intro&Itemid=120&sid=" . $survey_id);
jexit();
}
}else{ // 無法連線API
echo "無法連線API,請聯絡系統管理員。";
JHtml::_('utility.recordLog', "api_log.php", sprintf("Url:%s, Code:%d, Msg:%s", $api_request_url, $code, $message), JLog::ERROR);
jexit();
}
jexit();
}
}
| taipeicity/i-voting | administrator/components/com_surveyforce/controller.php | PHP | gpl-2.0 | 8,229 |
package org.mo.com.io;
public class FLinkInput
{
}
| favedit/MoPlatform | mo-1-common/src/lang-java/org/mo/com/io/FLinkInput.java | Java | gpl-2.0 | 52 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2013 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
require_once CLASS_EX_REALDIR . 'page_extends/frontparts/bloc/LC_Page_FrontParts_Bloc_Ex.php';
/**
* ランキング のページクラス.
*
* @package Page
* @author Designup.jp
* @version 1.1
*/
class LC_Page_FrontParts_Bloc_BcRanking extends LC_Page_FrontParts_Bloc_Ex
{
/**
* Page を初期化する.
*
* @return void
*/
public function init()
{
parent::init();
}
/**
* Page のプロセス.
*
* @return void
*/
public function process()
{
$this->action();
$this->sendResponse();
}
/**
* Page のアクション.
*
* @return void
*/
public function action()
{
// 基本情報を渡す
// $objSiteInfo = SC_Helper_DB_Ex::sfGetBasisData();
// $this->arrInfo = $objSiteInfo->data;
//売上ランキング取得
$this->arrBestProducts = $this->lfGetRanking();
//売上ランキング取得、8位まで
//$this->arrBestProducts8 = $this->lfGetRanking(8);
//商品レビュー情報を取得
//$this->arrReviewList = $this->getReviewList();
//メーカー情報を取得
//$this->arrMakerList = $this->getMakerList();
}
/**
* おすすめ商品検索.
*
* @return array $arrBestProducts 検索結果配列
*/
public function lfGetRanking($getNumber = 10)
{
// $objRecommend = new SC_Helper_BestProducts_Ex();
// 売上ランキング取得、デフォルトは5位まで取得
$arrRanking = $this->getList($getNumber);
$response = array();
if (count($arrRanking) > 0) {
// 商品一覧を取得
$objQuery =& SC_Query_Ex::getSingletonInstance();
$objProduct = new SC_Product_Ex();
// where条件生成&セット
$arrProductId = array();
foreach ($arrRanking as $key => $val) {
$arrProductId[] = $val['product_id'];
}
//$arrProducts = $objProduct->getListByProductIds($objQuery, $arrProductId);
$arrProducts = $objProduct->getListByProductIdsWithAgencyCode($objQuery, $arrProductId);
// 税込金額を設定する
SC_Product_Ex::setIncTaxToProducts($arrProducts);
// 売上ランキング情報にマージ
$i=0;
foreach ($arrRanking as $key => $value) {
if (isset($arrProducts[$value['product_id']])) {
$product = $arrProducts[$value['product_id']];
if ($product['status'] == 1 && (!NOSTOCK_HIDDEN || ($product['stock_max'] >= 1 || $product['stock_unlimited_max'] == 1))) {
if ($i == $getNumber ) {
break;
}
$response[] = array_merge($value, $arrProducts[$value['product_id']]);
$i++;
}
} else {
// 削除済み商品は除外
unset($arrRanking[$key]);
}
}
}
return $response;
}
/**
* 商品情報を取得
*
* @return array $arrNewProducts 検索結果配列
*/
public function getList($dispNumber = 0, $pageNumber = 0, $has_deleted = false)
{
$objQuery =& SC_Query_Ex::getSingletonInstance();
$col = 'OD.product_id,OD.price,SUM(OD.quantity),SUM(OD.quantity)*OD.price';
$table = 'dtb_order as O, dtb_order_detail as OD';
$where = 'O.order_id = OD.order_id AND O.del_flg = 0';
$objQuery->setGroupBy('OD.product_id');
$objQuery->setOrder('SUM(OD.quantity) DESC');
/*
if ($dispNumber > 0) {
if ($pageNumber > 0) {
$objQuery->setLimitOffset($dispNumber, (($pageNumber - 1) * $dispNumber));
} else {
$objQuery->setLimit($dispNumber);
}
}
*/
$arrRet = $objQuery->select($col, $table, $where);
// データの中身の表示テスト
// echo "<pre>";
// var_dump($arrRet);
// echo "</pre>";
return $arrRet;
}
/*
public function getList($dispNumber = 0, $pageNumber = 0, $has_deleted = false)
{
$objQuery =& SC_Query_Ex::getSingletonInstance();
$col = 'product_id,price,SUM(quantity),SUM(quantity)*price';
$table = 'dtb_order_detail';
$where = '';
$objQuery->setGroupBy('product_id,price');
$objQuery->setOrder('SUM(quantity)*price DESC');
if ($dispNumber > 0) {
if ($pageNumber > 0) {
$objQuery->setLimitOffset($dispNumber, (($pageNumber - 1) * $dispNumber));
} else {
$objQuery->setLimit($dispNumber);
}
}
$arrRet = $objQuery->select($col, $table, $where);
// データの中身の表示テスト
// echo "<pre>";
// var_dump($arrRet);
// echo "</pre>";
return $arrRet;
}
*/
/**
* 商品のレビューと商品情報を結合した情報を取得
* 商品ごとに集計、小数点以下切り捨て
*
* @return array $arrReviewList 検索結果配列
*/
public function getReviewList($dispNumber = 0, $pageNumber = 0, $has_deleted = false)
{
$objQuery =& SC_Query_Ex::getSingletonInstance();
$col = 'product_id,TRUNC(AVG(recommend_level),0) AS recommend_level,COUNT(*) AS recommend_count';
$table = 'dtb_review';
$where = '';
$objQuery->setGroupBy('product_id');
$objQuery->setOrder('product_id DESC');
if ($dispNumber > 0) {
if ($pageNumber > 0) {
$objQuery->setLimitOffset($dispNumber, (($pageNumber - 1) * $dispNumber));
} else {
$objQuery->setLimit($dispNumber);
}
}
$arrRet = $objQuery->select($col, $table, $where);
// データの中身の表示テスト
// echo "<pre>";
// var_dump($arrRet);
// echo "</pre>";
return $arrRet;
}
/**
* メーカー情報の取得
*
* @return array $arrMakerList 検索結果配列
*/
public function getMakerList($dispNumber = 0, $pageNumber = 0, $has_deleted = false)
{
$objQuery =& SC_Query_Ex::getSingletonInstance();
$col = '*';
$table = 'dtb_maker';
$where = '';
if ($dispNumber > 0) {
if ($pageNumber > 0) {
$objQuery->setLimitOffset($dispNumber, (($pageNumber - 1) * $dispNumber));
} else {
$objQuery->setLimit($dispNumber);
}
}
$arrRet = $objQuery->select($col, $table, $where);
// データの中身の表示テスト
// echo "<pre>";
// var_dump($arrRet);
// echo "</pre>";
return $arrRet;
}
}
| kazuma-fujita/taheebo-ec | data/class/pages/frontparts/bloc/LC_Page_FrontParts_Bloc_BcRanking.php | PHP | gpl-2.0 | 7,846 |
/*
Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 Mark Aylett <[email protected]>
This file is part of Aug written by Mark Aylett.
Aug is released under the GPL with the additional exemption that compiling,
linking, and/or using OpenSSL is allowed.
Aug 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.
Aug 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.
*/
#ifndef AUGUTILPP_LOG_HPP
#define AUGUTILPP_LOG_HPP
#include "augutilpp/config.hpp"
#include "augctxpp/exception.hpp"
#include "augutil/log.h"
#include "augctx/defs.h" // AUG_MAXLINE
#include <string>
namespace aug {
inline void
vformatlog(char* buf, size_t& n, clockref clock, unsigned level,
const char* format, va_list args)
{
verify(aug_vformatlog(buf, &n, clock.get(), level, format, args));
}
inline void
formatlog(char* buf, size_t& n, clockref clock, unsigned level,
const char* format, ...)
{
va_list args;
va_start(args, format);
aug_result result(aug_vformatlog(buf, &n, clock.get(), level, format,
args));
va_end(args);
verify(result);
}
inline std::string
vformatlog(clockref clock, unsigned level, const char* format,
va_list args)
{
char buf[AUG_MAXLINE];
size_t n(sizeof(buf));
vformatlog(buf, n, clock, level, format, args);
return std::string(buf, n);
}
inline std::string
formatlog(clockref clock, unsigned level, const char* format, ...)
{
char buf[AUG_MAXLINE];
size_t n(sizeof(buf));
va_list args;
va_start(args, format);
aug_result result(aug_vformatlog(buf, &n, clock.get(), level, format,
args));
va_end(args);
verify(result);
return std::string(buf, n);
}
inline logptr
createdaemonlog(mpoolref mpool, clockref clock)
{
return object_attach<aug_log>
(aug_createdaemonlog(mpool.get(), clock.get()));
}
inline void
setdaemonlog(ctxref ctx)
{
verify(aug_setdaemonlog(ctx.get()));
}
}
#endif // AUGUTILPP_LOG_HPP
| marayl/aug | src/cpp/augutilpp/log.hpp | C++ | gpl-2.0 | 2,797 |
<?php
/**
* Item Controller
*
* @package ReReplacer
* @version 5.4.4
*
* @author Peter van Westen <[email protected]>
* @link http://www.nonumber.nl
* @copyright Copyright © 2012 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
/**
* Item Controller
*/
class ReReplacerControllerItem extends JControllerForm
{
/**
* @var string The prefix to use with controller messages.
*/
protected $text_prefix = 'NN';
// Parent class access checks are sufficient for this controller.
}
| cristhian-fe/EidonKaires | administrator/components/com_rereplacer/controllers/item.php | PHP | gpl-2.0 | 682 |
/*
* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "c1/c1_Compilation.hpp"
#include "c1/c1_Instruction.hpp"
#include "c1/c1_InstructionPrinter.hpp"
#include "c1/c1_LIRAssembler.hpp"
#include "c1/c1_MacroAssembler.hpp"
#include "c1/c1_ValueStack.hpp"
#include "ci/ciInstance.hpp"
#include "runtime/os.hpp"
void LIR_Assembler::patching_epilog(PatchingStub* patch, LIR_PatchCode patch_code, Register obj, CodeEmitInfo* info) {
// We must have enough patching space so that call can be inserted.
// We cannot use fat nops here, since the concurrent code rewrite may transiently
// create the illegal instruction sequence.
while ((intx) _masm->pc() - (intx) patch->pc_start() < NativeGeneralJump::instruction_size) {
_masm->nop();
}
patch->install(_masm, patch_code, obj, info);
append_code_stub(patch);
#ifdef ASSERT
Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());
if (patch->id() == PatchingStub::access_field_id) {
switch (code) {
case Bytecodes::_putstatic:
case Bytecodes::_getstatic:
case Bytecodes::_putfield:
case Bytecodes::_getfield:
break;
default:
ShouldNotReachHere();
}
} else if (patch->id() == PatchingStub::load_klass_id) {
switch (code) {
case Bytecodes::_new:
case Bytecodes::_anewarray:
case Bytecodes::_multianewarray:
case Bytecodes::_instanceof:
case Bytecodes::_checkcast:
break;
default:
ShouldNotReachHere();
}
} else if (patch->id() == PatchingStub::load_mirror_id) {
switch (code) {
case Bytecodes::_putstatic:
case Bytecodes::_getstatic:
case Bytecodes::_ldc:
case Bytecodes::_ldc_w:
break;
default:
ShouldNotReachHere();
}
} else if (patch->id() == PatchingStub::load_appendix_id) {
Bytecodes::Code bc_raw = info->scope()->method()->raw_code_at_bci(info->stack()->bci());
assert(Bytecodes::has_optional_appendix(bc_raw), "unexpected appendix resolution");
} else {
ShouldNotReachHere();
}
#endif
}
PatchingStub::PatchID LIR_Assembler::patching_id(CodeEmitInfo* info) {
IRScope* scope = info->scope();
Bytecodes::Code bc_raw = scope->method()->raw_code_at_bci(info->stack()->bci());
if (Bytecodes::has_optional_appendix(bc_raw)) {
return PatchingStub::load_appendix_id;
}
return PatchingStub::load_mirror_id;
}
//---------------------------------------------------------------
LIR_Assembler::LIR_Assembler(Compilation* c):
_compilation(c)
, _masm(c->masm())
, _bs(Universe::heap()->barrier_set())
, _frame_map(c->frame_map())
, _current_block(NULL)
, _pending_non_safepoint(NULL)
, _pending_non_safepoint_offset(0)
{
_slow_case_stubs = new CodeStubList();
}
LIR_Assembler::~LIR_Assembler() {
}
void LIR_Assembler::check_codespace() {
CodeSection* cs = _masm->code_section();
if (cs->remaining() < (int)(NOT_LP64(1*K)LP64_ONLY(2*K))) {
BAILOUT("CodeBuffer overflow");
}
}
void LIR_Assembler::append_code_stub(CodeStub* stub) {
_slow_case_stubs->append(stub);
}
void LIR_Assembler::emit_stubs(CodeStubList* stub_list) {
for (int m = 0; m < stub_list->length(); m++) {
CodeStub* s = (*stub_list)[m];
check_codespace();
CHECK_BAILOUT();
#ifndef PRODUCT
if (CommentedAssembly) {
stringStream st;
s->print_name(&st);
st.print(" slow case");
_masm->block_comment(st.as_string());
}
#endif
s->emit_code(this);
#ifdef ASSERT
s->assert_no_unbound_labels();
#endif
}
}
void LIR_Assembler::emit_slow_case_stubs() {
emit_stubs(_slow_case_stubs);
}
bool LIR_Assembler::needs_icache(ciMethod* method) const {
return !method->is_static();
}
int LIR_Assembler::code_offset() const {
return _masm->offset();
}
address LIR_Assembler::pc() const {
return _masm->pc();
}
// To bang the stack of this compiled method we use the stack size
// that the interpreter would need in case of a deoptimization. This
// removes the need to bang the stack in the deoptimization blob which
// in turn simplifies stack overflow handling.
int LIR_Assembler::bang_size_in_bytes() const {
return MAX2(initial_frame_size_in_bytes() + os::extra_bang_size_in_bytes(), _compilation->interpreter_frame_size());
}
void LIR_Assembler::emit_exception_entries(ExceptionInfoList* info_list) {
for (int i = 0; i < info_list->length(); i++) {
XHandlers* handlers = info_list->at(i)->exception_handlers();
for (int j = 0; j < handlers->length(); j++) {
XHandler* handler = handlers->handler_at(j);
assert(handler->lir_op_id() != -1, "handler not processed by LinearScan");
assert(handler->entry_code() == NULL ||
handler->entry_code()->instructions_list()->last()->code() == lir_branch ||
handler->entry_code()->instructions_list()->last()->code() == lir_delay_slot, "last operation must be branch");
if (handler->entry_pco() == -1) {
// entry code not emitted yet
if (handler->entry_code() != NULL && handler->entry_code()->instructions_list()->length() > 1) {
handler->set_entry_pco(code_offset());
if (CommentedAssembly) {
_masm->block_comment("Exception adapter block");
}
emit_lir_list(handler->entry_code());
} else {
handler->set_entry_pco(handler->entry_block()->exception_handler_pco());
}
assert(handler->entry_pco() != -1, "must be set now");
}
}
}
}
void LIR_Assembler::emit_code(BlockList* hir) {
if (PrintLIR) {
print_LIR(hir);
}
int n = hir->length();
for (int i = 0; i < n; i++) {
emit_block(hir->at(i));
CHECK_BAILOUT();
}
flush_debug_info(code_offset());
DEBUG_ONLY(check_no_unbound_labels());
}
void LIR_Assembler::emit_block(BlockBegin* block) {
if (block->is_set(BlockBegin::backward_branch_target_flag)) {
align_backward_branch_target();
}
// if this block is the start of an exception handler, record the
// PC offset of the first instruction for later construction of
// the ExceptionHandlerTable
if (block->is_set(BlockBegin::exception_entry_flag)) {
block->set_exception_handler_pco(code_offset());
}
#ifndef PRODUCT
if (PrintLIRWithAssembly) {
// don't print Phi's
InstructionPrinter ip(false);
block->print(ip);
}
#endif /* PRODUCT */
assert(block->lir() != NULL, "must have LIR");
X86_ONLY(assert(_masm->rsp_offset() == 0, "frame size should be fixed"));
#ifndef PRODUCT
if (CommentedAssembly) {
stringStream st;
st.print_cr(" block B%d [%d, %d]", block->block_id(), block->bci(), block->end()->printable_bci());
_masm->block_comment(st.as_string());
}
#endif
emit_lir_list(block->lir());
X86_ONLY(assert(_masm->rsp_offset() == 0, "frame size should be fixed"));
}
void LIR_Assembler::emit_lir_list(LIR_List* list) {
peephole(list);
int n = list->length();
for (int i = 0; i < n; i++) {
LIR_Op* op = list->at(i);
check_codespace();
CHECK_BAILOUT();
#ifndef PRODUCT
if (CommentedAssembly) {
// Don't record out every op since that's too verbose. Print
// branches since they include block and stub names. Also print
// patching moves since they generate funny looking code.
if (op->code() == lir_branch ||
(op->code() == lir_move && op->as_Op1()->patch_code() != lir_patch_none)) {
stringStream st;
op->print_on(&st);
_masm->block_comment(st.as_string());
}
}
if (PrintLIRWithAssembly) {
// print out the LIR operation followed by the resulting assembly
list->at(i)->print(); tty->cr();
}
#endif /* PRODUCT */
op->emit_code(this);
if (compilation()->debug_info_recorder()->recording_non_safepoints()) {
process_debug_info(op);
}
#ifndef PRODUCT
if (PrintLIRWithAssembly) {
_masm->code()->decode();
}
#endif /* PRODUCT */
}
}
#ifdef ASSERT
void LIR_Assembler::check_no_unbound_labels() {
CHECK_BAILOUT();
for (int i = 0; i < _branch_target_blocks.length() - 1; i++) {
if (!_branch_target_blocks.at(i)->label()->is_bound()) {
tty->print_cr("label of block B%d is not bound", _branch_target_blocks.at(i)->block_id());
assert(false, "unbound label");
}
}
}
#endif
//----------------------------------debug info--------------------------------
void LIR_Assembler::add_debug_info_for_branch(CodeEmitInfo* info) {
int pc_offset = code_offset();
flush_debug_info(pc_offset);
info->record_debug_info(compilation()->debug_info_recorder(), pc_offset);
if (info->exception_handlers() != NULL) {
compilation()->add_exception_handlers_for_pco(pc_offset, info->exception_handlers());
}
}
void LIR_Assembler::add_call_info(int pc_offset, CodeEmitInfo* cinfo) {
flush_debug_info(pc_offset);
cinfo->record_debug_info(compilation()->debug_info_recorder(), pc_offset);
if (cinfo->exception_handlers() != NULL) {
compilation()->add_exception_handlers_for_pco(pc_offset, cinfo->exception_handlers());
}
}
static ValueStack* debug_info(Instruction* ins) {
StateSplit* ss = ins->as_StateSplit();
if (ss != NULL) return ss->state();
return ins->state_before();
}
void LIR_Assembler::process_debug_info(LIR_Op* op) {
Instruction* src = op->source();
if (src == NULL) return;
int pc_offset = code_offset();
if (_pending_non_safepoint == src) {
_pending_non_safepoint_offset = pc_offset;
return;
}
ValueStack* vstack = debug_info(src);
if (vstack == NULL) return;
if (_pending_non_safepoint != NULL) {
// Got some old debug info. Get rid of it.
if (debug_info(_pending_non_safepoint) == vstack) {
_pending_non_safepoint_offset = pc_offset;
return;
}
if (_pending_non_safepoint_offset < pc_offset) {
record_non_safepoint_debug_info();
}
_pending_non_safepoint = NULL;
}
// Remember the debug info.
if (pc_offset > compilation()->debug_info_recorder()->last_pc_offset()) {
_pending_non_safepoint = src;
_pending_non_safepoint_offset = pc_offset;
}
}
// Index caller states in s, where 0 is the oldest, 1 its callee, etc.
// Return NULL if n is too large.
// Returns the caller_bci for the next-younger state, also.
static ValueStack* nth_oldest(ValueStack* s, int n, int& bci_result) {
ValueStack* t = s;
for (int i = 0; i < n; i++) {
if (t == NULL) break;
t = t->caller_state();
}
if (t == NULL) return NULL;
for (;;) {
ValueStack* tc = t->caller_state();
if (tc == NULL) return s;
t = tc;
bci_result = tc->bci();
s = s->caller_state();
}
}
void LIR_Assembler::record_non_safepoint_debug_info() {
int pc_offset = _pending_non_safepoint_offset;
ValueStack* vstack = debug_info(_pending_non_safepoint);
int bci = vstack->bci();
DebugInformationRecorder* debug_info = compilation()->debug_info_recorder();
assert(debug_info->recording_non_safepoints(), "sanity");
debug_info->add_non_safepoint(pc_offset);
// Visit scopes from oldest to youngest.
for (int n = 0; ; n++) {
int s_bci = bci;
ValueStack* s = nth_oldest(vstack, n, s_bci);
if (s == NULL) break;
IRScope* scope = s->scope();
//Always pass false for reexecute since these ScopeDescs are never used for deopt
methodHandle null_mh;
debug_info->describe_scope(pc_offset, null_mh, scope->method(), s->bci(), false/*reexecute*/);
}
debug_info->end_non_safepoint(pc_offset);
}
ImplicitNullCheckStub* LIR_Assembler::add_debug_info_for_null_check_here(CodeEmitInfo* cinfo) {
return add_debug_info_for_null_check(code_offset(), cinfo);
}
ImplicitNullCheckStub* LIR_Assembler::add_debug_info_for_null_check(int pc_offset, CodeEmitInfo* cinfo) {
ImplicitNullCheckStub* stub = new ImplicitNullCheckStub(pc_offset, cinfo);
append_code_stub(stub);
return stub;
}
void LIR_Assembler::add_debug_info_for_div0_here(CodeEmitInfo* info) {
add_debug_info_for_div0(code_offset(), info);
}
void LIR_Assembler::add_debug_info_for_div0(int pc_offset, CodeEmitInfo* cinfo) {
DivByZeroStub* stub = new DivByZeroStub(pc_offset, cinfo);
append_code_stub(stub);
}
void LIR_Assembler::emit_rtcall(LIR_OpRTCall* op) {
rt_call(op->result_opr(), op->addr(), op->arguments(), op->tmp(), op->info());
}
void LIR_Assembler::emit_call(LIR_OpJavaCall* op) {
verify_oop_map(op->info());
if (os::is_MP()) {
// must align calls sites, otherwise they can't be updated atomically on MP hardware
align_call(op->code());
}
// emit the static call stub stuff out of line
emit_static_call_stub();
CHECK_BAILOUT();
switch (op->code()) {
case lir_static_call:
case lir_dynamic_call:
call(op, relocInfo::static_call_type);
break;
case lir_optvirtual_call:
call(op, relocInfo::opt_virtual_call_type);
break;
case lir_icvirtual_call:
ic_call(op);
break;
case lir_virtual_call:
vtable_call(op);
break;
default:
fatal("unexpected op code: %s", op->name());
break;
}
// JSR 292
// Record if this method has MethodHandle invokes.
if (op->is_method_handle_invoke()) {
compilation()->set_has_method_handle_invokes(true);
}
#if defined(X86) && defined(TIERED)
// C2 leave fpu stack dirty clean it
if (UseSSE < 2) {
int i;
for ( i = 1; i <= 7 ; i++ ) {
ffree(i);
}
if (!op->result_opr()->is_float_kind()) {
ffree(0);
}
}
#endif // X86 && TIERED
}
void LIR_Assembler::emit_opLabel(LIR_OpLabel* op) {
_masm->bind (*(op->label()));
}
void LIR_Assembler::emit_op1(LIR_Op1* op) {
switch (op->code()) {
case lir_move:
if (op->move_kind() == lir_move_volatile) {
assert(op->patch_code() == lir_patch_none, "can't patch volatiles");
volatile_move_op(op->in_opr(), op->result_opr(), op->type(), op->info());
} else {
move_op(op->in_opr(), op->result_opr(), op->type(),
op->patch_code(), op->info(), op->pop_fpu_stack(),
op->move_kind() == lir_move_unaligned,
op->move_kind() == lir_move_wide);
}
break;
case lir_roundfp: {
LIR_OpRoundFP* round_op = op->as_OpRoundFP();
roundfp_op(round_op->in_opr(), round_op->tmp(), round_op->result_opr(), round_op->pop_fpu_stack());
break;
}
case lir_return:
return_op(op->in_opr());
break;
case lir_safepoint:
if (compilation()->debug_info_recorder()->last_pc_offset() == code_offset()) {
_masm->nop();
}
safepoint_poll(op->in_opr(), op->info());
break;
case lir_fxch:
fxch(op->in_opr()->as_jint());
break;
case lir_fld:
fld(op->in_opr()->as_jint());
break;
case lir_ffree:
ffree(op->in_opr()->as_jint());
break;
case lir_branch:
break;
case lir_push:
push(op->in_opr());
break;
case lir_pop:
pop(op->in_opr());
break;
case lir_neg:
negate(op->in_opr(), op->result_opr());
break;
case lir_leal:
leal(op->in_opr(), op->result_opr());
break;
case lir_null_check:
if (GenerateCompilerNullChecks) {
ImplicitNullCheckStub* stub = add_debug_info_for_null_check_here(op->info());
if (op->in_opr()->is_single_cpu()) {
_masm->null_check(op->in_opr()->as_register(), stub->entry());
} else {
Unimplemented();
}
}
break;
case lir_monaddr:
monitor_address(op->in_opr()->as_constant_ptr()->as_jint(), op->result_opr());
break;
#ifdef SPARC
case lir_pack64:
pack64(op->in_opr(), op->result_opr());
break;
case lir_unpack64:
unpack64(op->in_opr(), op->result_opr());
break;
#endif
case lir_unwind:
unwind_op(op->in_opr());
break;
default:
Unimplemented();
break;
}
}
void LIR_Assembler::emit_op0(LIR_Op0* op) {
switch (op->code()) {
case lir_word_align: {
_masm->align(BytesPerWord);
break;
}
case lir_nop:
assert(op->info() == NULL, "not supported");
_masm->nop();
break;
case lir_label:
Unimplemented();
break;
case lir_build_frame:
build_frame();
break;
case lir_std_entry:
// init offsets
offsets()->set_value(CodeOffsets::OSR_Entry, _masm->offset());
_masm->align(CodeEntryAlignment);
if (needs_icache(compilation()->method())) {
check_icache();
}
offsets()->set_value(CodeOffsets::Verified_Entry, _masm->offset());
_masm->verified_entry();
build_frame();
offsets()->set_value(CodeOffsets::Frame_Complete, _masm->offset());
break;
case lir_osr_entry:
offsets()->set_value(CodeOffsets::OSR_Entry, _masm->offset());
osr_entry();
break;
case lir_24bit_FPU:
set_24bit_FPU();
break;
case lir_reset_FPU:
reset_FPU();
break;
case lir_breakpoint:
breakpoint();
break;
case lir_fpop_raw:
fpop();
break;
case lir_membar:
membar();
break;
case lir_membar_acquire:
membar_acquire();
break;
case lir_membar_release:
membar_release();
break;
case lir_membar_loadload:
membar_loadload();
break;
case lir_membar_storestore:
membar_storestore();
break;
case lir_membar_loadstore:
membar_loadstore();
break;
case lir_membar_storeload:
membar_storeload();
break;
case lir_get_thread:
get_thread(op->result_opr());
break;
default:
ShouldNotReachHere();
break;
}
}
void LIR_Assembler::emit_op2(LIR_Op2* op) {
switch (op->code()) {
case lir_cmp:
if (op->info() != NULL) {
assert(op->in_opr1()->is_address() || op->in_opr2()->is_address(),
"shouldn't be codeemitinfo for non-address operands");
add_debug_info_for_null_check_here(op->info()); // exception possible
}
comp_op(op->condition(), op->in_opr1(), op->in_opr2(), op);
break;
case lir_cmp_l2i:
case lir_cmp_fd2i:
case lir_ucmp_fd2i:
comp_fl2i(op->code(), op->in_opr1(), op->in_opr2(), op->result_opr(), op);
break;
case lir_cmove:
cmove(op->condition(), op->in_opr1(), op->in_opr2(), op->result_opr(), op->type());
break;
case lir_shl:
case lir_shr:
case lir_ushr:
if (op->in_opr2()->is_constant()) {
shift_op(op->code(), op->in_opr1(), op->in_opr2()->as_constant_ptr()->as_jint(), op->result_opr());
} else {
shift_op(op->code(), op->in_opr1(), op->in_opr2(), op->result_opr(), op->tmp1_opr());
}
break;
case lir_add:
case lir_sub:
case lir_mul:
case lir_mul_strictfp:
case lir_div:
case lir_div_strictfp:
case lir_rem:
assert(op->fpu_pop_count() < 2, "");
arith_op(
op->code(),
op->in_opr1(),
op->in_opr2(),
op->result_opr(),
op->info(),
op->fpu_pop_count() == 1);
break;
case lir_abs:
case lir_sqrt:
case lir_sin:
case lir_tan:
case lir_cos:
case lir_log10:
case lir_pow:
intrinsic_op(op->code(), op->in_opr1(), op->in_opr2(), op->result_opr(), op);
break;
case lir_logic_and:
case lir_logic_or:
case lir_logic_xor:
logic_op(
op->code(),
op->in_opr1(),
op->in_opr2(),
op->result_opr());
break;
case lir_throw:
throw_op(op->in_opr1(), op->in_opr2(), op->info());
break;
case lir_xadd:
case lir_xchg:
atomic_op(op->code(), op->in_opr1(), op->in_opr2(), op->result_opr(), op->tmp1_opr());
break;
default:
Unimplemented();
break;
}
}
void LIR_Assembler::build_frame() {
_masm->build_frame(initial_frame_size_in_bytes(), bang_size_in_bytes());
}
void LIR_Assembler::roundfp_op(LIR_Opr src, LIR_Opr tmp, LIR_Opr dest, bool pop_fpu_stack) {
assert((src->is_single_fpu() && dest->is_single_stack()) ||
(src->is_double_fpu() && dest->is_double_stack()),
"round_fp: rounds register -> stack location");
reg2stack (src, dest, src->type(), pop_fpu_stack);
}
void LIR_Assembler::move_op(LIR_Opr src, LIR_Opr dest, BasicType type, LIR_PatchCode patch_code, CodeEmitInfo* info, bool pop_fpu_stack, bool unaligned, bool wide) {
if (src->is_register()) {
if (dest->is_register()) {
assert(patch_code == lir_patch_none && info == NULL, "no patching and info allowed here");
reg2reg(src, dest);
} else if (dest->is_stack()) {
assert(patch_code == lir_patch_none && info == NULL, "no patching and info allowed here");
reg2stack(src, dest, type, pop_fpu_stack);
} else if (dest->is_address()) {
reg2mem(src, dest, type, patch_code, info, pop_fpu_stack, wide, unaligned);
} else {
ShouldNotReachHere();
}
} else if (src->is_stack()) {
assert(patch_code == lir_patch_none && info == NULL, "no patching and info allowed here");
if (dest->is_register()) {
stack2reg(src, dest, type);
} else if (dest->is_stack()) {
stack2stack(src, dest, type);
} else {
ShouldNotReachHere();
}
} else if (src->is_constant()) {
if (dest->is_register()) {
const2reg(src, dest, patch_code, info); // patching is possible
} else if (dest->is_stack()) {
assert(patch_code == lir_patch_none && info == NULL, "no patching and info allowed here");
const2stack(src, dest);
} else if (dest->is_address()) {
assert(patch_code == lir_patch_none, "no patching allowed here");
const2mem(src, dest, type, info, wide);
} else {
ShouldNotReachHere();
}
} else if (src->is_address()) {
mem2reg(src, dest, type, patch_code, info, wide, unaligned);
} else {
ShouldNotReachHere();
}
}
void LIR_Assembler::verify_oop_map(CodeEmitInfo* info) {
#ifndef PRODUCT
if (VerifyOops) {
OopMapStream s(info->oop_map());
while (!s.is_done()) {
OopMapValue v = s.current();
if (v.is_oop()) {
VMReg r = v.reg();
if (!r->is_stack()) {
stringStream st;
st.print("bad oop %s at %d", r->as_Register()->name(), _masm->offset());
#ifdef SPARC
_masm->_verify_oop(r->as_Register(), os::strdup(st.as_string(), mtCompiler), __FILE__, __LINE__);
#else
_masm->verify_oop(r->as_Register());
#endif
} else {
_masm->verify_stack_oop(r->reg2stack() * VMRegImpl::stack_slot_size);
}
}
check_codespace();
CHECK_BAILOUT();
s.next();
}
}
#endif
}
| gaoxiaojun/dync | src/share/vm/c1/c1_LIRAssembler.cpp | C++ | gpl-2.0 | 23,698 |
-- Unban a player banned with Punkbuster.
-- From kmod script.
-- params is parameters passed from et_ClientCommand function.
-- * params["arg1"] => guid
function execute_command(params)
params.say = "chat"
if params.nbArg < 2 then
printCmdMsg(params, "Useage: unban [guid]\n")
else
if tonumber(et.trap_Cvar_Get("sv_punkbuster")) == 1 then
et.trap_SendConsoleCommand(
et.EXEC_APPEND,
"pb_sv_unbanguid " .. params["arg1"] .. "\n"
)
et.trap_SendConsoleCommand(
et.EXEC_APPEND,
"pb_sv_UpdBanFile\n"
)
params.broadcast2allClients = true
params.noDisplayCmd = true
printCmdMsg(
params,
client[clientNum]["name"] .. " have been unbanned\n"
)
else
printCmdMsg(
params,
"Cannot unban with Punkbuster (Punkbuster is disable).\n"
)
end
end
return 1
end
| cyrillePrigent/kmod-ng | umod/command/client/unban.lua | Lua | gpl-2.0 | 1,059 |
define(function () {
return {
customerAccount: ['CustomerAccountService', function (CustomerAccountService) {
return CustomerAccountService.getCurrent();
}]
};
});
| lordmarkm/tyrael-laundry | tyrael-laundry-dist/src/main/webapp/common/resolve/JobOrderListResolve.js | JavaScript | gpl-2.0 | 182 |
<ul class="lang-switch nav navbar-nav navbar-right">
<li role="heading"><span class="nav-plain-text">Language:</span></li>
<li><a {% if page.lang contains 'en' %} class="active-lang"{% endif %} href="
{% if page.url contains '/fr' %}{{ page.url | remove_first:'/fr' }}
{% elsif page.url contains '/es' %}{{ page.url | remove_first:'/es' }}
{% else %}{{ page.url }}
{% endif %}" title="English">En</a></li>
<li><a {% if page.lang contains 'fr' %} class="active-lang"{% endif %} href="
{% if page.url contains '/fr' %}{{ page.url }}
{% elsif page.url contains '/es' %}{{ page.url | replace_first:'/es','/fr' }}
{% else %}{{ page.url | prepend:'/fr' }}
{% endif %}" title="French">Fr</a></li>
<li><a {% if page.lang contains 'es' %} class="active-lang"{% endif %} href="
{% if page.url contains '/es' %}{{ page.url }}
{% elsif page.url contains '/fr' %}{{ page.url | replace_first:'/fr','/es' }}
{% else %}{{ page.url | prepend:'/es' }}
{% endif %}" title="Spanish">Es</a></li>
</ul>
| opentechinstitute/commotion-docs | commotionwireless.net/_includes/language-switcher-navbar.html | HTML | gpl-2.0 | 1,095 |
/*
Tests multidimensional numerical integration using cubature.
Copyright 2014 Ilja Honkonen
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/>.
*/
#include "array"
#include "cmath"
#include "cstdlib"
#include "iostream"
#include "limits"
#include "cubature.h"
bool good_solution(
const double integral,
const double exact,
const double max_relative_error
) {
if (
std::fabs(integral - exact)
> max_relative_error * std::max(std::fabs(integral), std::fabs(exact))
) {
return false;
}
return true;
}
int main()
{
constexpr double max_acceptable_error = 1e-9;
// integration range
const std::array<double, 3> start{1, 1, 1}, end{2, 2, 2};
double integral, error, exact;
/*
Returns x*y^2*z^3.
In dimension(s) over which pcubature is integrating, x, y or z
are given by r, the rest are given in extra_data. Format of
extra_data: std::pair<std::array<size_t, 3>, std::array<double, 3>>.
size_t tells the index of the dimension over which integration over
Nth dimension in r actually goes. The first r_dims of
size_t's contain valid data. For the rest the corresponding
double contains the coordinate at which to integrate over the
rest of dimensions of r.
For example when integrating x and z from 0 to 1 with y == -2
integrand could be called by cubature as (999's mark unused data):
f = integrand(
2,
std::array<double, 2>{0, 0}.data(),
std::pair<
std::array<size_t, 3>,
std::array<double, 3>
>{{0, 2, 999}, {999, -2, 999}}.data(),
1,
ret_val.data()
);
and when integrating y from -2 to -1 with x == 0.5 and z == 2/3:
f = integrand(
1,
std::array<double, 1>{-2}.data(),
std::pair<
std::array<size_t, 3>,
std::array<double, 3>
>{{1, 999, 999}, {0.5, 999, 2/3}}.data(),
1,
ret_val.data()
);
*/
auto integrand
= [](
unsigned r_dims,
const double* r,
void* extra_data,
unsigned f_dims,
double* f
) {
if (r_dims == 0) {
return -1;
}
if (f_dims != 1) {
return -2;
}
if (r == NULL) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (f == NULL) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (extra_data == NULL) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
const auto integration_info
= *static_cast<
std::pair<
std::array<size_t, 3>,
std::array<double, 3>
>*
>(extra_data);
std::array<double, 3> real_r = integration_info.second;
for (size_t i = 0; i < r_dims; i++) {
if (integration_info.first[i] > 3) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
real_r[integration_info.first[i]] = *(r + i);
}
*f
= std::pow(real_r[0], 1)
* std::pow(real_r[1], 2)
* std::pow(real_r[2], 3);
return 0;
};
std::pair<std::array<size_t, 3>, std::array<double, 3>> integration_parameters;
// 1d over x at y == 3/2 and z == 3/2
exact = std::pow(3./2., 6);
integration_parameters.first[0] = 0;
integration_parameters.first[1] = 999;
integration_parameters.first[2] = 999;
integration_parameters.second[0] = 999;
integration_parameters.second[1] = 3.0 / 2.0;
integration_parameters.second[2] = 3.0 / 2.0;
if (
pcubature(
1,
integrand,
&integration_parameters,
1,
start.data(),
end.data(),
0,
0,
1e-3,
ERROR_LINF,
&integral,
&error
) != 0
) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (not good_solution(integral, exact, max_acceptable_error)) {
std::cerr << __FILE__ << "(" << __LINE__ << "): "
<< "Too large relative error when integrating from " << start[0]
<< " to " << end[0]
<< ", exact: " << exact
<< ", numerical: " << integral
<< std::endl;
abort();
}
// 2d over y and z at x == 3/2
exact = 105.0 / 8.0;
integration_parameters.first[0] = 1;
integration_parameters.first[1] = 2;
integration_parameters.first[2] = 999;
integration_parameters.second[0] = 3.0 / 2.0;
integration_parameters.second[1] = 999;
integration_parameters.second[2] = 999;
if (
pcubature(
1,
integrand,
&integration_parameters,
2,
start.data(),
end.data(),
0,
0,
1e-3,
ERROR_LINF,
&integral,
&error
) != 0
) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (not good_solution(integral, exact, max_acceptable_error)) {
std::cerr << __FILE__ << "(" << __LINE__ << "): "
<< "Too large relative error when integrating from "
<< start[1] << "," << start[2]
<< " to " << end[1] << "," << end[2]
<< ", exact: " << exact
<< ", numerical: " << integral
<< std::endl;
abort();
}
// integrate over the edges of the unit cube from start to end
std::array<
std::pair<
// exact value for below integration parameters
double,
// same as in integration_parameters
std::pair<
std::array<size_t, 3>,
std::array<double, 3>
>
>,
12
> integration_params1d{{
// over x at min y, min z
{3.0 / 2.0, {{0, 999, 999}, {999, 1, 1}}},
// x at min y, max z
{12, {{0, 999, 999}, {999, 1, 2}}},
// x at max y, min z
{6, {{0, 999, 999}, {999, 2, 1}}},
// x at max y, max z
{48, {{0, 999, 999}, {999, 2, 2}}},
// over y at min x, min z
{7.0 / 3.0, {{1, 999, 999}, {1, 999, 1}}},
// y at min x, max z
{56.0 / 3.0, {{1, 999, 999}, {1, 999, 2}}},
// y at max y, min z
{14.0 / 3.0, {{1, 999, 999}, {2, 999, 1}}},
// y at max x, max z
{112.0 / 3.0, {{1, 999, 999}, {2, 999, 2}}},
// over z at min x, min y
{15.0 / 4.0, {{2, 999, 999}, {1, 1, 999}}},
// z at min x, max y
{15, {{2, 999, 999}, {1, 2, 999}}},
// z at max x, min y
{15.0 / 2.0, {{2, 999, 999}, {2, 1, 999}}},
// z at max x, max y
{30, {{2, 999, 999}, {2, 2, 999}}}
}};
for (auto& info: integration_params1d) {
const double exact = info.first;
if (
pcubature(
1,
integrand,
&info.second,
1,
start.data(),
end.data(),
0,
0,
1e-3,
ERROR_LINF,
&integral,
&error
) != 0
) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (not good_solution(integral, exact, max_acceptable_error)) {
std::cerr << __FILE__ << "(" << __LINE__ << "): "
<< "Too large relative error, exact: " << exact
<< ", numerical: " << integral
<< std::endl;
abort();
}
}
// integrate over the faces of the unit cube from start to end
std::array<
std::pair<
double,
std::pair<
std::array<size_t, 3>,
std::array<double, 3>
>
>,
6
> integration_params2d{{
// over x and y at min z
{7.0 / 2.0, {{0, 1, 999}, {999, 999, 1}}},
// x, y at max z
{28, {{0, 1, 999}, {999, 999, 2}}},
// x, z at min y
{45.0 / 8.0, {{0, 2, 999}, {999, 1, 999}}},
// x, z at max y
{45.0 / 2.0, {{0, 2, 999}, {999, 2, 999}}},
// y, z at min x
{35.0 / 4.0, {{1, 2, 999}, {1, 999, 999}}},
// y, z at max x
{35.0 / 2.0, {{1, 2, 999}, {2, 999, 999}}}
}};
for (auto& info: integration_params2d) {
const double exact = info.first;
if (
pcubature(
1,
integrand,
&info.second,
2,
start.data(),
end.data(),
0,
0,
1e-3,
ERROR_LINF,
&integral,
&error
) != 0
) {
std::cerr << __FILE__ << "(" << __LINE__ << ")" << std::endl;
abort();
}
if (not good_solution(integral, exact, max_acceptable_error)) {
std::cerr << __FILE__ << "(" << __LINE__ << "): "
<< "Too large relative error, exact: " << exact
<< ", numerical: " << integral
<< std::endl;
abort();
}
}
return EXIT_SUCCESS;
}
| nasailja/background_B | tests/integration/cubature_multidim.cpp | C++ | gpl-2.0 | 8,198 |
/*
* linux/include/linux/jbd2.h
*
* Written by Stephen C. Tweedie <[email protected]>
*
* Copyright 1998-2000 Red Hat, Inc --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Definitions for transaction data structures for the buffer cache
* filesystem journaling support.
*/
#ifndef _LINUX_JBD2_H
#define _LINUX_JBD2_H
/* Allow this file to be included directly into e2fsprogs */
#ifndef __KERNEL__
#include "jfs_compat.h"
#define JBD2_DEBUG
#define jfs_debug jbd_debug
#else
#include <linux/types.h>
#include <linux/buffer_head.h>
#include <linux/journal-head.h>
#include <linux/stddef.h>
#include <linux/bit_spinlock.h>
#include <linux/mutex.h>
#include <linux/timer.h>
#endif
#define journal_oom_retry 1
/*
* Define JBD2_PARANIOD_IOFAIL to cause a kernel BUG() if ext4 finds
* certain classes of error which can occur due to failed IOs. Under
* normal use we want ext4 to continue after such errors, because
* hardware _can_ fail, but for debugging purposes when running tests on
* known-good hardware we may want to trap these errors.
*/
#undef JBD2_PARANOID_IOFAIL
/*
* The default maximum commit age, in seconds.
*/
#define JBD2_DEFAULT_MAX_COMMIT_AGE 5
#ifdef CONFIG_JBD2_DEBUG
/*
* Define JBD2_EXPENSIVE_CHECKING to enable more expensive internal
* consistency checks. By default we don't do this unless
* CONFIG_JBD2_DEBUG is on.
*/
#define JBD2_EXPENSIVE_CHECKING
extern u8 jbd2_journal_enable_debug;
#define jbd_debug(n, f, a...) \
do { \
if ((n) <= jbd2_journal_enable_debug) { \
printk (KERN_DEBUG "(%s, %d): %s: ", \
__FILE__, __LINE__, __FUNCTION__); \
printk (f, ## a); \
} \
} while (0)
#else
#define jbd_debug(f, a...) /**/
#endif
static inline void *jbd2_alloc(size_t size, gfp_t flags)
{
return (void *)__get_free_pages(flags, get_order(size));
}
static inline void jbd2_free(void *ptr, size_t size)
{
free_pages((unsigned long)ptr, get_order(size));
};
#define JBD2_MIN_JOURNAL_BLOCKS 1024
#ifdef __KERNEL__
/**
* typedef handle_t - The handle_t type represents a single atomic update being performed by some process.
*
* All filesystem modifications made by the process go
* through this handle. Recursive operations (such as quota operations)
* are gathered into a single update.
*
* The buffer credits field is used to account for journaled buffers
* being modified by the running process. To ensure that there is
* enough log space for all outstanding operations, we need to limit the
* number of outstanding buffers possible at any time. When the
* operation completes, any buffer credits not used are credited back to
* the transaction, so that at all times we know how many buffers the
* outstanding updates on a transaction might possibly touch.
*
* This is an opaque datatype.
**/
typedef struct handle_s handle_t; /* Atomic operation type */
/**
* typedef journal_t - The journal_t maintains all of the journaling state information for a single filesystem.
*
* journal_t is linked to from the fs superblock structure.
*
* We use the journal_t to keep track of all outstanding transaction
* activity on the filesystem, and to manage the state of the log
* writing process.
*
* This is an opaque datatype.
**/
typedef struct journal_s journal_t; /* Journal control structure */
#endif
/*
* Internal structures used by the logging mechanism:
*/
#define JBD2_MAGIC_NUMBER 0xc03b3998U /* The first 4 bytes of /dev/random! */
/*
* On-disk structures
*/
/*
* Descriptor block types:
*/
#define JBD2_DESCRIPTOR_BLOCK 1
#define JBD2_COMMIT_BLOCK 2
#define JBD2_SUPERBLOCK_V1 3
#define JBD2_SUPERBLOCK_V2 4
#define JBD2_REVOKE_BLOCK 5
/*
* Standard header for all descriptor blocks:
*/
typedef struct journal_header_s
{
__be32 h_magic;
__be32 h_blocktype;
__be32 h_sequence;
} journal_header_t;
/*
* Checksum types.
*/
#define JBD2_CRC32_CHKSUM 1
#define JBD2_MD5_CHKSUM 2
#define JBD2_SHA1_CHKSUM 3
#define JBD2_CRC32_CHKSUM_SIZE 4
#define JBD2_CHECKSUM_BYTES (32 / sizeof(u32))
/*
* Commit block header for storing transactional checksums:
*/
struct commit_header {
__be32 h_magic;
__be32 h_blocktype;
__be32 h_sequence;
unsigned char h_chksum_type;
unsigned char h_chksum_size;
unsigned char h_padding[2];
__be32 h_chksum[JBD2_CHECKSUM_BYTES];
__be64 h_commit_sec;
__be32 h_commit_nsec;
};
/*
* The block tag: used to describe a single buffer in the journal.
* t_blocknr_high is only used if INCOMPAT_64BIT is set, so this
* raw struct shouldn't be used for pointer math or sizeof() - use
* journal_tag_bytes(journal) instead to compute this.
*/
typedef struct journal_block_tag_s
{
__be32 t_blocknr; /* The on-disk block number */
__be32 t_flags; /* See below */
__be32 t_blocknr_high; /* most-significant high 32bits. */
} journal_block_tag_t;
#define JBD2_TAG_SIZE32 (offsetof(journal_block_tag_t, t_blocknr_high))
#define JBD2_TAG_SIZE64 (sizeof(journal_block_tag_t))
/*
* The revoke descriptor: used on disk to describe a series of blocks to
* be revoked from the log
*/
typedef struct jbd2_journal_revoke_header_s
{
journal_header_t r_header;
__be32 r_count; /* Count of bytes used in the block */
} jbd2_journal_revoke_header_t;
/* Definitions for the journal tag flags word: */
#define JBD2_FLAG_ESCAPE 1 /* on-disk block is escaped */
#define JBD2_FLAG_SAME_UUID 2 /* block has same uuid as previous */
#define JBD2_FLAG_DELETED 4 /* block deleted by this transaction */
#define JBD2_FLAG_LAST_TAG 8 /* last tag in this descriptor block */
/*
* The journal superblock. All fields are in big-endian byte order.
*/
typedef struct journal_superblock_s
{
/* 0x0000 */
journal_header_t s_header;
/* 0x000C */
/* Static information describing the journal */
__be32 s_blocksize; /* journal device blocksize */
__be32 s_maxlen; /* total blocks in journal file */
__be32 s_first; /* first block of log information */
/* 0x0018 */
/* Dynamic information describing the current state of the log */
__be32 s_sequence; /* first commit ID expected in log */
__be32 s_start; /* blocknr of start of log */
/* 0x0020 */
/* Error value, as set by jbd2_journal_abort(). */
__be32 s_errno;
/* 0x0024 */
/* Remaining fields are only valid in a version-2 superblock */
__be32 s_feature_compat; /* compatible feature set */
__be32 s_feature_incompat; /* incompatible feature set */
__be32 s_feature_ro_compat; /* readonly-compatible feature set */
/* 0x0030 */
__u8 s_uuid[16]; /* 128-bit uuid for journal */
/* 0x0040 */
__be32 s_nr_users; /* Nr of filesystems sharing log */
__be32 s_dynsuper; /* Blocknr of dynamic superblock copy*/
/* 0x0048 */
__be32 s_max_transaction; /* Limit of journal blocks per trans.*/
__be32 s_max_trans_data; /* Limit of data blocks per trans. */
/* 0x0050 */
__u32 s_padding[44];
/* 0x0100 */
__u8 s_users[16*48]; /* ids of all fs'es sharing the log */
/* 0x0400 */
} journal_superblock_t;
#define JBD2_HAS_COMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_compat & cpu_to_be32((mask))))
#define JBD2_HAS_RO_COMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_ro_compat & cpu_to_be32((mask))))
#define JBD2_HAS_INCOMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_incompat & cpu_to_be32((mask))))
#define JBD2_FEATURE_COMPAT_CHECKSUM 0x00000001
#define JBD2_FEATURE_INCOMPAT_REVOKE 0x00000001
#define JBD2_FEATURE_INCOMPAT_64BIT 0x00000002
#define JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT 0x00000004
/* Features known to this kernel version: */
#define JBD2_KNOWN_COMPAT_FEATURES JBD2_FEATURE_COMPAT_CHECKSUM
#define JBD2_KNOWN_ROCOMPAT_FEATURES 0
#define JBD2_KNOWN_INCOMPAT_FEATURES (JBD2_FEATURE_INCOMPAT_REVOKE | \
JBD2_FEATURE_INCOMPAT_64BIT | \
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT)
#ifdef __KERNEL__
#include <linux/fs.h>
#include <linux/sched.h>
#define J_ASSERT(assert) BUG_ON(!(assert))
#if defined(CONFIG_BUFFER_DEBUG)
void buffer_assertion_failure(struct buffer_head *bh);
#define J_ASSERT_BH(bh, expr) \
do { \
if (!(expr)) \
buffer_assertion_failure(bh); \
J_ASSERT(expr); \
} while (0)
#define J_ASSERT_JH(jh, expr) J_ASSERT_BH(jh2bh(jh), expr)
#else
#define J_ASSERT_BH(bh, expr) J_ASSERT(expr)
#define J_ASSERT_JH(jh, expr) J_ASSERT(expr)
#endif
#if defined(JBD2_PARANOID_IOFAIL)
#define J_EXPECT(expr, why...) J_ASSERT(expr)
#define J_EXPECT_BH(bh, expr, why...) J_ASSERT_BH(bh, expr)
#define J_EXPECT_JH(jh, expr, why...) J_ASSERT_JH(jh, expr)
#else
#define __journal_expect(expr, why...) \
({ \
int val = (expr); \
if (!val) { \
printk(KERN_ERR \
"EXT3-fs unexpected failure: %s;\n",# expr); \
printk(KERN_ERR why "\n"); \
} \
val; \
})
#define J_EXPECT(expr, why...) __journal_expect(expr, ## why)
#define J_EXPECT_BH(bh, expr, why...) __journal_expect(expr, ## why)
#define J_EXPECT_JH(jh, expr, why...) __journal_expect(expr, ## why)
#endif
enum jbd_state_bits {
BH_JBD /* Has an attached ext3 journal_head */
= BH_PrivateStart,
BH_JWrite, /* Being written to log (@@@ DEBUGGING) */
BH_Freed, /* Has been freed (truncated) */
BH_Revoked, /* Has been revoked from the log */
BH_RevokeValid, /* Revoked flag is valid */
BH_JBDDirty, /* Is dirty but journaled */
BH_State, /* Pins most journal_head state */
BH_JournalHead, /* Pins bh->b_private and jh->b_bh */
BH_Unshadow, /* Dummy bit, for BJ_Shadow wakeup filtering */
};
BUFFER_FNS(JBD, jbd)
BUFFER_FNS(JWrite, jwrite)
BUFFER_FNS(JBDDirty, jbddirty)
TAS_BUFFER_FNS(JBDDirty, jbddirty)
BUFFER_FNS(Revoked, revoked)
TAS_BUFFER_FNS(Revoked, revoked)
BUFFER_FNS(RevokeValid, revokevalid)
TAS_BUFFER_FNS(RevokeValid, revokevalid)
BUFFER_FNS(Freed, freed)
static inline struct buffer_head *jh2bh(struct journal_head *jh)
{
return jh->b_bh;
}
static inline struct journal_head *bh2jh(struct buffer_head *bh)
{
return bh->b_private;
}
static inline void jbd_lock_bh_state(struct buffer_head *bh)
{
bit_spin_lock(BH_State, &bh->b_state);
}
static inline int jbd_trylock_bh_state(struct buffer_head *bh)
{
return bit_spin_trylock(BH_State, &bh->b_state);
}
static inline int jbd_is_locked_bh_state(struct buffer_head *bh)
{
return bit_spin_is_locked(BH_State, &bh->b_state);
}
static inline void jbd_unlock_bh_state(struct buffer_head *bh)
{
bit_spin_unlock(BH_State, &bh->b_state);
}
static inline void jbd_lock_bh_journal_head(struct buffer_head *bh)
{
bit_spin_lock(BH_JournalHead, &bh->b_state);
}
static inline void jbd_unlock_bh_journal_head(struct buffer_head *bh)
{
bit_spin_unlock(BH_JournalHead, &bh->b_state);
}
/* Flags in jbd_inode->i_flags */
#define __JI_COMMIT_RUNNING 0
/* Commit of the inode data in progress. We use this flag to protect us from
* concurrent deletion of inode. We cannot use reference to inode for this
* since we cannot afford doing last iput() on behalf of kjournald
*/
#define JI_COMMIT_RUNNING (1 << __JI_COMMIT_RUNNING)
/**
* struct jbd_inode is the structure linking inodes in ordered mode
* present in a transaction so that we can sync them during commit.
*/
struct jbd2_inode {
/* Which transaction does this inode belong to? Either the running
* transaction or the committing one. [j_list_lock] */
transaction_t *i_transaction;
/* Pointer to the running transaction modifying inode's data in case
* there is already a committing transaction touching it. [j_list_lock] */
transaction_t *i_next_transaction;
/* List of inodes in the i_transaction [j_list_lock] */
struct list_head i_list;
/* VFS inode this inode belongs to [constant during the lifetime
* of the structure] */
struct inode *i_vfs_inode;
/* Flags of inode [j_list_lock] */
unsigned int i_flags;
};
struct jbd2_revoke_table_s;
/**
* struct handle_s - The handle_s type is the concrete type associated with
* handle_t.
* @h_transaction: Which compound transaction is this update a part of?
* @h_buffer_credits: Number of remaining buffers we are allowed to dirty.
* @h_ref: Reference count on this handle
* @h_err: Field for caller's use to track errors through large fs operations
* @h_sync: flag for sync-on-close
* @h_jdata: flag to force data journaling
* @h_aborted: flag indicating fatal error on handle
**/
/* Docbook can't yet cope with the bit fields, but will leave the documentation
* in so it can be fixed later.
*/
struct handle_s
{
/* Which compound transaction is this update a part of? */
transaction_t *h_transaction;
/* Number of remaining buffers we are allowed to dirty: */
int h_buffer_credits;
/* Reference count on this handle */
int h_ref;
/* Field for caller's use to track errors through large fs */
/* operations */
int h_err;
/* Flags [no locking] */
unsigned int h_sync: 1; /* sync-on-close */
unsigned int h_jdata: 1; /* force data journaling */
unsigned int h_aborted: 1; /* fatal error on handle */
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map h_lockdep_map;
#endif
};
/*
* Some stats for checkpoint phase
*/
struct transaction_chp_stats_s {
unsigned long cs_chp_time;
unsigned long cs_forced_to_close;
unsigned long cs_written;
unsigned long cs_dropped;
};
/* The transaction_t type is the guts of the journaling mechanism. It
* tracks a compound transaction through its various states:
*
* RUNNING: accepting new updates
* LOCKED: Updates still running but we don't accept new ones
* RUNDOWN: Updates are tidying up but have finished requesting
* new buffers to modify (state not used for now)
* FLUSH: All updates complete, but we are still writing to disk
* COMMIT: All data on disk, writing commit record
* FINISHED: We still have to keep the transaction for checkpointing.
*
* The transaction keeps track of all of the buffers modified by a
* running transaction, and all of the buffers committed but not yet
* flushed to home for finished transactions.
*/
/*
* Lock ranking:
*
* j_list_lock
* ->jbd_lock_bh_journal_head() (This is "innermost")
*
* j_state_lock
* ->jbd_lock_bh_state()
*
* jbd_lock_bh_state()
* ->j_list_lock
*
* j_state_lock
* ->t_handle_lock
*
* j_state_lock
* ->j_list_lock (journal_unmap_buffer)
*
*/
struct transaction_s
{
/* Pointer to the journal for this transaction. [no locking] */
journal_t *t_journal;
/* Sequence number for this transaction [no locking] */
tid_t t_tid;
/*
* Transaction's current state
* [no locking - only kjournald2 alters this]
* [j_list_lock] guards transition of a transaction into T_FINISHED
* state and subsequent call of __jbd2_journal_drop_transaction()
* FIXME: needs barriers
* KLUDGE: [use j_state_lock]
*/
enum {
T_RUNNING,
T_LOCKED,
T_RUNDOWN,
T_FLUSH,
T_COMMIT,
T_FINISHED
} t_state;
/*
* Where in the log does this transaction's commit start? [no locking]
*/
unsigned long t_log_start;
/* Number of buffers on the t_buffers list [j_list_lock] */
int t_nr_buffers;
/*
* Doubly-linked circular list of all buffers reserved but not yet
* modified by this transaction [j_list_lock]
*/
struct journal_head *t_reserved_list;
/*
* Doubly-linked circular list of all metadata buffers owned by this
* transaction [j_list_lock]
*/
struct journal_head *t_buffers;
/*
* Doubly-linked circular list of all forget buffers (superseded
* buffers which we can un-checkpoint once this transaction commits)
* [j_list_lock]
*/
struct journal_head *t_forget;
/*
* Doubly-linked circular list of all buffers still to be flushed before
* this transaction can be checkpointed. [j_list_lock]
*/
struct journal_head *t_checkpoint_list;
/*
* Doubly-linked circular list of all buffers submitted for IO while
* checkpointing. [j_list_lock]
*/
struct journal_head *t_checkpoint_io_list;
/*
* Doubly-linked circular list of temporary buffers currently undergoing
* IO in the log [j_list_lock]
*/
struct journal_head *t_iobuf_list;
/*
* Doubly-linked circular list of metadata buffers being shadowed by log
* IO. The IO buffers on the iobuf list and the shadow buffers on this
* list match each other one for one at all times. [j_list_lock]
*/
struct journal_head *t_shadow_list;
/*
* Doubly-linked circular list of control buffers being written to the
* log. [j_list_lock]
*/
struct journal_head *t_log_list;
/*
* List of inodes whose data we've modified in data=ordered mode.
* [j_list_lock]
*/
struct list_head t_inode_list;
/*
* Protects info related to handles
*/
spinlock_t t_handle_lock;
/*
* Longest time some handle had to wait for running transaction
*/
unsigned long t_max_wait;
/*
* When transaction started
*/
unsigned long t_start;
/*
* Checkpointing stats [j_checkpoint_sem]
*/
struct transaction_chp_stats_s t_chp_stats;
/*
* Number of outstanding updates running on this transaction
* [t_handle_lock]
*/
int t_updates;
/*
* Number of buffers reserved for use by all handles in this transaction
* handle but not yet modified. [t_handle_lock]
*/
int t_outstanding_credits;
/*
* Forward and backward links for the circular list of all transactions
* awaiting checkpoint. [j_list_lock]
*/
transaction_t *t_cpnext, *t_cpprev;
/*
* When will the transaction expire (become due for commit), in jiffies?
* [no locking]
*/
unsigned long t_expires;
/*
* How many handles used this transaction? [t_handle_lock]
*/
int t_handle_count;
};
struct transaction_run_stats_s {
unsigned long rs_wait;
unsigned long rs_running;
unsigned long rs_locked;
unsigned long rs_flushing;
unsigned long rs_logging;
unsigned long rs_handle_count;
unsigned long rs_blocks;
unsigned long rs_blocks_logged;
};
struct transaction_stats_s {
int ts_type;
unsigned long ts_tid;
union {
struct transaction_run_stats_s run;
struct transaction_chp_stats_s chp;
} u;
};
#define JBD2_STATS_RUN 1
#define JBD2_STATS_CHECKPOINT 2
static inline unsigned long
jbd2_time_diff(unsigned long start, unsigned long end)
{
if (end >= start)
return end - start;
return end + (MAX_JIFFY_OFFSET - start);
}
/**
* struct journal_s - The journal_s type is the concrete type associated with
* journal_t.
* @j_flags: General journaling state flags
* @j_errno: Is there an outstanding uncleared error on the journal (from a
* prior abort)?
* @j_sb_buffer: First part of superblock buffer
* @j_superblock: Second part of superblock buffer
* @j_format_version: Version of the superblock format
* @j_state_lock: Protect the various scalars in the journal
* @j_barrier_count: Number of processes waiting to create a barrier lock
* @j_barrier: The barrier lock itself
* @j_running_transaction: The current running transaction..
* @j_committing_transaction: the transaction we are pushing to disk
* @j_checkpoint_transactions: a linked circular list of all transactions
* waiting for checkpointing
* @j_wait_transaction_locked: Wait queue for waiting for a locked transaction
* to start committing, or for a barrier lock to be released
* @j_wait_logspace: Wait queue for waiting for checkpointing to complete
* @j_wait_done_commit: Wait queue for waiting for commit to complete
* @j_wait_checkpoint: Wait queue to trigger checkpointing
* @j_wait_commit: Wait queue to trigger commit
* @j_wait_updates: Wait queue to wait for updates to complete
* @j_checkpoint_mutex: Mutex for locking against concurrent checkpoints
* @j_head: Journal head - identifies the first unused block in the journal
* @j_tail: Journal tail - identifies the oldest still-used block in the
* journal.
* @j_free: Journal free - how many free blocks are there in the journal?
* @j_first: The block number of the first usable block
* @j_last: The block number one beyond the last usable block
* @j_dev: Device where we store the journal
* @j_blocksize: blocksize for the location where we store the journal.
* @j_blk_offset: starting block offset for into the device where we store the
* journal
* @j_fs_dev: Device which holds the client fs. For internal journal this will
* be equal to j_dev
* @j_maxlen: Total maximum capacity of the journal region on disk.
* @j_list_lock: Protects the buffer lists and internal buffer state.
* @j_inode: Optional inode where we store the journal. If present, all journal
* block numbers are mapped into this inode via bmap().
* @j_tail_sequence: Sequence number of the oldest transaction in the log
* @j_transaction_sequence: Sequence number of the next transaction to grant
* @j_commit_sequence: Sequence number of the most recently committed
* transaction
* @j_commit_request: Sequence number of the most recent transaction wanting
* commit
* @j_uuid: Uuid of client object.
* @j_task: Pointer to the current commit thread for this journal
* @j_max_transaction_buffers: Maximum number of metadata buffers to allow in a
* single compound commit transaction
* @j_commit_interval: What is the maximum transaction lifetime before we begin
* a commit?
* @j_commit_timer: The timer used to wakeup the commit thread
* @j_revoke_lock: Protect the revoke table
* @j_revoke: The revoke table - maintains the list of revoked blocks in the
* current transaction.
* @j_revoke_table: alternate revoke tables for j_revoke
* @j_wbuf: array of buffer_heads for jbd2_journal_commit_transaction
* @j_wbufsize: maximum number of buffer_heads allowed in j_wbuf, the
* number that will fit in j_blocksize
* @j_last_sync_writer: most recent pid which did a synchronous write
* @j_history: Buffer storing the transactions statistics history
* @j_history_max: Maximum number of transactions in the statistics history
* @j_history_cur: Current number of transactions in the statistics history
* @j_history_lock: Protect the transactions statistics history
* @j_proc_entry: procfs entry for the jbd statistics directory
* @j_stats: Overall statistics
* @j_private: An opaque pointer to fs-private information.
*/
struct journal_s
{
/* General journaling state flags [j_state_lock] */
unsigned long j_flags;
/*
* Is there an outstanding uncleared error on the journal (from a prior
* abort)? [j_state_lock]
*/
int j_errno;
/* The superblock buffer */
struct buffer_head *j_sb_buffer;
journal_superblock_t *j_superblock;
/* Version of the superblock format */
int j_format_version;
/*
* Protect the various scalars in the journal
*/
spinlock_t j_state_lock;
/*
* Number of processes waiting to create a barrier lock [j_state_lock]
*/
int j_barrier_count;
/* The barrier lock itself */
struct mutex j_barrier;
/*
* Transactions: The current running transaction...
* [j_state_lock] [caller holding open handle]
*/
transaction_t *j_running_transaction;
/*
* the transaction we are pushing to disk
* [j_state_lock] [caller holding open handle]
*/
transaction_t *j_committing_transaction;
/*
* ... and a linked circular list of all transactions waiting for
* checkpointing. [j_list_lock]
*/
transaction_t *j_checkpoint_transactions;
/*
* Wait queue for waiting for a locked transaction to start committing,
* or for a barrier lock to be released
*/
wait_queue_head_t j_wait_transaction_locked;
/* Wait queue for waiting for checkpointing to complete */
wait_queue_head_t j_wait_logspace;
/* Wait queue for waiting for commit to complete */
wait_queue_head_t j_wait_done_commit;
/* Wait queue to trigger checkpointing */
wait_queue_head_t j_wait_checkpoint;
/* Wait queue to trigger commit */
wait_queue_head_t j_wait_commit;
/* Wait queue to wait for updates to complete */
wait_queue_head_t j_wait_updates;
/* Semaphore for locking against concurrent checkpoints */
struct mutex j_checkpoint_mutex;
/*
* Journal head: identifies the first unused block in the journal.
* [j_state_lock]
*/
unsigned long j_head;
/*
* Journal tail: identifies the oldest still-used block in the journal.
* [j_state_lock]
*/
unsigned long j_tail;
/*
* Journal free: how many free blocks are there in the journal?
* [j_state_lock]
*/
unsigned long j_free;
/*
* Journal start and end: the block numbers of the first usable block
* and one beyond the last usable block in the journal. [j_state_lock]
*/
unsigned long j_first;
unsigned long j_last;
/*
* Device, blocksize and starting block offset for the location where we
* store the journal.
*/
struct block_device *j_dev;
int j_blocksize;
unsigned long long j_blk_offset;
char j_devname[BDEVNAME_SIZE+24];
/*
* Device which holds the client fs. For internal journal this will be
* equal to j_dev.
*/
struct block_device *j_fs_dev;
/* Total maximum capacity of the journal region on disk. */
unsigned int j_maxlen;
/*
* Protects the buffer lists and internal buffer state.
*/
spinlock_t j_list_lock;
/* Optional inode where we store the journal. If present, all */
/* journal block numbers are mapped into this inode via */
/* bmap(). */
struct inode *j_inode;
/*
* Sequence number of the oldest transaction in the log [j_state_lock]
*/
tid_t j_tail_sequence;
/*
* Sequence number of the next transaction to grant [j_state_lock]
*/
tid_t j_transaction_sequence;
/*
* Sequence number of the most recently committed transaction
* [j_state_lock].
*/
tid_t j_commit_sequence;
/*
* Sequence number of the most recent transaction wanting commit
* [j_state_lock]
*/
tid_t j_commit_request;
/*
* Journal uuid: identifies the object (filesystem, LVM volume etc)
* backed by this journal. This will eventually be replaced by an array
* of uuids, allowing us to index multiple devices within a single
* journal and to perform atomic updates across them.
*/
__u8 j_uuid[16];
/* Pointer to the current commit thread for this journal */
struct task_struct *j_task;
/*
* Maximum number of metadata buffers to allow in a single compound
* commit transaction
*/
int j_max_transaction_buffers;
/*
* What is the maximum transaction lifetime before we begin a commit?
*/
unsigned long j_commit_interval;
/* The timer used to wakeup the commit thread: */
struct timer_list j_commit_timer;
/*
* The revoke table: maintains the list of revoked blocks in the
* current transaction. [j_revoke_lock]
*/
spinlock_t j_revoke_lock;
struct jbd2_revoke_table_s *j_revoke;
struct jbd2_revoke_table_s *j_revoke_table[2];
/*
* array of bhs for jbd2_journal_commit_transaction
*/
struct buffer_head **j_wbuf;
int j_wbufsize;
pid_t j_last_sync_writer;
/*
* Journal statistics
*/
struct transaction_stats_s *j_history;
int j_history_max;
int j_history_cur;
/*
* Protect the transactions statistics history
*/
spinlock_t j_history_lock;
struct proc_dir_entry *j_proc_entry;
struct transaction_stats_s j_stats;
/* Failed journal commit ID */
unsigned int j_failed_commit;
/*
* An opaque pointer to fs-private information. ext3 puts its
* superblock pointer here
*/
void *j_private;
};
/*
* Journal flag definitions
*/
#define JBD2_UNMOUNT 0x001 /* Journal thread is being destroyed */
#define JBD2_ABORT 0x002 /* Journaling has been aborted for errors. */
#define JBD2_ACK_ERR 0x004 /* The errno in the sb has been acked */
#define JBD2_FLUSHED 0x008 /* The journal superblock has been flushed */
#define JBD2_LOADED 0x010 /* The journal superblock has been loaded */
#define JBD2_BARRIER 0x020 /* Use IDE barriers */
/*
* Function declarations for the journaling transaction and buffer
* management
*/
/* Filing buffers */
extern void jbd2_journal_unfile_buffer(journal_t *, struct journal_head *);
extern void __jbd2_journal_unfile_buffer(struct journal_head *);
extern void __jbd2_journal_refile_buffer(struct journal_head *);
extern void jbd2_journal_refile_buffer(journal_t *, struct journal_head *);
extern void __jbd2_journal_file_buffer(struct journal_head *, transaction_t *, int);
extern void __journal_free_buffer(struct journal_head *bh);
extern void jbd2_journal_file_buffer(struct journal_head *, transaction_t *, int);
extern void __journal_clean_data_list(transaction_t *transaction);
/* Log buffer allocation */
extern struct journal_head * jbd2_journal_get_descriptor_buffer(journal_t *);
int jbd2_journal_next_log_block(journal_t *, unsigned long long *);
/* Commit management */
extern void jbd2_journal_commit_transaction(journal_t *);
/* Checkpoint list management */
int __jbd2_journal_clean_checkpoint_list(journal_t *journal);
int __jbd2_journal_remove_checkpoint(struct journal_head *);
void __jbd2_journal_insert_checkpoint(struct journal_head *, transaction_t *);
/* Buffer IO */
extern int
jbd2_journal_write_metadata_buffer(transaction_t *transaction,
struct journal_head *jh_in,
struct journal_head **jh_out,
unsigned long long blocknr);
/* Transaction locking */
extern void __wait_on_journal (journal_t *);
/*
* Journal locking.
*
* We need to lock the journal during transaction state changes so that nobody
* ever tries to take a handle on the running transaction while we are in the
* middle of moving it to the commit phase. j_state_lock does this.
*
* Note that the locking is completely interrupt unsafe. We never touch
* journal structures from interrupts.
*/
static inline handle_t *journal_current_handle(void)
{
return current->journal_info;
}
/* The journaling code user interface:
*
* Create and destroy handles
* Register buffer modifications against the current transaction.
*/
extern handle_t *jbd2_journal_start(journal_t *, int nblocks);
extern int jbd2_journal_restart (handle_t *, int nblocks);
extern int jbd2_journal_extend (handle_t *, int nblocks);
extern int jbd2_journal_get_write_access(handle_t *, struct buffer_head *);
extern int jbd2_journal_get_create_access (handle_t *, struct buffer_head *);
extern int jbd2_journal_get_undo_access(handle_t *, struct buffer_head *);
extern int jbd2_journal_dirty_metadata (handle_t *, struct buffer_head *);
extern void jbd2_journal_release_buffer (handle_t *, struct buffer_head *);
extern int jbd2_journal_forget (handle_t *, struct buffer_head *);
extern void journal_sync_buffer (struct buffer_head *);
extern void jbd2_journal_invalidatepage(journal_t *,
struct page *, unsigned long);
extern int jbd2_journal_try_to_free_buffers(journal_t *, struct page *, gfp_t);
extern int jbd2_journal_stop(handle_t *);
extern int jbd2_journal_flush (journal_t *);
extern void jbd2_journal_lock_updates (journal_t *);
extern void jbd2_journal_unlock_updates (journal_t *);
extern journal_t * jbd2_journal_init_dev(struct block_device *bdev,
struct block_device *fs_dev,
unsigned long long start, int len, int bsize);
extern journal_t * jbd2_journal_init_inode (struct inode *);
extern int jbd2_journal_update_format (journal_t *);
extern int jbd2_journal_check_used_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_check_available_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_set_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern void jbd2_journal_clear_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_create (journal_t *);
extern int jbd2_journal_load (journal_t *journal);
extern void jbd2_journal_destroy (journal_t *);
extern int jbd2_journal_recover (journal_t *journal);
extern int jbd2_journal_wipe (journal_t *, int);
extern int jbd2_journal_skip_recovery (journal_t *);
extern void jbd2_journal_update_superblock (journal_t *, int);
extern void __jbd2_journal_abort_hard (journal_t *);
extern void jbd2_journal_abort (journal_t *, int);
extern int jbd2_journal_errno (journal_t *);
extern void jbd2_journal_ack_err (journal_t *);
extern int jbd2_journal_clear_err (journal_t *);
extern int jbd2_journal_bmap(journal_t *, unsigned long, unsigned long long *);
extern int jbd2_journal_force_commit(journal_t *);
extern int jbd2_journal_file_inode(handle_t *handle, struct jbd2_inode *inode);
extern int jbd2_journal_begin_ordered_truncate(struct jbd2_inode *inode, loff_t new_size);
extern void jbd2_journal_init_jbd_inode(struct jbd2_inode *jinode, struct inode *inode);
extern void jbd2_journal_release_jbd_inode(journal_t *journal, struct jbd2_inode *jinode);
/*
* journal_head management
*/
struct journal_head *jbd2_journal_add_journal_head(struct buffer_head *bh);
struct journal_head *jbd2_journal_grab_journal_head(struct buffer_head *bh);
void jbd2_journal_remove_journal_head(struct buffer_head *bh);
void jbd2_journal_put_journal_head(struct journal_head *jh);
/*
* handle management
*/
extern struct kmem_cache *jbd2_handle_cache;
static inline handle_t *jbd2_alloc_handle(gfp_t gfp_flags)
{
return kmem_cache_alloc(jbd2_handle_cache, gfp_flags);
}
static inline void jbd2_free_handle(handle_t *handle)
{
kmem_cache_free(jbd2_handle_cache, handle);
}
/* Primary revoke support */
#define JOURNAL_REVOKE_DEFAULT_HASH 256
extern int jbd2_journal_init_revoke(journal_t *, int);
extern void jbd2_journal_destroy_revoke_caches(void);
extern int jbd2_journal_init_revoke_caches(void);
extern void jbd2_journal_destroy_revoke(journal_t *);
extern int jbd2_journal_revoke (handle_t *, unsigned long long, struct buffer_head *);
extern int jbd2_journal_cancel_revoke(handle_t *, struct journal_head *);
extern void jbd2_journal_write_revoke_records(journal_t *, transaction_t *);
/* Recovery revoke support */
extern int jbd2_journal_set_revoke(journal_t *, unsigned long long, tid_t);
extern int jbd2_journal_test_revoke(journal_t *, unsigned long long, tid_t);
extern void jbd2_journal_clear_revoke(journal_t *);
extern void jbd2_journal_switch_revoke_table(journal_t *journal);
/*
* The log thread user interface:
*
* Request space in the current transaction, and force transaction commit
* transitions on demand.
*/
int __jbd2_log_space_left(journal_t *); /* Called with journal locked */
int jbd2_log_start_commit(journal_t *journal, tid_t tid);
int __jbd2_log_start_commit(journal_t *journal, tid_t tid);
int jbd2_journal_start_commit(journal_t *journal, tid_t *tid);
int jbd2_journal_force_commit_nested(journal_t *journal);
int jbd2_log_wait_commit(journal_t *journal, tid_t tid);
int jbd2_log_do_checkpoint(journal_t *journal);
void __jbd2_log_wait_for_space(journal_t *journal);
extern void __jbd2_journal_drop_transaction(journal_t *, transaction_t *);
extern int jbd2_cleanup_journal_tail(journal_t *);
/* Debugging code only: */
#define jbd_ENOSYS() \
do { \
printk (KERN_ERR "JBD unimplemented function %s\n", __FUNCTION__); \
current->state = TASK_UNINTERRUPTIBLE; \
schedule(); \
} while (1)
/*
* is_journal_abort
*
* Simple test wrapper function to test the JBD2_ABORT state flag. This
* bit, when set, indicates that we have had a fatal error somewhere,
* either inside the journaling layer or indicated to us by the client
* (eg. ext3), and that we and should not commit any further
* transactions.
*/
static inline int is_journal_aborted(journal_t *journal)
{
return journal->j_flags & JBD2_ABORT;
}
static inline int is_handle_aborted(handle_t *handle)
{
if (handle->h_aborted)
return 1;
return is_journal_aborted(handle->h_transaction->t_journal);
}
static inline void jbd2_journal_abort_handle(handle_t *handle)
{
handle->h_aborted = 1;
}
#endif /* __KERNEL__ */
/* Comparison functions for transaction IDs: perform comparisons using
* modulo arithmetic so that they work over sequence number wraps. */
static inline int tid_gt(tid_t x, tid_t y)
{
int difference = (x - y);
return (difference > 0);
}
static inline int tid_geq(tid_t x, tid_t y)
{
int difference = (x - y);
return (difference >= 0);
}
extern int jbd2_journal_blocks_per_page(struct inode *inode);
extern size_t journal_tag_bytes(journal_t *journal);
/*
* Return the minimum number of blocks which must be free in the journal
* before a new transaction may be started. Must be called under j_state_lock.
*/
static inline int jbd_space_needed(journal_t *journal)
{
int nblocks = journal->j_max_transaction_buffers;
if (journal->j_committing_transaction)
nblocks += journal->j_committing_transaction->
t_outstanding_credits;
return nblocks;
}
/*
* Definitions which augment the buffer_head layer
*/
/* journaling buffer types */
#define BJ_None 0 /* Not journaled */
#define BJ_Metadata 1 /* Normal journaled metadata */
#define BJ_Forget 2 /* Buffer superseded by this transaction */
#define BJ_IO 3 /* Buffer is for temporary IO use */
#define BJ_Shadow 4 /* Buffer contents being shadowed to the log */
#define BJ_LogCtl 5 /* Buffer contains log descriptors */
#define BJ_Reserved 6 /* Buffer is reserved for access by journal */
#define BJ_Types 7
extern int jbd_blocks_per_page(struct inode *inode);
#ifdef __KERNEL__
#define buffer_trace_init(bh) do {} while (0)
#define print_buffer_fields(bh) do {} while (0)
#define print_buffer_trace(bh) do {} while (0)
#define BUFFER_TRACE(bh, info) do {} while (0)
#define BUFFER_TRACE2(bh, bh2, info) do {} while (0)
#define JBUFFER_TRACE(jh, info) do {} while (0)
#endif /* __KERNEL__ */
#endif /* _LINUX_JBD2_H */
| athurg/linux_kernel | include/linux/jbd2.h | C | gpl-2.0 | 37,930 |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Components.Aphid.Parser
{
public class AphidExpressionBinder : SerializationBinder
{
private const string _prefix = "System.Collections.Generic.List`1[[";
public override Type BindToType(string assemblyName, string typeName)
{
if (typeName.StartsWith(_prefix))
{
var name = typeName.Substring(_prefix.Length).RemoveAtIndexOf(',');
return typeof(List<>).MakeGenericType(Type.GetType(name));
}
return Type.GetType(typeName);
}
}
}
| John-Leitch/Aphid | Components.Aphid/Parser/Mutators/AphidExpressionBinder.cs | C# | gpl-2.0 | 677 |
/****************************************************************************
**
** Jreen
**
** Copyright © 2011 Aleksey Sidorov <[email protected]>
**
*****************************************************************************
**
** $JREEN_BEGIN_LICENSE$
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see http://www.gnu.org/licenses/.
** $JREEN_END_LICENSE$
**
****************************************************************************/
#ifndef BOOKMARK_H
#define BOOKMARK_H
#include "stanzaextension.h"
#include "jid.h"
namespace Jreen {
//XEP-0048
//http://xmpp.org/extensions/xep-0048.html
class BookmarkPrivate;
/*! For ease-of-use in a Jabber client, it is desirable to have a way to store shortcuts
* to various services and resources (such as conference rooms and web pages) as "bookmarks"
* that can be displayed in the user's client.
* Several Jabber clients have already agreed on and implemented a method to provide this service;
* that informal agreement is documented and expanded upon in this document
*/
class JREEN_EXPORT Bookmark : public Payload
{
Q_DECLARE_PRIVATE(Bookmark)
J_PAYLOAD(Jreen::Bookmark) //dummy
public:
class ConferencePrivate;
class JREEN_EXPORT Conference
{
public:
Conference();
Conference(const QString &name, const JID &jid, const QString &nick,
const QString &password = QString(), bool autojoin = false);
Conference(const Conference &o);
Conference &operator =(const Conference &o);
~Conference();
bool operator ==(const Conference &o);
bool operator !=(const Conference &o);
bool isValid() const;
void setJid(const JID &jid);
void setName(const QString &name);
/*! set the user's preferred roomnick for the chatroom
*/
void setNick(const QString &nick);
/*! set an unencrypted string for the password needed to enter a password-protected room.
* \note For security reasons, use of this element is NOT RECOMMENDED.
*/
void setPassword(const QString &password);
/*! set autojoin attribute
*/
void setAutojoin(bool set);
/*! returns friendly name of bookmark
*/
QString name() const;
/*! returns friendly name of bookmark
*/
QString nick() const;
/*! returns the user's preferred roomnick for the chatroom
*/
QString password() const;
/*! returns JabberID of the chat room.
*/
JID jid() const;
/*! returns autojoin attribute
*/
bool autojoin() const;
private:
QExplicitlySharedDataPointer<ConferencePrivate> d_ptr;
};
/*! Default constructor \param jid - The JabberID of the chat room
* \param name - A friendly name for the bookmark(optional)
* \param nick - The user's preferred roomnick for the chatroom(optional).
*/
Bookmark();
/*! set friendly name of bookmark
*/
~Bookmark();
QList<Conference> conferences() const;
void addConference(const Conference &conf);
void setConferences(const QList<Conference> &conferences);
private:
QScopedPointer<BookmarkPrivate> d_ptr;
};
} // namespace Jreen
#endif // BOOKMARK_H
| norrs/debian-libjreen | src/bookmark.h | C | gpl-2.0 | 3,569 |
# export AWS_ACCESS_KEY="Your-Access-Key"
# export AWS_SECRET_KEY="Your-Secret-Key"
today=`date +"%d-%m-%Y","%T"`
logfile="/awslog/automation-instances.log"
# Grab all Instance IDs for REBOOT action and export the IDs to a text file
sudo aws ec2 describe-instances --filters Name=tag:reboot-time,Values=18-00 Name=tag:bash-profile,Values=wd --query Reservations[*].Instances[*].[InstanceId] --output text > ~/tmp/reboot_wd_instance_info.txt 2>&1
# Take list of rebooting instances
for instance_id in $(cat ~/tmp/reboot_wd_instance_info.txt)
do
# Reboot instances
rebootresult=$(sudo aws ec2 reboot-instances --instance-ids $instance_id)
# Put info into log file
echo Atempt to reboot $today instances by AWS CLI with result $rebootresult --EMPTY FOR NO RESULT-- >> $logfile
done
| STARTSPACE/aws-ec2-start-stop-reboot-by-timetable | reboot/wd/reboot-wd-18.sh | Shell | gpl-2.0 | 785 |
<?php
global $VISUAL_COMPOSER_EXTENSIONS;
?>
<div id="ts-settings-files" class="tab-content">
<div class="ts-vcsc-section-main">
<div class="ts-vcsc-section-title ts-vcsc-section-show"><i class="dashicons-download"></i>External Files Settings</div>
<div class="ts-vcsc-section-content">
<div class="ts-vcsc-notice-field ts-vcsc-critical" style="margin-top: 10px; font-size: 13px; text-align: justify; font-weight: bold;">
Changes to the default settings done in this section can severely impact the overall functionality of this add-on or WordPress itself. Only make changes if you really know what you are doing and if the add-on is not
working correctly with the default settings!
</div>
<p>
<h4>Force Load of jQuery:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to force a load of jQuery and jQuery Migrate:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadjQuery == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadjQuery" class="toggle-check ts_vcsc_extend_settings_loadjQuery" name="ts_vcsc_extend_settings_loadjQuery" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadjQuery); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadjQuery == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadjQuery == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadjQuery">Force Load of jQuery</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load ONLY Lightbox Files on ALL Pages:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the lightbox files on ALL pages, even if no shortcode has been detected:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadLightbox == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadLightbox" class="toggle-check ts_vcsc_extend_settings_loadLightbox" name="ts_vcsc_extend_settings_loadLightbox" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadLightbox); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadLightbox == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadLightbox == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadLightbox">Load Lightbox On All Pages</label></span>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load ONLY Tooltip Files on ALL Pages:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the tooltip files on ALL pages, even if no shortcode has been detected:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadTooltip == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadTooltip" class="toggle-check ts_vcsc_extend_settings_loadTooltip" name="ts_vcsc_extend_settings_loadTooltip" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadTooltip); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadTooltip == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadTooltip == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadTooltip">Load Tooltips On All Pages</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load ONLY Icon Font Files on ALL Pages:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the active Icon Font files on ALL pages, even if no shortcode has been detected:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadFonts == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadFonts" class="toggle-check ts_vcsc_extend_settings_loadFonts" name="ts_vcsc_extend_settings_loadFonts" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadFonts); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadFonts == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadFonts == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadFonts">Load active Icon Fonts On All Pages</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load ALL Files on ALL Pages:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load ALL of the plugin files on ALL pages, even if no shortcode has been detected:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadForcable == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadForcable" class="toggle-check ts_vcsc_extend_settings_loadForcable" name="ts_vcsc_extend_settings_loadForcable" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadForcable); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadForcable == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadForcable == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadForcable">Load ALL Files On All Pages</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load External Files in HEAD:</h4>
<p style="font-size: 12px; text-align: justify;">Please define where you want to load the JS Files:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadHeader == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadHeader" class="toggle-check ts_vcsc_extend_settings_loadHeader" name="ts_vcsc_extend_settings_loadHeader" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadHeader); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadHeader == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadHeader == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadHeader">Load all Files in HEAD</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load Files via WordPress Standard:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the script files via "wp_enqueue_script" and "wp_enqueue_style":</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadEnqueue == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadEnqueue" class="toggle-check ts_vcsc_extend_settings_loadEnqueue" name="ts_vcsc_extend_settings_loadEnqueue" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadEnqueue); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadEnqueue == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadEnqueue == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadEnqueue">Load Files with Standard Method</label>
</p>
<div class="ts-vcsc-notice-field ts-vcsc-warning" style="margin-top: 30px; margin-bottom: 30px; font-size: 13px; text-align: justify;">
This plugin will load some external CSS and JS files in order to make the content elements work on the front end. Your theme or another plugin might already load the same file, which in some cases
can cause problems. Use this page to enable/disable the files this plugin should be allowed to load on the front end.
</div>
<p>
<h4>Load Modernizr File:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the Modernizr file to ensure CSS3 compatibility for most browsers:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadModernizr == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadModernizr" class="toggle-check ts_vcsc_extend_settings_loadModernizr" name="ts_vcsc_extend_settings_loadModernizr" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadModernizr); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadModernizr == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadModernizr == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadModernizr">Load Modernizr</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load Waypoints File:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the Waypoints File for Viewport Animations:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadWaypoints == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadWaypoints" class="toggle-check ts_vcsc_extend_settings_loadWaypoints" name="ts_vcsc_extend_settings_loadWaypoints" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadWaypoints); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadWaypoints == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadWaypoints == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadWaypoints">Load WayPoints</label>
</p>
<hr class='style-six' style='margin-top: 20px;'>
<p>
<h4>Load CountTo File:</h4>
<p style="font-size: 12px; text-align: justify;">Please define if you want to load the CountTo File for the Icon Counter:</p>
<div class="ts-switch-button ts-composer-switch" data-value="<?php echo ($ts_vcsc_extend_settings_loadCountTo == 1 ? 'true' : 'false'); ?>" data-width="80" data-style="compact" data-on="Yes" data-off="No" style="float: left; margin-right: 10px;">
<input type="checkbox" style="display: none; " id="ts_vcsc_extend_settings_loadCountTo" class="toggle-check ts_vcsc_extend_settings_loadCountTo" name="ts_vcsc_extend_settings_loadCountTo" value="1" <?php echo checked('1', $ts_vcsc_extend_settings_loadCountTo); ?>/>
<div class="toggle toggle-light" style="width: 80px; height: 20px;">
<div class="toggle-slide">
<div class="toggle-inner">
<div class="toggle-on <?php echo ($ts_vcsc_extend_settings_loadCountTo == 1 ? 'active' : ''); ?>">Yes</div>
<div class="toggle-blob"></div>
<div class="toggle-off <?php echo ($ts_vcsc_extend_settings_loadCountTo == 0 ? 'active' : ''); ?>">No</div>
</div>
</div>
</div>
</div>
<label class="labelToggleBox" for="ts_vcsc_extend_settings_loadCountTo">Load CountTo</label>
</p>
</div>
</div>
</div> | baochung26/happy-c | wp-content/plugins/ts-visual-composer-extend/assets/ts_vcsc_settings_external.php | PHP | gpl-2.0 | 14,684 |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2019 MaNGOS project <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#ifndef MANGOS_GRIDNOTIFIERS_H
#define MANGOS_GRIDNOTIFIERS_H
#include "ObjectGridLoader.h"
#include "UpdateData.h"
#include <iostream>
#include "Corpse.h"
#include "Object.h"
#include "DynamicObject.h"
#include "GameObject.h"
#include "Player.h"
#include "Unit.h"
namespace MaNGOS
{
struct VisibleNotifier
{
Camera& i_camera;
UpdateData i_data;
GuidSet i_clientGUIDs;
std::set<WorldObject*> i_visibleNow;
explicit VisibleNotifier(Camera& c) : i_camera(c), i_clientGUIDs(c.GetOwner()->m_clientGUIDs) {}
template<class T> void Visit(GridRefManager<T>& m);
void Visit(CameraMapType& /*m*/) {}
void Notify(void);
};
struct VisibleChangesNotifier
{
WorldObject& i_object;
explicit VisibleChangesNotifier(WorldObject& object) : i_object(object) {}
template<class T> void Visit(GridRefManager<T>&) {}
void Visit(CameraMapType&);
};
struct MessageDeliverer
{
Player const& i_player;
WorldPacket* i_message;
bool i_toSelf;
MessageDeliverer(Player const& pl, WorldPacket* msg, bool to_self) : i_player(pl), i_message(msg), i_toSelf(to_self) {}
void Visit(CameraMapType& m);
template<class SKIP> void Visit(GridRefManager<SKIP>&) {}
};
struct MessageDelivererExcept
{
uint32 i_phaseMask;
WorldPacket* i_message;
Player const* i_skipped_receiver;
MessageDelivererExcept(WorldObject const* obj, WorldPacket* msg, Player const* skipped)
: i_phaseMask(obj->GetPhaseMask()), i_message(msg), i_skipped_receiver(skipped) {}
void Visit(CameraMapType& m);
template<class SKIP> void Visit(GridRefManager<SKIP>&) {}
};
struct ObjectMessageDeliverer
{
uint32 i_phaseMask;
WorldPacket* i_message;
explicit ObjectMessageDeliverer(WorldObject const& obj, WorldPacket* msg)
: i_phaseMask(obj.GetPhaseMask()), i_message(msg) {}
void Visit(CameraMapType& m);
template<class SKIP> void Visit(GridRefManager<SKIP>&) {}
};
struct MessageDistDeliverer
{
Player const& i_player;
WorldPacket* i_message;
bool i_toSelf;
bool i_ownTeamOnly;
float i_dist;
MessageDistDeliverer(Player const& pl, WorldPacket* msg, float dist, bool to_self, bool ownTeamOnly)
: i_player(pl), i_message(msg), i_toSelf(to_self), i_ownTeamOnly(ownTeamOnly), i_dist(dist) {}
void Visit(CameraMapType& m);
template<class SKIP> void Visit(GridRefManager<SKIP>&) {}
};
struct ObjectMessageDistDeliverer
{
WorldObject const& i_object;
WorldPacket* i_message;
float i_dist;
ObjectMessageDistDeliverer(WorldObject const& obj, WorldPacket* msg, float dist) : i_object(obj), i_message(msg), i_dist(dist) {}
void Visit(CameraMapType& m);
template<class SKIP> void Visit(GridRefManager<SKIP>&) {}
};
struct ObjectUpdater
{
uint32 i_timeDiff;
explicit ObjectUpdater(const uint32& diff) : i_timeDiff(diff) {}
template<class T> void Visit(GridRefManager<T>& m);
void Visit(PlayerMapType&) {}
void Visit(CorpseMapType&) {}
void Visit(CameraMapType&) {}
void Visit(CreatureMapType&);
};
struct PlayerRelocationNotifier
{
Player& i_player;
PlayerRelocationNotifier(Player& pl) : i_player(pl) {}
template<class T> void Visit(GridRefManager<T>&) {}
void Visit(CreatureMapType&);
};
struct CreatureRelocationNotifier
{
Creature& i_creature;
CreatureRelocationNotifier(Creature& c) : i_creature(c) {}
template<class T> void Visit(GridRefManager<T>&) {}
#ifdef WIN32
template<> void Visit(PlayerMapType&);
#endif
};
struct DynamicObjectUpdater
{
DynamicObject& i_dynobject;
Unit* i_check;
bool i_positive;
DynamicObjectUpdater(DynamicObject& dynobject, Unit* caster, bool positive) : i_dynobject(dynobject), i_positive(positive)
{
i_check = caster;
Unit* owner = i_check->GetOwner();
if (owner)
{ i_check = owner; }
}
template<class T> inline void Visit(GridRefManager<T>&) {}
#ifdef WIN32
template<> inline void Visit<Player>(PlayerMapType&);
template<> inline void Visit<Creature>(CreatureMapType&);
#endif
void VisitHelper(Unit* target);
};
// SEARCHERS & LIST SEARCHERS & WORKERS
/* Model Searcher class:
template<class Check>
struct SomeSearcher
{
ResultType& i_result;
Check & i_check;
SomeSearcher(ResultType& result, Check & check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_result(result), i_check(check) {}
void Visit(CreatureMapType &m);
{
..some code fast return if result found
for(CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
{
if (!itr->getSource()->InSamePhase(i_phaseMask))
continue;
if (!i_check(itr->getSource()))
continue;
..some code for update result and possible stop search
}
}
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
};
*/
// WorldObject searchers & workers
template<class Check>
struct WorldObjectSearcher
{
uint32 i_phaseMask;
WorldObject*& i_object;
Check& i_check;
WorldObjectSearcher(WorldObject*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(GameObjectMapType& m);
void Visit(PlayerMapType& m);
void Visit(CreatureMapType& m);
void Visit(CorpseMapType& m);
void Visit(DynamicObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Check>
struct WorldObjectLastSearcher
{
uint32 i_phaseMask;
WorldObject*& i_object;
Check& i_check;
WorldObjectLastSearcher(WorldObject* & result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(PlayerMapType& m);
void Visit(CreatureMapType& m);
void Visit(CorpseMapType& m);
void Visit(GameObjectMapType& m);
void Visit(DynamicObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Check>
struct WorldObjectListSearcher
{
uint32 i_phaseMask;
std::list<WorldObject*>& i_objects;
Check& i_check;
WorldObjectListSearcher(std::list<WorldObject*>& objects, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_objects(objects), i_check(check) {}
void Visit(PlayerMapType& m);
void Visit(CreatureMapType& m);
void Visit(CorpseMapType& m);
void Visit(GameObjectMapType& m);
void Visit(DynamicObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Do>
struct WorldObjectWorker
{
uint32 i_phaseMask;
Do const& i_do;
WorldObjectWorker(WorldObject const* searcher, Do const& _do)
: i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
void Visit(GameObjectMapType& m)
{
for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
void Visit(PlayerMapType& m)
{
for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
void Visit(CreatureMapType& m)
{
for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
void Visit(CorpseMapType& m)
{
for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
void Visit(DynamicObjectMapType& m)
{
for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Gameobject searchers
template<class Check>
struct GameObjectSearcher
{
uint32 i_phaseMask;
GameObject*& i_object;
Check& i_check;
GameObjectSearcher(GameObject*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(GameObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Last accepted by Check GO if any (Check can change requirements at each call)
template<class Check>
struct GameObjectLastSearcher
{
uint32 i_phaseMask;
GameObject*& i_object;
Check& i_check;
GameObjectLastSearcher(GameObject*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(GameObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Check>
struct GameObjectListSearcher
{
uint32 i_phaseMask;
std::list<GameObject*>& i_objects;
Check& i_check;
GameObjectListSearcher(std::list<GameObject*>& objects, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_objects(objects), i_check(check) {}
void Visit(GameObjectMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Unit searchers
// First accepted by Check Unit if any
template<class Check>
struct UnitSearcher
{
uint32 i_phaseMask;
Unit*& i_object;
Check& i_check;
UnitSearcher(Unit*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(CreatureMapType& m);
void Visit(PlayerMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Last accepted by Check Unit if any (Check can change requirements at each call)
template<class Check>
struct UnitLastSearcher
{
uint32 i_phaseMask;
Unit*& i_object;
Check& i_check;
UnitLastSearcher(Unit*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(CreatureMapType& m);
void Visit(PlayerMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// All accepted by Check units if any
template<class Check>
struct UnitListSearcher
{
uint32 i_phaseMask;
std::list<Unit*>& i_objects;
Check& i_check;
UnitListSearcher(std::list<Unit*>& objects, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_objects(objects), i_check(check) {}
void Visit(PlayerMapType& m);
void Visit(CreatureMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Creature searchers
template<class Check>
struct CreatureSearcher
{
uint32 i_phaseMask;
Creature*& i_object;
Check& i_check;
CreatureSearcher(Creature*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(CreatureMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Last accepted by Check Creature if any (Check can change requirements at each call)
template<class Check>
struct CreatureLastSearcher
{
uint32 i_phaseMask;
Creature*& i_object;
Check& i_check;
CreatureLastSearcher(Creature*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(CreatureMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Check>
struct CreatureListSearcher
{
uint32 i_phaseMask;
std::list<Creature*>& i_objects;
Check& i_check;
CreatureListSearcher(std::list<Creature*>& objects, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_objects(objects), i_check(check) {}
void Visit(CreatureMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Do>
struct CreatureWorker
{
uint32 i_phaseMask;
Do& i_do;
CreatureWorker(WorldObject const* searcher, Do& _do)
: i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
void Visit(CreatureMapType& m)
{
for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// Player searchers
template<class Check>
struct PlayerSearcher
{
uint32 i_phaseMask;
Player*& i_object;
Check& i_check;
PlayerSearcher(Player*& result, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_object(result), i_check(check) {}
void Visit(PlayerMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Check>
struct PlayerListSearcher
{
uint32 i_phaseMask;
std::list<Player*>& i_objects;
Check& i_check;
PlayerListSearcher(std::list<Player*>& objects, Check& check)
: i_phaseMask(check.GetFocusObject().GetPhaseMask()), i_objects(objects), i_check(check) {}
void Visit(PlayerMapType& m);
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Do>
struct PlayerWorker
{
uint32 i_phaseMask;
Do& i_do;
PlayerWorker(WorldObject const* searcher, Do& _do)
: i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
void Visit(PlayerMapType& m)
{
for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->InSamePhase(i_phaseMask))
i_do(itr->getSource());
}
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
template<class Do>
struct CameraDistWorker
{
WorldObject const* i_searcher;
float i_dist;
Do& i_do;
CameraDistWorker(WorldObject const* searcher, float _dist, Do& _do)
: i_searcher(searcher), i_dist(_dist), i_do(_do) {}
void Visit(CameraMapType& m)
{
for (CameraMapType::iterator itr = m.begin(); itr != m.end(); ++itr)
if (itr->getSource()->GetBody()->InSamePhase(i_searcher) && itr->getSource()->GetBody()->IsWithinDist(i_searcher, i_dist))
i_do(itr->getSource()->GetOwner());
}
template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED>&) {}
};
// CHECKS && DO classes
/* Model Check class:
class SomeCheck
{
public:
SomeCheck(SomeObjecType const* fobj, ..some other args) : i_fobj(fobj), ...other inits {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Creature* u) and for other intresting typs (Player/GameObject/Camera
{
return ..(code return true if Object fit to requirenment);
}
template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
private:
SomeObjecType const* i_fobj; // Focus object used for check distance from, phase, so place in world
..other values need for check
};
*/
// WorldObject check classes
class RaiseDeadObjectCheck
{
public:
RaiseDeadObjectCheck(Player const* fobj, float range) : i_fobj(fobj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Creature* u)
{
if (i_fobj->isHonorOrXPTarget(u) ||
u->getDeathState() != CORPSE || u->IsDeadByDefault() || u->IsTaxiFlying() ||
(u->GetCreatureTypeMask() & (1 << (CREATURE_TYPE_HUMANOID - 1))) == 0 ||
(u->GetDisplayId() != u->GetNativeDisplayId()))
return false;
return i_fobj->IsWithinDistInMap(u, i_range);
}
template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
private:
Player const* i_fobj;
float i_range;
};
class ExplodeCorpseObjectCheck
{
public:
ExplodeCorpseObjectCheck(WorldObject const* fobj, float range) : i_fobj(fobj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Player* u)
{
if (u->getDeathState() != CORPSE || u->IsTaxiFlying() ||
u->HasAuraType(SPELL_AURA_GHOST) || (u->GetDisplayId() != u->GetNativeDisplayId()))
return false;
return i_fobj->IsWithinDistInMap(u, i_range);
}
bool operator()(Creature* u)
{
if (u->getDeathState() != CORPSE || u->IsTaxiFlying() || u->IsDeadByDefault() ||
(u->GetDisplayId() != u->GetNativeDisplayId()) ||
(u->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL) != 0)
return false;
return i_fobj->IsWithinDistInMap(u, i_range);
}
template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
private:
WorldObject const* i_fobj;
float i_range;
};
class CannibalizeObjectCheck
{
public:
CannibalizeObjectCheck(WorldObject const* fobj, float range) : i_fobj(fobj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Player* u)
{
if (i_fobj->IsFriendlyTo(u) || u->IsAlive() || u->IsTaxiFlying())
{ return false; }
return i_fobj->IsWithinDistInMap(u, i_range);
}
bool operator()(Corpse* u);
bool operator()(Creature* u)
{
if (i_fobj->IsFriendlyTo(u) || u->IsAlive() || u->IsTaxiFlying() ||
(u->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0)
{ return false; }
return i_fobj->IsWithinDistInMap(u, i_range);
}
template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
private:
WorldObject const* i_fobj;
float i_range;
};
// WorldObject do classes
class RespawnDo
{
public:
RespawnDo() {}
void operator()(Creature* u) const;
void operator()(GameObject* u) const;
void operator()(WorldObject*) const {}
void operator()(Corpse*) const {}
};
// GameObject checks
class GameObjectFocusCheck
{
public:
GameObjectFocusCheck(Unit const* unit, uint32 focusId) : i_unit(unit), i_focusId(focusId) {}
WorldObject const& GetFocusObject() const { return *i_unit; }
bool operator()(GameObject* go) const
{
if (go->GetGOInfo()->type != GAMEOBJECT_TYPE_SPELL_FOCUS)
{ return false; }
if (go->GetGOInfo()->spellFocus.focusId != i_focusId)
{ return false; }
float dist = (float)go->GetGOInfo()->spellFocus.dist;
return go->IsWithinDistInMap(i_unit, dist);
}
private:
Unit const* i_unit;
uint32 i_focusId;
};
// Find the nearest Fishing hole and return true only if source object is in range of hole
class NearestGameObjectFishingHoleCheck
{
public:
NearestGameObjectFishingHoleCheck(WorldObject const& obj, float range) : i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(GameObject* go)
{
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_FISHINGHOLE && go->isSpawned() && i_obj.IsWithinDistInMap(go, i_range) && i_obj.IsWithinDistInMap(go, (float)go->GetGOInfo()->fishinghole.radius))
{
i_range = i_obj.GetDistance(go);
return true;
}
return false;
}
float GetLastRange() const { return i_range; }
private:
WorldObject const& i_obj;
float i_range;
// prevent clone
NearestGameObjectFishingHoleCheck(NearestGameObjectFishingHoleCheck const&);
};
// Success at unit in range, range update for next check (this can be use with GameobjectLastSearcher to find nearest GO)
class NearestGameObjectEntryInObjectRangeCheck
{
public:
NearestGameObjectEntryInObjectRangeCheck(WorldObject const& obj, uint32 entry, float range) : i_obj(obj), i_entry(entry), i_range(range) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(GameObject* go)
{
if (go->GetEntry() == i_entry && i_obj.IsWithinDistInMap(go, i_range))
{
i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check
return true;
}
return false;
}
float GetLastRange() const { return i_range; }
private:
WorldObject const& i_obj;
uint32 i_entry;
float i_range;
// prevent clone this object
NearestGameObjectEntryInObjectRangeCheck(NearestGameObjectEntryInObjectRangeCheck const&);
};
// Success at gameobject in range of xyz, range update for next check (this can be use with GameobjectLastSearcher to find nearest GO)
class NearestGameObjectEntryInPosRangeCheck
{
public:
NearestGameObjectEntryInPosRangeCheck(WorldObject const& obj, uint32 entry, float x, float y, float z, float range)
: i_obj(obj), i_entry(entry), i_x(x), i_y(y), i_z(z), i_range(range) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(GameObject* go)
{
if (go->GetEntry() == i_entry && go->IsWithinDist3d(i_x, i_y, i_z, i_range))
{
// use found GO range as new range limit for next check
i_range = go->GetDistance(i_x, i_y, i_z);
return true;
}
return false;
}
float GetLastRange() const { return i_range; }
private:
WorldObject const& i_obj;
uint32 i_entry;
float i_x, i_y, i_z;
float i_range;
// prevent clone this object
NearestGameObjectEntryInPosRangeCheck(NearestGameObjectEntryInPosRangeCheck const&);
};
// Success at gameobject with entry in range of provided xyz
class GameObjectEntryInPosRangeCheck
{
public:
GameObjectEntryInPosRangeCheck(WorldObject const& obj, uint32 entry, float x, float y, float z, float range)
: i_obj(obj), i_entry(entry), i_x(x), i_y(y), i_z(z), i_range(range) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(GameObject* go)
{
if (go->GetEntry() == i_entry && go->IsWithinDist3d(i_x, i_y, i_z, i_range))
{ return true; }
return false;
}
float GetLastRange() const { return i_range; }
private:
WorldObject const& i_obj;
uint32 i_entry;
float i_x, i_y, i_z;
float i_range;
// prevent clone this object
GameObjectEntryInPosRangeCheck(GameObjectEntryInPosRangeCheck const&);
};
// Success at gameobject of type in range of provided xyz
class GameObjectTypeInPosRangeCheck
{
public:
GameObjectTypeInPosRangeCheck(Unit const& obj, GameobjectTypes type, float x, float y, float z, float range, bool onlyHostile, bool onlyFriendly)
: i_obj(obj), i_type(type), i_x(x), i_y(y), i_z(z), i_range(range), i_onlyHostile(onlyHostile), i_onlyFriendly(onlyFriendly) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(GameObject* go)
{
if (go->GetGoType() == i_type
&& (!i_onlyHostile || go->IsHostileTo(&i_obj)) && (!i_onlyFriendly || go->IsFriendlyTo(&i_obj))
&& go->IsWithinDist3d(i_x, i_y, i_z, i_range))
return true;
return false;
}
float GetLastRange() const { return i_range; }
private:
Unit const& i_obj;
GameobjectTypes i_type;
float i_x, i_y, i_z;
float i_range;
bool i_onlyHostile, i_onlyFriendly;
// prevent clone this object
GameObjectTypeInPosRangeCheck(GameObjectTypeInPosRangeCheck const&);
};
// Unit checks
class MostHPMissingInRangeCheck
{
public:
MostHPMissingInRangeCheck(Unit const* obj, float range, uint32 hp) : i_obj(obj), i_range(range), i_hp(hp) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && u->GetMaxHealth() - u->GetHealth() > i_hp)
{
i_hp = u->GetMaxHealth() - u->GetHealth();
return true;
}
return false;
}
private:
Unit const* i_obj;
float i_range;
uint32 i_hp;
};
class FriendlyCCedInRangeCheck
{
public:
FriendlyCCedInRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) &&
(u->IsCharmed() || u->IsFrozen() || u->hasUnitState(UNIT_STAT_CAN_NOT_REACT)))
{
return true;
}
return false;
}
private:
WorldObject const* i_obj;
float i_range;
};
class FriendlyMissingBuffInRangeCheck
{
public:
FriendlyMissingBuffInRangeCheck(WorldObject const* obj, float range, uint32 spellid) : i_obj(obj), i_range(range), i_spell(spellid) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) &&
!(u->HasAura(i_spell, EFFECT_INDEX_0) || u->HasAura(i_spell, EFFECT_INDEX_1) || u->HasAura(i_spell, EFFECT_INDEX_2)))
{
return true;
}
return false;
}
private:
WorldObject const* i_obj;
float i_range;
uint32 i_spell;
};
class AnyUnfriendlyUnitInObjectRangeCheck
{
public:
AnyUnfriendlyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range)
{
i_controlledByPlayer = obj->IsControlledByPlayer();
}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && (i_controlledByPlayer ? !i_obj->IsFriendlyTo(u) : i_obj->IsHostileTo(u))
&& i_obj->IsWithinDistInMap(u, i_range))
{ return true; }
else
{ return false; }
}
private:
WorldObject const* i_obj;
bool i_controlledByPlayer;
float i_range;
};
class AnyUnfriendlyVisibleUnitInObjectRangeCheck
{
public:
AnyUnfriendlyVisibleUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range)
: i_obj(obj), i_funit(funit), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
return u->IsAlive()
&& i_obj->IsWithinDistInMap(u, i_range)
&& !i_funit->IsFriendlyTo(u)
&& u->IsVisibleForOrDetect(i_funit, i_funit, false);
}
private:
WorldObject const* i_obj;
Unit const* i_funit;
float i_range;
};
class AnyFriendlyUnitInObjectRangeCheck
{
public:
AnyFriendlyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_obj->IsFriendlyTo(u))
{ return true; }
else
{ return false; }
}
private:
WorldObject const* i_obj;
float i_range;
};
class AnyUnitInObjectRangeCheck
{
public:
AnyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range))
{ return true; }
return false;
}
private:
WorldObject const* i_obj;
float i_range;
};
// Success at unit in range, range update for next check (this can be use with UnitLastSearcher to find nearest unit)
class NearestAttackableUnitInObjectRangeCheck
{
public:
NearestAttackableUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
if (u->IsTargetableForAttack() && i_obj->IsWithinDistInMap(u, i_range) &&
!i_funit->IsFriendlyTo(u) && u->IsVisibleForOrDetect(i_funit, i_funit, false))
{
i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check
return true;
}
return false;
}
private:
WorldObject const* i_obj;
Unit const* i_funit;
float i_range;
// prevent clone this object
NearestAttackableUnitInObjectRangeCheck(NearestAttackableUnitInObjectRangeCheck const&);
};
class AnyAoEVisibleTargetUnitInObjectRangeCheck
{
public:
AnyAoEVisibleTargetUnitInObjectRangeCheck(WorldObject const* obj, WorldObject const* originalCaster, float range)
: i_obj(obj), i_originalCaster(originalCaster), i_range(range)
{
i_targetForUnit = i_originalCaster->isType(TYPEMASK_UNIT);
i_targetForPlayer = (i_originalCaster->GetTypeId() == TYPEID_PLAYER);
}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
// Check contains checks for: live, non-selectable, non-attackable flags, flight check and GM check, ignore totems
if (!u->IsTargetableForAttack())
{ return false; }
// ignore totems as AoE targets
if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->IsTotem())
{ return false; }
// check visibility only for unit-like original casters
if (i_targetForUnit && !u->IsVisibleForOrDetect((Unit const*)i_originalCaster, i_originalCaster, false))
{ return false; }
if ((i_targetForPlayer ? !i_originalCaster->IsFriendlyTo(u) : i_originalCaster->IsHostileTo(u)) && i_obj->IsWithinDistInMap(u, i_range))
{ return true; }
return false;
}
private:
WorldObject const* i_obj;
WorldObject const* i_originalCaster;
float i_range;
bool i_targetForUnit;
bool i_targetForPlayer;
};
class AnyAoETargetUnitInObjectRangeCheck
{
public:
AnyAoETargetUnitInObjectRangeCheck(WorldObject const* obj, float range)
: i_obj(obj), i_range(range)
{
i_targetForPlayer = i_obj->IsControlledByPlayer();
}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Unit* u)
{
// Check contains checks for: live, non-selectable, non-attackable flags, flight check and GM check, ignore totems
if (!u->IsTargetableForAttack())
{ return false; }
if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->IsTotem())
{ return false; }
if ((i_targetForPlayer ? !i_obj->IsFriendlyTo(u) : i_obj->IsHostileTo(u)) && i_obj->IsWithinDistInMap(u, i_range))
{ return true; }
return false;
}
private:
WorldObject const* i_obj;
float i_range;
bool i_targetForPlayer;
};
// do attack at call of help to friendly crearture
class CallOfHelpCreatureInRangeDo
{
public:
CallOfHelpCreatureInRangeDo(Unit* funit, Unit* enemy, float range)
: i_funit(funit), i_enemy(enemy), i_range(range)
{}
void operator()(Creature* u);
private:
Unit* const i_funit;
Unit* const i_enemy;
float i_range;
};
class AnyDeadUnitCheck
{
public:
explicit AnyDeadUnitCheck(WorldObject const* fobj) : i_fobj(fobj) {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Unit* u) { return !u->IsAlive(); }
private:
WorldObject const* i_fobj;
};
class AnyStealthedCheck
{
public:
explicit AnyStealthedCheck(WorldObject const* fobj) : i_fobj(fobj) {}
WorldObject const& GetFocusObject() const { return *i_fobj; }
bool operator()(Unit* u) { return u->GetVisibility() == VISIBILITY_GROUP_STEALTH; }
private:
WorldObject const* i_fobj;
};
// Creature checks
class InAttackDistanceFromAnyHostileCreatureCheck
{
public:
explicit InAttackDistanceFromAnyHostileCreatureCheck(Unit* funit) : i_funit(funit) {}
WorldObject const& GetFocusObject() const { return *i_funit; }
bool operator()(Creature* u)
{
if (u->IsAlive() && u->IsHostileTo(i_funit) && i_funit->IsWithinDistInMap(u, u->GetAttackDistance(i_funit)))
{ return true; }
return false;
}
private:
Unit* const i_funit;
};
class AnyAssistCreatureInRangeCheck
{
public:
AnyAssistCreatureInRangeCheck(Unit* funit, Unit* enemy, float range)
: i_funit(funit), i_enemy(enemy), i_range(range)
{
}
WorldObject const& GetFocusObject() const { return *i_funit; }
bool operator()(Creature* u);
private:
Unit* const i_funit;
Unit* const i_enemy;
float i_range;
};
class NearestAssistCreatureInCreatureRangeCheck
{
public:
NearestAssistCreatureInCreatureRangeCheck(Creature* obj, Unit* enemy, float range)
: i_obj(obj), i_enemy(enemy), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Creature* u)
{
if (u == i_obj)
{ return false; }
if (!u->CanAssistTo(i_obj, i_enemy))
{ return false; }
if (!i_obj->IsWithinDistInMap(u, i_range))
{ return false; }
if (!i_obj->IsWithinLOSInMap(u))
{ return false; }
i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check
return true;
}
float GetLastRange() const { return i_range; }
private:
Creature* const i_obj;
Unit* const i_enemy;
float i_range;
// prevent clone this object
NearestAssistCreatureInCreatureRangeCheck(NearestAssistCreatureInCreatureRangeCheck const&);
};
// Success at unit in range, range update for next check (this can be use with CreatureLastSearcher to find nearest creature)
class NearestCreatureEntryWithLiveStateInObjectRangeCheck
{
public:
NearestCreatureEntryWithLiveStateInObjectRangeCheck(WorldObject const& obj, uint32 entry, bool onlyAlive, bool onlyDead, float range, bool excludeSelf = false)
: i_obj(obj), i_entry(entry), i_onlyAlive(onlyAlive), i_onlyDead(onlyDead), i_excludeSelf(excludeSelf), i_range(range) {}
WorldObject const& GetFocusObject() const { return i_obj; }
bool operator()(Creature* u)
{
if (u->GetEntry() == i_entry && ((i_onlyAlive && u->IsAlive()) || (i_onlyDead && u->IsCorpse()) || (!i_onlyAlive && !i_onlyDead))
&& (!i_excludeSelf || &i_obj != u) && i_obj.IsWithinDistInMap(u, i_range))
{
i_range = i_obj.GetDistance(u); // use found unit range as new range limit for next check
return true;
}
return false;
}
float GetLastRange() const { return i_range; }
private:
WorldObject const& i_obj;
uint32 i_entry;
bool i_onlyAlive;
bool i_onlyDead;
bool i_excludeSelf;
float i_range;
// prevent clone this object
NearestCreatureEntryWithLiveStateInObjectRangeCheck(NearestCreatureEntryWithLiveStateInObjectRangeCheck const&);
};
class AllCreaturesOfEntryInRangeCheck
{
public:
AllCreaturesOfEntryInRangeCheck(const WorldObject* pObject, uint32 uiEntry, float fMaxRange) : m_pObject(pObject), m_uiEntry(uiEntry), m_fRange(fMaxRange) {}
WorldObject const& GetFocusObject() const { return *m_pObject; }
bool operator()(Unit* pUnit)
{
if (pUnit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(pUnit, m_fRange, false))
{ return true; }
return false;
}
private:
const WorldObject* m_pObject;
uint32 m_uiEntry;
float m_fRange;
// prevent clone this object
AllCreaturesOfEntryInRangeCheck(AllCreaturesOfEntryInRangeCheck const&);
};
// Player checks and do
class AnyPlayerInObjectRangeCheck
{
public:
AnyPlayerInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Player* u)
{
if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range))
{ return true; }
return false;
}
private:
WorldObject const* i_obj;
float i_range;
};
class AnyPlayerInObjectRangeWithAuraCheck
{
public:
AnyPlayerInObjectRangeWithAuraCheck(WorldObject const* obj, float range, uint32 spellId)
: i_obj(obj), i_range(range), i_spellId(spellId) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Player* u)
{
return u->IsAlive()
&& i_obj->IsWithinDistInMap(u, i_range)
&& u->HasAura(i_spellId);
}
private:
WorldObject const* i_obj;
float i_range;
uint32 i_spellId;
};
class AnyPlayerInCapturePointRange
{
public:
AnyPlayerInCapturePointRange(WorldObject const* obj, float range)
: i_obj(obj), i_range(range) {}
WorldObject const& GetFocusObject() const { return *i_obj; }
bool operator()(Player* u)
{
return u->CanUseCapturePoint() &&
i_obj->IsWithinDistInMap(u, i_range);
}
private:
WorldObject const* i_obj;
float i_range;
};
// Prepare using Builder localized packets with caching and send to player
template<class Builder>
class LocalizedPacketDo
{
public:
explicit LocalizedPacketDo(Builder& builder) : i_builder(builder) {}
~LocalizedPacketDo()
{
for (size_t i = 0; i < i_data_cache.size(); ++i)
{ delete i_data_cache[i]; }
}
void operator()(Player* p);
private:
Builder& i_builder;
std::vector<WorldPacket*> i_data_cache; // 0 = default, i => i-1 locale index
};
// Prepare using Builder localized packets with caching and send to player
template<class Builder>
class LocalizedPacketListDo
{
public:
typedef std::vector<WorldPacket*> WorldPacketList;
explicit LocalizedPacketListDo(Builder& builder) : i_builder(builder) {}
~LocalizedPacketListDo()
{
for (size_t i = 0; i < i_data_cache.size(); ++i)
for (size_t j = 0; j < i_data_cache[i].size(); ++j)
{ delete i_data_cache[i][j]; }
}
void operator()(Player* p);
private:
Builder& i_builder;
std::vector<WorldPacketList> i_data_cache;
// 0 = default, i => i-1 locale index
};
#ifndef WIN32
template<> void PlayerRelocationNotifier::Visit<Creature>(CreatureMapType&);
template<> void CreatureRelocationNotifier::Visit<Player>(PlayerMapType&);
template<> void CreatureRelocationNotifier::Visit<Creature>(CreatureMapType&);
template<> inline void DynamicObjectUpdater::Visit<Creature>(CreatureMapType&);
template<> inline void DynamicObjectUpdater::Visit<Player>(PlayerMapType&);
#endif
}
#endif
| H0zen/M2-server | src/game/WorldHandlers/GridNotifiers.h | C | gpl-2.0 | 46,372 |
#! /bin/sh
# Copyright (C) 2003-2018 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, 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 <https://www.gnu.org/licenses/>.
# Make sure empty calls to AC_CONFIG_FILES or AC_CONFIG_HEADERS are diagnosed.
. test-init.sh
# We avoid using configure.ac stub initialized by our testsuite setup, as
# we need to keep track of line numbers (to grep for error messages).
cat > configure.ac << END
AC_INIT([$me], [1.0])
AM_INIT_AUTOMAKE
AC_CONFIG_FILES ([oops])
AC_CONFIG_HEADERS
AC_OUTPUT
END
$ACLOCAL
AUTOMAKE_fails
grep 'configure\.ac:3:.* arguments .*AC_CONFIG_FILES' stderr
grep 'configure\.ac:4:.* arguments .*AC_CONFIG_HEADERS' stderr
:
| komh/automake-os2 | t/conff2.sh | Shell | gpl-2.0 | 1,205 |
package com.app.labeli;
import com.app.labeli.member.Member;
import net.tools.*;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* > @FragmentConnection
*
* Fragment to create a connection between app
* and API.
*
* @author Florian "Aamu Lumi" Kauder
* for the project @Label[i]
*/
public class FragmentConnection extends Fragment {
private EditText editTextLogin, editTextPassword;
private Button button;
private ProgressDialog pDialog;
public FragmentConnection() {
}
public void connectToAPI(View v){
if (editTextLogin.length() == 0)
Toast.makeText(getActivity(), "Veuillez rentrer un identifiant", Toast.LENGTH_SHORT).show();
else if (editTextPassword.length() == 0)
Toast.makeText(getActivity(), "Veuillez rentrer un mot de passe", Toast.LENGTH_SHORT).show();
else {
new InitConnection(editTextLogin.getText().toString(), editTextPassword.getText().toString())
.execute();
}
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getActivity().getActionBar().setTitle("Connexion");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_connection, container,
false);
editTextLogin = (EditText) v.findViewById(R.id.fragment_connection_edit_text_login);
editTextPassword = (EditText) v.findViewById(R.id.fragment_connection_edit_text_password);
button = (Button) v.findViewById(R.id.fragment_connection_button_connection);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
connectToAPI(arg0);
}
});
return v;
}
private class InitConnection extends AsyncTask<Void, Void, String>
{
String username, password;
boolean success;
public InitConnection(String username, String password){
this.username = username;
this.password = password;
this.success = false;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FragmentConnection.this.getActivity());
pDialog.setMessage("Connexion");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(Void... params)
{
success = APIConnection.login(username, password);
return null;
}
@Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (!success)
Toast.makeText(getActivity(), "Mauvais identifiant / mot de passe", Toast.LENGTH_SHORT).show();
else {
Member loggedUser = APIConnection.getLoggedUser();
Toast.makeText(getActivity(), "Bonjour " + loggedUser.getFirstName() + " " + loggedUser.getLastName(), Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).loadLeftMenu();
Fragment fragment = new FragmentAccount();
Bundle args = new Bundle();
fragment.setArguments(args);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.replace(R.id.activity_main_content_frame, fragment, fragment.getClass().getName());
transaction.addToBackStack(fragment.getClass().getName());
transaction.commit();
}
}
}
}
| asso-labeli/labeli-android-app | src/com/app/labeli/FragmentConnection.java | Java | gpl-2.0 | 3,863 |
/*
* This file implements the perfmon-2 subsystem which is used
* to program the IA-64 Performance Monitoring Unit (PMU).
*
* The initial version of perfmon.c was written by
* Ganesh Venkitachalam, IBM Corp.
*
* Then it was modified for perfmon-1.x by Stephane Eranian and
* David Mosberger, Hewlett Packard Co.
*
* Version Perfmon-2.x is a rewrite of perfmon-1.x
* by Stephane Eranian, Hewlett Packard Co.
*
* Copyright (C) 1999-2005 Hewlett Packard Co
* Stephane Eranian <[email protected]>
* David Mosberger-Tang <[email protected]>
*
* More information about perfmon available at:
* http://www.hpl.hp.com/research/linux/perfmon
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <linux/sysctl.h>
#include <linux/list.h>
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/vfs.h>
#include <linux/smp.h>
#include <linux/pagemap.h>
#include <linux/mount.h>
#include <linux/bitops.h>
#include <linux/capability.h>
#include <linux/rcupdate.h>
#include <linux/completion.h>
#include <linux/tracehook.h>
#include <linux/slab.h>
#include <asm/errno.h>
#include <asm/intrinsics.h>
#include <asm/page.h>
#include <asm/perfmon.h>
#include <asm/processor.h>
#include <asm/signal.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/delay.h>
#ifdef CONFIG_PERFMON
/*
* perfmon context state
*/
#define PFM_CTX_UNLOADED 1 /* context is not loaded onto any task */
#define PFM_CTX_LOADED 2 /* context is loaded onto a task */
#define PFM_CTX_MASKED 3 /* context is loaded but monitoring is masked due to overflow */
#define PFM_CTX_ZOMBIE 4 /* owner of the context is closing it */
#define PFM_INVALID_ACTIVATION (~0UL)
#define PFM_NUM_PMC_REGS 64 /* PMC save area for ctxsw */
#define PFM_NUM_PMD_REGS 64 /* PMD save area for ctxsw */
/*
* depth of message queue
*/
#define PFM_MAX_MSGS 32
#define PFM_CTXQ_EMPTY(g) ((g)->ctx_msgq_head == (g)->ctx_msgq_tail)
/*
* type of a PMU register (bitmask).
* bitmask structure:
* bit0 : register implemented
* bit1 : end marker
* bit2-3 : reserved
* bit4 : pmc has pmc.pm
* bit5 : pmc controls a counter (has pmc.oi), pmd is used as counter
* bit6-7 : register type
* bit8-31: reserved
*/
#define PFM_REG_NOTIMPL 0x0 /* not implemented at all */
#define PFM_REG_IMPL 0x1 /* register implemented */
#define PFM_REG_END 0x2 /* end marker */
#define PFM_REG_MONITOR (0x1<<4|PFM_REG_IMPL) /* a PMC with a pmc.pm field only */
#define PFM_REG_COUNTING (0x2<<4|PFM_REG_MONITOR) /* a monitor + pmc.oi+ PMD used as a counter */
#define PFM_REG_CONTROL (0x4<<4|PFM_REG_IMPL) /* PMU control register */
#define PFM_REG_CONFIG (0x8<<4|PFM_REG_IMPL) /* configuration register */
#define PFM_REG_BUFFER (0xc<<4|PFM_REG_IMPL) /* PMD used as buffer */
#define PMC_IS_LAST(i) (pmu_conf->pmc_desc[i].type & PFM_REG_END)
#define PMD_IS_LAST(i) (pmu_conf->pmd_desc[i].type & PFM_REG_END)
#define PMC_OVFL_NOTIFY(ctx, i) ((ctx)->ctx_pmds[i].flags & PFM_REGFL_OVFL_NOTIFY)
/* i assumed unsigned */
#define PMC_IS_IMPL(i) (i< PMU_MAX_PMCS && (pmu_conf->pmc_desc[i].type & PFM_REG_IMPL))
#define PMD_IS_IMPL(i) (i< PMU_MAX_PMDS && (pmu_conf->pmd_desc[i].type & PFM_REG_IMPL))
/* XXX: these assume that register i is implemented */
#define PMD_IS_COUNTING(i) ((pmu_conf->pmd_desc[i].type & PFM_REG_COUNTING) == PFM_REG_COUNTING)
#define PMC_IS_COUNTING(i) ((pmu_conf->pmc_desc[i].type & PFM_REG_COUNTING) == PFM_REG_COUNTING)
#define PMC_IS_MONITOR(i) ((pmu_conf->pmc_desc[i].type & PFM_REG_MONITOR) == PFM_REG_MONITOR)
#define PMC_IS_CONTROL(i) ((pmu_conf->pmc_desc[i].type & PFM_REG_CONTROL) == PFM_REG_CONTROL)
#define PMC_DFL_VAL(i) pmu_conf->pmc_desc[i].default_value
#define PMC_RSVD_MASK(i) pmu_conf->pmc_desc[i].reserved_mask
#define PMD_PMD_DEP(i) pmu_conf->pmd_desc[i].dep_pmd[0]
#define PMC_PMD_DEP(i) pmu_conf->pmc_desc[i].dep_pmd[0]
#define PFM_NUM_IBRS IA64_NUM_DBG_REGS
#define PFM_NUM_DBRS IA64_NUM_DBG_REGS
#define CTX_OVFL_NOBLOCK(c) ((c)->ctx_fl_block == 0)
#define CTX_HAS_SMPL(c) ((c)->ctx_fl_is_sampling)
#define PFM_CTX_TASK(h) (h)->ctx_task
#define PMU_PMC_OI 5 /* position of pmc.oi bit */
/* XXX: does not support more than 64 PMDs */
#define CTX_USED_PMD(ctx, mask) (ctx)->ctx_used_pmds[0] |= (mask)
#define CTX_IS_USED_PMD(ctx, c) (((ctx)->ctx_used_pmds[0] & (1UL << (c))) != 0UL)
#define CTX_USED_MONITOR(ctx, mask) (ctx)->ctx_used_monitors[0] |= (mask)
#define CTX_USED_IBR(ctx,n) (ctx)->ctx_used_ibrs[(n)>>6] |= 1UL<< ((n) % 64)
#define CTX_USED_DBR(ctx,n) (ctx)->ctx_used_dbrs[(n)>>6] |= 1UL<< ((n) % 64)
#define CTX_USES_DBREGS(ctx) (((pfm_context_t *)(ctx))->ctx_fl_using_dbreg==1)
#define PFM_CODE_RR 0 /* requesting code range restriction */
#define PFM_DATA_RR 1 /* requestion data range restriction */
#define PFM_CPUINFO_CLEAR(v) pfm_get_cpu_var(pfm_syst_info) &= ~(v)
#define PFM_CPUINFO_SET(v) pfm_get_cpu_var(pfm_syst_info) |= (v)
#define PFM_CPUINFO_GET() pfm_get_cpu_var(pfm_syst_info)
#define RDEP(x) (1UL<<(x))
/*
* context protection macros
* in SMP:
* - we need to protect against CPU concurrency (spin_lock)
* - we need to protect against PMU overflow interrupts (local_irq_disable)
* in UP:
* - we need to protect against PMU overflow interrupts (local_irq_disable)
*
* spin_lock_irqsave()/spin_unlock_irqrestore():
* in SMP: local_irq_disable + spin_lock
* in UP : local_irq_disable
*
* spin_lock()/spin_lock():
* in UP : removed automatically
* in SMP: protect against context accesses from other CPU. interrupts
* are not masked. This is useful for the PMU interrupt handler
* because we know we will not get PMU concurrency in that code.
*/
#define PROTECT_CTX(c, f) \
do { \
DPRINT(("spinlock_irq_save ctx %p by [%d]\n", c, task_pid_nr(current))); \
spin_lock_irqsave(&(c)->ctx_lock, f); \
DPRINT(("spinlocked ctx %p by [%d]\n", c, task_pid_nr(current))); \
} while(0)
#define UNPROTECT_CTX(c, f) \
do { \
DPRINT(("spinlock_irq_restore ctx %p by [%d]\n", c, task_pid_nr(current))); \
spin_unlock_irqrestore(&(c)->ctx_lock, f); \
} while(0)
#define PROTECT_CTX_NOPRINT(c, f) \
do { \
spin_lock_irqsave(&(c)->ctx_lock, f); \
} while(0)
#define UNPROTECT_CTX_NOPRINT(c, f) \
do { \
spin_unlock_irqrestore(&(c)->ctx_lock, f); \
} while(0)
#define PROTECT_CTX_NOIRQ(c) \
do { \
spin_lock(&(c)->ctx_lock); \
} while(0)
#define UNPROTECT_CTX_NOIRQ(c) \
do { \
spin_unlock(&(c)->ctx_lock); \
} while(0)
#ifdef CONFIG_SMP
#define GET_ACTIVATION() pfm_get_cpu_var(pmu_activation_number)
#define INC_ACTIVATION() pfm_get_cpu_var(pmu_activation_number)++
#define SET_ACTIVATION(c) (c)->ctx_last_activation = GET_ACTIVATION()
#else /* !CONFIG_SMP */
#define SET_ACTIVATION(t) do {} while(0)
#define GET_ACTIVATION(t) do {} while(0)
#define INC_ACTIVATION(t) do {} while(0)
#endif /* CONFIG_SMP */
#define SET_PMU_OWNER(t, c) do { pfm_get_cpu_var(pmu_owner) = (t); pfm_get_cpu_var(pmu_ctx) = (c); } while(0)
#define GET_PMU_OWNER() pfm_get_cpu_var(pmu_owner)
#define GET_PMU_CTX() pfm_get_cpu_var(pmu_ctx)
#define LOCK_PFS(g) spin_lock_irqsave(&pfm_sessions.pfs_lock, g)
#define UNLOCK_PFS(g) spin_unlock_irqrestore(&pfm_sessions.pfs_lock, g)
#define PFM_REG_RETFLAG_SET(flags, val) do { flags &= ~PFM_REG_RETFL_MASK; flags |= (val); } while(0)
/*
* cmp0 must be the value of pmc0
*/
#define PMC0_HAS_OVFL(cmp0) (cmp0 & ~0x1UL)
#define PFMFS_MAGIC 0xa0b4d889
/*
* debugging
*/
#define PFM_DEBUGGING 1
#ifdef PFM_DEBUGGING
#define DPRINT(a) \
do { \
if (unlikely(pfm_sysctl.debug >0)) { printk("%s.%d: CPU%d [%d] ", __func__, __LINE__, smp_processor_id(), task_pid_nr(current)); printk a; } \
} while (0)
#define DPRINT_ovfl(a) \
do { \
if (unlikely(pfm_sysctl.debug > 0 && pfm_sysctl.debug_ovfl >0)) { printk("%s.%d: CPU%d [%d] ", __func__, __LINE__, smp_processor_id(), task_pid_nr(current)); printk a; } \
} while (0)
#endif
/*
* 64-bit software counter structure
*
* the next_reset_type is applied to the next call to pfm_reset_regs()
*/
typedef struct {
unsigned long val; /* virtual 64bit counter value */
unsigned long lval; /* last reset value */
unsigned long long_reset; /* reset value on sampling overflow */
unsigned long short_reset; /* reset value on overflow */
unsigned long reset_pmds[4]; /* which other pmds to reset when this counter overflows */
unsigned long smpl_pmds[4]; /* which pmds are accessed when counter overflow */
unsigned long seed; /* seed for random-number generator */
unsigned long mask; /* mask for random-number generator */
unsigned int flags; /* notify/do not notify */
unsigned long eventid; /* overflow event identifier */
} pfm_counter_t;
/*
* context flags
*/
typedef struct {
unsigned int block:1; /* when 1, task will blocked on user notifications */
unsigned int system:1; /* do system wide monitoring */
unsigned int using_dbreg:1; /* using range restrictions (debug registers) */
unsigned int is_sampling:1; /* true if using a custom format */
unsigned int excl_idle:1; /* exclude idle task in system wide session */
unsigned int going_zombie:1; /* context is zombie (MASKED+blocking) */
unsigned int trap_reason:2; /* reason for going into pfm_handle_work() */
unsigned int no_msg:1; /* no message sent on overflow */
unsigned int can_restart:1; /* allowed to issue a PFM_RESTART */
unsigned int reserved:22;
} pfm_context_flags_t;
#define PFM_TRAP_REASON_NONE 0x0 /* default value */
#define PFM_TRAP_REASON_BLOCK 0x1 /* we need to block on overflow */
#define PFM_TRAP_REASON_RESET 0x2 /* we need to reset PMDs */
/*
* perfmon context: encapsulates all the state of a monitoring session
*/
typedef struct pfm_context {
spinlock_t ctx_lock; /* context protection */
pfm_context_flags_t ctx_flags; /* bitmask of flags (block reason incl.) */
unsigned int ctx_state; /* state: active/inactive (no bitfield) */
struct task_struct *ctx_task; /* task to which context is attached */
unsigned long ctx_ovfl_regs[4]; /* which registers overflowed (notification) */
struct completion ctx_restart_done; /* use for blocking notification mode */
unsigned long ctx_used_pmds[4]; /* bitmask of PMD used */
unsigned long ctx_all_pmds[4]; /* bitmask of all accessible PMDs */
unsigned long ctx_reload_pmds[4]; /* bitmask of force reload PMD on ctxsw in */
unsigned long ctx_all_pmcs[4]; /* bitmask of all accessible PMCs */
unsigned long ctx_reload_pmcs[4]; /* bitmask of force reload PMC on ctxsw in */
unsigned long ctx_used_monitors[4]; /* bitmask of monitor PMC being used */
unsigned long ctx_pmcs[PFM_NUM_PMC_REGS]; /* saved copies of PMC values */
unsigned int ctx_used_ibrs[1]; /* bitmask of used IBR (speedup ctxsw in) */
unsigned int ctx_used_dbrs[1]; /* bitmask of used DBR (speedup ctxsw in) */
unsigned long ctx_dbrs[IA64_NUM_DBG_REGS]; /* DBR values (cache) when not loaded */
unsigned long ctx_ibrs[IA64_NUM_DBG_REGS]; /* IBR values (cache) when not loaded */
pfm_counter_t ctx_pmds[PFM_NUM_PMD_REGS]; /* software state for PMDS */
unsigned long th_pmcs[PFM_NUM_PMC_REGS]; /* PMC thread save state */
unsigned long th_pmds[PFM_NUM_PMD_REGS]; /* PMD thread save state */
unsigned long ctx_saved_psr_up; /* only contains psr.up value */
unsigned long ctx_last_activation; /* context last activation number for last_cpu */
unsigned int ctx_last_cpu; /* CPU id of current or last CPU used (SMP only) */
unsigned int ctx_cpu; /* cpu to which perfmon is applied (system wide) */
int ctx_fd; /* file descriptor used my this context */
pfm_ovfl_arg_t ctx_ovfl_arg; /* argument to custom buffer format handler */
pfm_buffer_fmt_t *ctx_buf_fmt; /* buffer format callbacks */
void *ctx_smpl_hdr; /* points to sampling buffer header kernel vaddr */
unsigned long ctx_smpl_size; /* size of sampling buffer */
void *ctx_smpl_vaddr; /* user level virtual address of smpl buffer */
wait_queue_head_t ctx_msgq_wait;
pfm_msg_t ctx_msgq[PFM_MAX_MSGS];
int ctx_msgq_head;
int ctx_msgq_tail;
struct fasync_struct *ctx_async_queue;
wait_queue_head_t ctx_zombieq; /* termination cleanup wait queue */
} pfm_context_t;
/*
* magic number used to verify that structure is really
* a perfmon context
*/
#define PFM_IS_FILE(f) ((f)->f_op == &pfm_file_ops)
#define PFM_GET_CTX(t) ((pfm_context_t *)(t)->thread.pfm_context)
#ifdef CONFIG_SMP
#define SET_LAST_CPU(ctx, v) (ctx)->ctx_last_cpu = (v)
#define GET_LAST_CPU(ctx) (ctx)->ctx_last_cpu
#else
#define SET_LAST_CPU(ctx, v) do {} while(0)
#define GET_LAST_CPU(ctx) do {} while(0)
#endif
#define ctx_fl_block ctx_flags.block
#define ctx_fl_system ctx_flags.system
#define ctx_fl_using_dbreg ctx_flags.using_dbreg
#define ctx_fl_is_sampling ctx_flags.is_sampling
#define ctx_fl_excl_idle ctx_flags.excl_idle
#define ctx_fl_going_zombie ctx_flags.going_zombie
#define ctx_fl_trap_reason ctx_flags.trap_reason
#define ctx_fl_no_msg ctx_flags.no_msg
#define ctx_fl_can_restart ctx_flags.can_restart
#define PFM_SET_WORK_PENDING(t, v) do { (t)->thread.pfm_needs_checking = v; } while(0);
#define PFM_GET_WORK_PENDING(t) (t)->thread.pfm_needs_checking
/*
* global information about all sessions
* mostly used to synchronize between system wide and per-process
*/
typedef struct {
spinlock_t pfs_lock; /* lock the structure */
unsigned int pfs_task_sessions; /* number of per task sessions */
unsigned int pfs_sys_sessions; /* number of per system wide sessions */
unsigned int pfs_sys_use_dbregs; /* incremented when a system wide session uses debug regs */
unsigned int pfs_ptrace_use_dbregs; /* incremented when a process uses debug regs */
struct task_struct *pfs_sys_session[NR_CPUS]; /* point to task owning a system-wide session */
} pfm_session_t;
/*
* information about a PMC or PMD.
* dep_pmd[]: a bitmask of dependent PMD registers
* dep_pmc[]: a bitmask of dependent PMC registers
*/
typedef int (*pfm_reg_check_t)(struct task_struct *task, pfm_context_t *ctx, unsigned int cnum, unsigned long *val, struct pt_regs *regs);
typedef struct {
unsigned int type;
int pm_pos;
unsigned long default_value; /* power-on default value */
unsigned long reserved_mask; /* bitmask of reserved bits */
pfm_reg_check_t read_check;
pfm_reg_check_t write_check;
unsigned long dep_pmd[4];
unsigned long dep_pmc[4];
} pfm_reg_desc_t;
/* assume cnum is a valid monitor */
#define PMC_PM(cnum, val) (((val) >> (pmu_conf->pmc_desc[cnum].pm_pos)) & 0x1)
/*
* This structure is initialized at boot time and contains
* a description of the PMU main characteristics.
*
* If the probe function is defined, detection is based
* on its return value:
* - 0 means recognized PMU
* - anything else means not supported
* When the probe function is not defined, then the pmu_family field
* is used and it must match the host CPU family such that:
* - cpu->family & config->pmu_family != 0
*/
typedef struct {
unsigned long ovfl_val; /* overflow value for counters */
pfm_reg_desc_t *pmc_desc; /* detailed PMC register dependencies descriptions */
pfm_reg_desc_t *pmd_desc; /* detailed PMD register dependencies descriptions */
unsigned int num_pmcs; /* number of PMCS: computed at init time */
unsigned int num_pmds; /* number of PMDS: computed at init time */
unsigned long impl_pmcs[4]; /* bitmask of implemented PMCS */
unsigned long impl_pmds[4]; /* bitmask of implemented PMDS */
char *pmu_name; /* PMU family name */
unsigned int pmu_family; /* cpuid family pattern used to identify pmu */
unsigned int flags; /* pmu specific flags */
unsigned int num_ibrs; /* number of IBRS: computed at init time */
unsigned int num_dbrs; /* number of DBRS: computed at init time */
unsigned int num_counters; /* PMC/PMD counting pairs : computed at init time */
int (*probe)(void); /* customized probe routine */
unsigned int use_rr_dbregs:1; /* set if debug registers used for range restriction */
} pmu_config_t;
/*
* PMU specific flags
*/
#define PFM_PMU_IRQ_RESEND 1 /* PMU needs explicit IRQ resend */
/*
* debug register related type definitions
*/
typedef struct {
unsigned long ibr_mask:56;
unsigned long ibr_plm:4;
unsigned long ibr_ig:3;
unsigned long ibr_x:1;
} ibr_mask_reg_t;
typedef struct {
unsigned long dbr_mask:56;
unsigned long dbr_plm:4;
unsigned long dbr_ig:2;
unsigned long dbr_w:1;
unsigned long dbr_r:1;
} dbr_mask_reg_t;
typedef union {
unsigned long val;
ibr_mask_reg_t ibr;
dbr_mask_reg_t dbr;
} dbreg_t;
/*
* perfmon command descriptions
*/
typedef struct {
int (*cmd_func)(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
char *cmd_name;
int cmd_flags;
unsigned int cmd_narg;
size_t cmd_argsize;
int (*cmd_getsize)(void *arg, size_t *sz);
} pfm_cmd_desc_t;
#define PFM_CMD_FD 0x01 /* command requires a file descriptor */
#define PFM_CMD_ARG_READ 0x02 /* command must read argument(s) */
#define PFM_CMD_ARG_RW 0x04 /* command must read/write argument(s) */
#define PFM_CMD_STOP 0x08 /* command does not work on zombie context */
#define PFM_CMD_NAME(cmd) pfm_cmd_tab[(cmd)].cmd_name
#define PFM_CMD_READ_ARG(cmd) (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_ARG_READ)
#define PFM_CMD_RW_ARG(cmd) (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_ARG_RW)
#define PFM_CMD_USE_FD(cmd) (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_FD)
#define PFM_CMD_STOPPED(cmd) (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_STOP)
#define PFM_CMD_ARG_MANY -1 /* cannot be zero */
typedef struct {
unsigned long pfm_spurious_ovfl_intr_count; /* keep track of spurious ovfl interrupts */
unsigned long pfm_replay_ovfl_intr_count; /* keep track of replayed ovfl interrupts */
unsigned long pfm_ovfl_intr_count; /* keep track of ovfl interrupts */
unsigned long pfm_ovfl_intr_cycles; /* cycles spent processing ovfl interrupts */
unsigned long pfm_ovfl_intr_cycles_min; /* min cycles spent processing ovfl interrupts */
unsigned long pfm_ovfl_intr_cycles_max; /* max cycles spent processing ovfl interrupts */
unsigned long pfm_smpl_handler_calls;
unsigned long pfm_smpl_handler_cycles;
char pad[SMP_CACHE_BYTES] ____cacheline_aligned;
} pfm_stats_t;
/*
* perfmon internal variables
*/
static pfm_stats_t pfm_stats[NR_CPUS];
static pfm_session_t pfm_sessions; /* global sessions information */
static DEFINE_SPINLOCK(pfm_alt_install_check);
static pfm_intr_handler_desc_t *pfm_alt_intr_handler;
static struct proc_dir_entry *perfmon_dir;
static pfm_uuid_t pfm_null_uuid = {0,};
static spinlock_t pfm_buffer_fmt_lock;
static LIST_HEAD(pfm_buffer_fmt_list);
static pmu_config_t *pmu_conf;
/* sysctl() controls */
pfm_sysctl_t pfm_sysctl;
EXPORT_SYMBOL(pfm_sysctl);
static ctl_table pfm_ctl_table[]={
{
.procname = "debug",
.data = &pfm_sysctl.debug,
.maxlen = sizeof(int),
.mode = 0666,
.proc_handler = proc_dointvec,
},
{
.procname = "debug_ovfl",
.data = &pfm_sysctl.debug_ovfl,
.maxlen = sizeof(int),
.mode = 0666,
.proc_handler = proc_dointvec,
},
{
.procname = "fastctxsw",
.data = &pfm_sysctl.fastctxsw,
.maxlen = sizeof(int),
.mode = 0600,
.proc_handler = proc_dointvec,
},
{
.procname = "expert_mode",
.data = &pfm_sysctl.expert_mode,
.maxlen = sizeof(int),
.mode = 0600,
.proc_handler = proc_dointvec,
},
{}
};
static ctl_table pfm_sysctl_dir[] = {
{
.procname = "perfmon",
.mode = 0555,
.child = pfm_ctl_table,
},
{}
};
static ctl_table pfm_sysctl_root[] = {
{
.procname = "kernel",
.mode = 0555,
.child = pfm_sysctl_dir,
},
{}
};
static struct ctl_table_header *pfm_sysctl_header;
static int pfm_context_unload(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
#define pfm_get_cpu_var(v) __ia64_per_cpu_var(v)
#define pfm_get_cpu_data(a,b) per_cpu(a, b)
static inline void
pfm_put_task(struct task_struct *task)
{
if (task != current) put_task_struct(task);
}
static inline void
pfm_reserve_page(unsigned long a)
{
SetPageReserved(vmalloc_to_page((void *)a));
}
static inline void
pfm_unreserve_page(unsigned long a)
{
ClearPageReserved(vmalloc_to_page((void*)a));
}
static inline unsigned long
pfm_protect_ctx_ctxsw(pfm_context_t *x)
{
spin_lock(&(x)->ctx_lock);
return 0UL;
}
static inline void
pfm_unprotect_ctx_ctxsw(pfm_context_t *x, unsigned long f)
{
spin_unlock(&(x)->ctx_lock);
}
static inline unsigned long
pfm_get_unmapped_area(struct file *file, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags, unsigned long exec)
{
return get_unmapped_area(file, addr, len, pgoff, flags);
}
/* forward declaration */
static const struct dentry_operations pfmfs_dentry_operations;
static struct dentry *
pfmfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data)
{
return mount_pseudo(fs_type, "pfm:", NULL, &pfmfs_dentry_operations,
PFMFS_MAGIC);
}
static struct file_system_type pfm_fs_type = {
.name = "pfmfs",
.mount = pfmfs_mount,
.kill_sb = kill_anon_super,
};
DEFINE_PER_CPU(unsigned long, pfm_syst_info);
DEFINE_PER_CPU(struct task_struct *, pmu_owner);
DEFINE_PER_CPU(pfm_context_t *, pmu_ctx);
DEFINE_PER_CPU(unsigned long, pmu_activation_number);
EXPORT_PER_CPU_SYMBOL_GPL(pfm_syst_info);
/* forward declaration */
static const struct file_operations pfm_file_ops;
/*
* forward declarations
*/
#ifndef CONFIG_SMP
static void pfm_lazy_save_regs (struct task_struct *ta);
#endif
void dump_pmu_state(const char *);
static int pfm_write_ibr_dbr(int mode, pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
#include "perfmon_itanium.h"
#include "perfmon_mckinley.h"
#include "perfmon_montecito.h"
#include "perfmon_generic.h"
static pmu_config_t *pmu_confs[]={
&pmu_conf_mont,
&pmu_conf_mck,
&pmu_conf_ita,
&pmu_conf_gen, /* must be last */
NULL
};
static int pfm_end_notify_user(pfm_context_t *ctx);
static inline void
pfm_clear_psr_pp(void)
{
ia64_rsm(IA64_PSR_PP);
ia64_srlz_i();
}
static inline void
pfm_set_psr_pp(void)
{
ia64_ssm(IA64_PSR_PP);
ia64_srlz_i();
}
static inline void
pfm_clear_psr_up(void)
{
ia64_rsm(IA64_PSR_UP);
ia64_srlz_i();
}
static inline void
pfm_set_psr_up(void)
{
ia64_ssm(IA64_PSR_UP);
ia64_srlz_i();
}
static inline unsigned long
pfm_get_psr(void)
{
unsigned long tmp;
tmp = ia64_getreg(_IA64_REG_PSR);
ia64_srlz_i();
return tmp;
}
static inline void
pfm_set_psr_l(unsigned long val)
{
ia64_setreg(_IA64_REG_PSR_L, val);
ia64_srlz_i();
}
static inline void
pfm_freeze_pmu(void)
{
ia64_set_pmc(0,1UL);
ia64_srlz_d();
}
static inline void
pfm_unfreeze_pmu(void)
{
ia64_set_pmc(0,0UL);
ia64_srlz_d();
}
static inline void
pfm_restore_ibrs(unsigned long *ibrs, unsigned int nibrs)
{
int i;
for (i=0; i < nibrs; i++) {
ia64_set_ibr(i, ibrs[i]);
ia64_dv_serialize_instruction();
}
ia64_srlz_i();
}
static inline void
pfm_restore_dbrs(unsigned long *dbrs, unsigned int ndbrs)
{
int i;
for (i=0; i < ndbrs; i++) {
ia64_set_dbr(i, dbrs[i]);
ia64_dv_serialize_data();
}
ia64_srlz_d();
}
/*
* PMD[i] must be a counter. no check is made
*/
static inline unsigned long
pfm_read_soft_counter(pfm_context_t *ctx, int i)
{
return ctx->ctx_pmds[i].val + (ia64_get_pmd(i) & pmu_conf->ovfl_val);
}
/*
* PMD[i] must be a counter. no check is made
*/
static inline void
pfm_write_soft_counter(pfm_context_t *ctx, int i, unsigned long val)
{
unsigned long ovfl_val = pmu_conf->ovfl_val;
ctx->ctx_pmds[i].val = val & ~ovfl_val;
/*
* writing to unimplemented part is ignore, so we do not need to
* mask off top part
*/
ia64_set_pmd(i, val & ovfl_val);
}
static pfm_msg_t *
pfm_get_new_msg(pfm_context_t *ctx)
{
int idx, next;
next = (ctx->ctx_msgq_tail+1) % PFM_MAX_MSGS;
DPRINT(("ctx_fd=%p head=%d tail=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
if (next == ctx->ctx_msgq_head) return NULL;
idx = ctx->ctx_msgq_tail;
ctx->ctx_msgq_tail = next;
DPRINT(("ctx=%p head=%d tail=%d msg=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail, idx));
return ctx->ctx_msgq+idx;
}
static pfm_msg_t *
pfm_get_next_msg(pfm_context_t *ctx)
{
pfm_msg_t *msg;
DPRINT(("ctx=%p head=%d tail=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
if (PFM_CTXQ_EMPTY(ctx)) return NULL;
/*
* get oldest message
*/
msg = ctx->ctx_msgq+ctx->ctx_msgq_head;
/*
* and move forward
*/
ctx->ctx_msgq_head = (ctx->ctx_msgq_head+1) % PFM_MAX_MSGS;
DPRINT(("ctx=%p head=%d tail=%d type=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail, msg->pfm_gen_msg.msg_type));
return msg;
}
static void
pfm_reset_msgq(pfm_context_t *ctx)
{
ctx->ctx_msgq_head = ctx->ctx_msgq_tail = 0;
DPRINT(("ctx=%p msgq reset\n", ctx));
}
static void *
pfm_rvmalloc(unsigned long size)
{
void *mem;
unsigned long addr;
size = PAGE_ALIGN(size);
mem = vzalloc(size);
if (mem) {
//printk("perfmon: CPU%d pfm_rvmalloc(%ld)=%p\n", smp_processor_id(), size, mem);
addr = (unsigned long)mem;
while (size > 0) {
pfm_reserve_page(addr);
addr+=PAGE_SIZE;
size-=PAGE_SIZE;
}
}
return mem;
}
static void
pfm_rvfree(void *mem, unsigned long size)
{
unsigned long addr;
if (mem) {
DPRINT(("freeing physical buffer @%p size=%lu\n", mem, size));
addr = (unsigned long) mem;
while ((long) size > 0) {
pfm_unreserve_page(addr);
addr+=PAGE_SIZE;
size-=PAGE_SIZE;
}
vfree(mem);
}
return;
}
static pfm_context_t *
pfm_context_alloc(int ctx_flags)
{
pfm_context_t *ctx;
/*
* allocate context descriptor
* must be able to free with interrupts disabled
*/
ctx = kzalloc(sizeof(pfm_context_t), GFP_KERNEL);
if (ctx) {
DPRINT(("alloc ctx @%p\n", ctx));
/*
* init context protection lock
*/
spin_lock_init(&ctx->ctx_lock);
/*
* context is unloaded
*/
ctx->ctx_state = PFM_CTX_UNLOADED;
/*
* initialization of context's flags
*/
ctx->ctx_fl_block = (ctx_flags & PFM_FL_NOTIFY_BLOCK) ? 1 : 0;
ctx->ctx_fl_system = (ctx_flags & PFM_FL_SYSTEM_WIDE) ? 1: 0;
ctx->ctx_fl_no_msg = (ctx_flags & PFM_FL_OVFL_NO_MSG) ? 1: 0;
/*
* will move to set properties
* ctx->ctx_fl_excl_idle = (ctx_flags & PFM_FL_EXCL_IDLE) ? 1: 0;
*/
/*
* init restart semaphore to locked
*/
init_completion(&ctx->ctx_restart_done);
/*
* activation is used in SMP only
*/
ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
SET_LAST_CPU(ctx, -1);
/*
* initialize notification message queue
*/
ctx->ctx_msgq_head = ctx->ctx_msgq_tail = 0;
init_waitqueue_head(&ctx->ctx_msgq_wait);
init_waitqueue_head(&ctx->ctx_zombieq);
}
return ctx;
}
static void
pfm_context_free(pfm_context_t *ctx)
{
if (ctx) {
DPRINT(("free ctx @%p\n", ctx));
kfree(ctx);
}
}
static void
pfm_mask_monitoring(struct task_struct *task)
{
pfm_context_t *ctx = PFM_GET_CTX(task);
unsigned long mask, val, ovfl_mask;
int i;
DPRINT_ovfl(("masking monitoring for [%d]\n", task_pid_nr(task)));
ovfl_mask = pmu_conf->ovfl_val;
/*
* monitoring can only be masked as a result of a valid
* counter overflow. In UP, it means that the PMU still
* has an owner. Note that the owner can be different
* from the current task. However the PMU state belongs
* to the owner.
* In SMP, a valid overflow only happens when task is
* current. Therefore if we come here, we know that
* the PMU state belongs to the current task, therefore
* we can access the live registers.
*
* So in both cases, the live register contains the owner's
* state. We can ONLY touch the PMU registers and NOT the PSR.
*
* As a consequence to this call, the ctx->th_pmds[] array
* contains stale information which must be ignored
* when context is reloaded AND monitoring is active (see
* pfm_restart).
*/
mask = ctx->ctx_used_pmds[0];
for (i = 0; mask; i++, mask>>=1) {
/* skip non used pmds */
if ((mask & 0x1) == 0) continue;
val = ia64_get_pmd(i);
if (PMD_IS_COUNTING(i)) {
/*
* we rebuild the full 64 bit value of the counter
*/
ctx->ctx_pmds[i].val += (val & ovfl_mask);
} else {
ctx->ctx_pmds[i].val = val;
}
DPRINT_ovfl(("pmd[%d]=0x%lx hw_pmd=0x%lx\n",
i,
ctx->ctx_pmds[i].val,
val & ovfl_mask));
}
/*
* mask monitoring by setting the privilege level to 0
* we cannot use psr.pp/psr.up for this, it is controlled by
* the user
*
* if task is current, modify actual registers, otherwise modify
* thread save state, i.e., what will be restored in pfm_load_regs()
*/
mask = ctx->ctx_used_monitors[0] >> PMU_FIRST_COUNTER;
for(i= PMU_FIRST_COUNTER; mask; i++, mask>>=1) {
if ((mask & 0x1) == 0UL) continue;
ia64_set_pmc(i, ctx->th_pmcs[i] & ~0xfUL);
ctx->th_pmcs[i] &= ~0xfUL;
DPRINT_ovfl(("pmc[%d]=0x%lx\n", i, ctx->th_pmcs[i]));
}
/*
* make all of this visible
*/
ia64_srlz_d();
}
/*
* must always be done with task == current
*
* context must be in MASKED state when calling
*/
static void
pfm_restore_monitoring(struct task_struct *task)
{
pfm_context_t *ctx = PFM_GET_CTX(task);
unsigned long mask, ovfl_mask;
unsigned long psr, val;
int i, is_system;
is_system = ctx->ctx_fl_system;
ovfl_mask = pmu_conf->ovfl_val;
if (task != current) {
printk(KERN_ERR "perfmon.%d: invalid task[%d] current[%d]\n", __LINE__, task_pid_nr(task), task_pid_nr(current));
return;
}
if (ctx->ctx_state != PFM_CTX_MASKED) {
printk(KERN_ERR "perfmon.%d: task[%d] current[%d] invalid state=%d\n", __LINE__,
task_pid_nr(task), task_pid_nr(current), ctx->ctx_state);
return;
}
psr = pfm_get_psr();
/*
* monitoring is masked via the PMC.
* As we restore their value, we do not want each counter to
* restart right away. We stop monitoring using the PSR,
* restore the PMC (and PMD) and then re-establish the psr
* as it was. Note that there can be no pending overflow at
* this point, because monitoring was MASKED.
*
* system-wide session are pinned and self-monitoring
*/
if (is_system && (PFM_CPUINFO_GET() & PFM_CPUINFO_DCR_PP)) {
/* disable dcr pp */
ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) & ~IA64_DCR_PP);
pfm_clear_psr_pp();
} else {
pfm_clear_psr_up();
}
/*
* first, we restore the PMD
*/
mask = ctx->ctx_used_pmds[0];
for (i = 0; mask; i++, mask>>=1) {
/* skip non used pmds */
if ((mask & 0x1) == 0) continue;
if (PMD_IS_COUNTING(i)) {
/*
* we split the 64bit value according to
* counter width
*/
val = ctx->ctx_pmds[i].val & ovfl_mask;
ctx->ctx_pmds[i].val &= ~ovfl_mask;
} else {
val = ctx->ctx_pmds[i].val;
}
ia64_set_pmd(i, val);
DPRINT(("pmd[%d]=0x%lx hw_pmd=0x%lx\n",
i,
ctx->ctx_pmds[i].val,
val));
}
/*
* restore the PMCs
*/
mask = ctx->ctx_used_monitors[0] >> PMU_FIRST_COUNTER;
for(i= PMU_FIRST_COUNTER; mask; i++, mask>>=1) {
if ((mask & 0x1) == 0UL) continue;
ctx->th_pmcs[i] = ctx->ctx_pmcs[i];
ia64_set_pmc(i, ctx->th_pmcs[i]);
DPRINT(("[%d] pmc[%d]=0x%lx\n",
task_pid_nr(task), i, ctx->th_pmcs[i]));
}
ia64_srlz_d();
/*
* must restore DBR/IBR because could be modified while masked
* XXX: need to optimize
*/
if (ctx->ctx_fl_using_dbreg) {
pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
}
/*
* now restore PSR
*/
if (is_system && (PFM_CPUINFO_GET() & PFM_CPUINFO_DCR_PP)) {
/* enable dcr pp */
ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) | IA64_DCR_PP);
ia64_srlz_i();
}
pfm_set_psr_l(psr);
}
static inline void
pfm_save_pmds(unsigned long *pmds, unsigned long mask)
{
int i;
ia64_srlz_d();
for (i=0; mask; i++, mask>>=1) {
if (mask & 0x1) pmds[i] = ia64_get_pmd(i);
}
}
/*
* reload from thread state (used for ctxw only)
*/
static inline void
pfm_restore_pmds(unsigned long *pmds, unsigned long mask)
{
int i;
unsigned long val, ovfl_val = pmu_conf->ovfl_val;
for (i=0; mask; i++, mask>>=1) {
if ((mask & 0x1) == 0) continue;
val = PMD_IS_COUNTING(i) ? pmds[i] & ovfl_val : pmds[i];
ia64_set_pmd(i, val);
}
ia64_srlz_d();
}
/*
* propagate PMD from context to thread-state
*/
static inline void
pfm_copy_pmds(struct task_struct *task, pfm_context_t *ctx)
{
unsigned long ovfl_val = pmu_conf->ovfl_val;
unsigned long mask = ctx->ctx_all_pmds[0];
unsigned long val;
int i;
DPRINT(("mask=0x%lx\n", mask));
for (i=0; mask; i++, mask>>=1) {
val = ctx->ctx_pmds[i].val;
/*
* We break up the 64 bit value into 2 pieces
* the lower bits go to the machine state in the
* thread (will be reloaded on ctxsw in).
* The upper part stays in the soft-counter.
*/
if (PMD_IS_COUNTING(i)) {
ctx->ctx_pmds[i].val = val & ~ovfl_val;
val &= ovfl_val;
}
ctx->th_pmds[i] = val;
DPRINT(("pmd[%d]=0x%lx soft_val=0x%lx\n",
i,
ctx->th_pmds[i],
ctx->ctx_pmds[i].val));
}
}
/*
* propagate PMC from context to thread-state
*/
static inline void
pfm_copy_pmcs(struct task_struct *task, pfm_context_t *ctx)
{
unsigned long mask = ctx->ctx_all_pmcs[0];
int i;
DPRINT(("mask=0x%lx\n", mask));
for (i=0; mask; i++, mask>>=1) {
/* masking 0 with ovfl_val yields 0 */
ctx->th_pmcs[i] = ctx->ctx_pmcs[i];
DPRINT(("pmc[%d]=0x%lx\n", i, ctx->th_pmcs[i]));
}
}
static inline void
pfm_restore_pmcs(unsigned long *pmcs, unsigned long mask)
{
int i;
for (i=0; mask; i++, mask>>=1) {
if ((mask & 0x1) == 0) continue;
ia64_set_pmc(i, pmcs[i]);
}
ia64_srlz_d();
}
static inline int
pfm_uuid_cmp(pfm_uuid_t a, pfm_uuid_t b)
{
return memcmp(a, b, sizeof(pfm_uuid_t));
}
static inline int
pfm_buf_fmt_exit(pfm_buffer_fmt_t *fmt, struct task_struct *task, void *buf, struct pt_regs *regs)
{
int ret = 0;
if (fmt->fmt_exit) ret = (*fmt->fmt_exit)(task, buf, regs);
return ret;
}
static inline int
pfm_buf_fmt_getsize(pfm_buffer_fmt_t *fmt, struct task_struct *task, unsigned int flags, int cpu, void *arg, unsigned long *size)
{
int ret = 0;
if (fmt->fmt_getsize) ret = (*fmt->fmt_getsize)(task, flags, cpu, arg, size);
return ret;
}
static inline int
pfm_buf_fmt_validate(pfm_buffer_fmt_t *fmt, struct task_struct *task, unsigned int flags,
int cpu, void *arg)
{
int ret = 0;
if (fmt->fmt_validate) ret = (*fmt->fmt_validate)(task, flags, cpu, arg);
return ret;
}
static inline int
pfm_buf_fmt_init(pfm_buffer_fmt_t *fmt, struct task_struct *task, void *buf, unsigned int flags,
int cpu, void *arg)
{
int ret = 0;
if (fmt->fmt_init) ret = (*fmt->fmt_init)(task, buf, flags, cpu, arg);
return ret;
}
static inline int
pfm_buf_fmt_restart(pfm_buffer_fmt_t *fmt, struct task_struct *task, pfm_ovfl_ctrl_t *ctrl, void *buf, struct pt_regs *regs)
{
int ret = 0;
if (fmt->fmt_restart) ret = (*fmt->fmt_restart)(task, ctrl, buf, regs);
return ret;
}
static inline int
pfm_buf_fmt_restart_active(pfm_buffer_fmt_t *fmt, struct task_struct *task, pfm_ovfl_ctrl_t *ctrl, void *buf, struct pt_regs *regs)
{
int ret = 0;
if (fmt->fmt_restart_active) ret = (*fmt->fmt_restart_active)(task, ctrl, buf, regs);
return ret;
}
static pfm_buffer_fmt_t *
__pfm_find_buffer_fmt(pfm_uuid_t uuid)
{
struct list_head * pos;
pfm_buffer_fmt_t * entry;
list_for_each(pos, &pfm_buffer_fmt_list) {
entry = list_entry(pos, pfm_buffer_fmt_t, fmt_list);
if (pfm_uuid_cmp(uuid, entry->fmt_uuid) == 0)
return entry;
}
return NULL;
}
/*
* find a buffer format based on its uuid
*/
static pfm_buffer_fmt_t *
pfm_find_buffer_fmt(pfm_uuid_t uuid)
{
pfm_buffer_fmt_t * fmt;
spin_lock(&pfm_buffer_fmt_lock);
fmt = __pfm_find_buffer_fmt(uuid);
spin_unlock(&pfm_buffer_fmt_lock);
return fmt;
}
int
pfm_register_buffer_fmt(pfm_buffer_fmt_t *fmt)
{
int ret = 0;
/* some sanity checks */
if (fmt == NULL || fmt->fmt_name == NULL) return -EINVAL;
/* we need at least a handler */
if (fmt->fmt_handler == NULL) return -EINVAL;
/*
* XXX: need check validity of fmt_arg_size
*/
spin_lock(&pfm_buffer_fmt_lock);
if (__pfm_find_buffer_fmt(fmt->fmt_uuid)) {
printk(KERN_ERR "perfmon: duplicate sampling format: %s\n", fmt->fmt_name);
ret = -EBUSY;
goto out;
}
list_add(&fmt->fmt_list, &pfm_buffer_fmt_list);
printk(KERN_INFO "perfmon: added sampling format %s\n", fmt->fmt_name);
out:
spin_unlock(&pfm_buffer_fmt_lock);
return ret;
}
EXPORT_SYMBOL(pfm_register_buffer_fmt);
int
pfm_unregister_buffer_fmt(pfm_uuid_t uuid)
{
pfm_buffer_fmt_t *fmt;
int ret = 0;
spin_lock(&pfm_buffer_fmt_lock);
fmt = __pfm_find_buffer_fmt(uuid);
if (!fmt) {
printk(KERN_ERR "perfmon: cannot unregister format, not found\n");
ret = -EINVAL;
goto out;
}
list_del_init(&fmt->fmt_list);
printk(KERN_INFO "perfmon: removed sampling format: %s\n", fmt->fmt_name);
out:
spin_unlock(&pfm_buffer_fmt_lock);
return ret;
}
EXPORT_SYMBOL(pfm_unregister_buffer_fmt);
extern void update_pal_halt_status(int);
static int
pfm_reserve_session(struct task_struct *task, int is_syswide, unsigned int cpu)
{
unsigned long flags;
/*
* validity checks on cpu_mask have been done upstream
*/
LOCK_PFS(flags);
DPRINT(("in sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
pfm_sessions.pfs_sys_sessions,
pfm_sessions.pfs_task_sessions,
pfm_sessions.pfs_sys_use_dbregs,
is_syswide,
cpu));
if (is_syswide) {
/*
* cannot mix system wide and per-task sessions
*/
if (pfm_sessions.pfs_task_sessions > 0UL) {
DPRINT(("system wide not possible, %u conflicting task_sessions\n",
pfm_sessions.pfs_task_sessions));
goto abort;
}
if (pfm_sessions.pfs_sys_session[cpu]) goto error_conflict;
DPRINT(("reserving system wide session on CPU%u currently on CPU%u\n", cpu, smp_processor_id()));
pfm_sessions.pfs_sys_session[cpu] = task;
pfm_sessions.pfs_sys_sessions++ ;
} else {
if (pfm_sessions.pfs_sys_sessions) goto abort;
pfm_sessions.pfs_task_sessions++;
}
DPRINT(("out sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
pfm_sessions.pfs_sys_sessions,
pfm_sessions.pfs_task_sessions,
pfm_sessions.pfs_sys_use_dbregs,
is_syswide,
cpu));
/*
* disable default_idle() to go to PAL_HALT
*/
update_pal_halt_status(0);
UNLOCK_PFS(flags);
return 0;
error_conflict:
DPRINT(("system wide not possible, conflicting session [%d] on CPU%d\n",
task_pid_nr(pfm_sessions.pfs_sys_session[cpu]),
cpu));
abort:
UNLOCK_PFS(flags);
return -EBUSY;
}
static int
pfm_unreserve_session(pfm_context_t *ctx, int is_syswide, unsigned int cpu)
{
unsigned long flags;
/*
* validity checks on cpu_mask have been done upstream
*/
LOCK_PFS(flags);
DPRINT(("in sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
pfm_sessions.pfs_sys_sessions,
pfm_sessions.pfs_task_sessions,
pfm_sessions.pfs_sys_use_dbregs,
is_syswide,
cpu));
if (is_syswide) {
pfm_sessions.pfs_sys_session[cpu] = NULL;
/*
* would not work with perfmon+more than one bit in cpu_mask
*/
if (ctx && ctx->ctx_fl_using_dbreg) {
if (pfm_sessions.pfs_sys_use_dbregs == 0) {
printk(KERN_ERR "perfmon: invalid release for ctx %p sys_use_dbregs=0\n", ctx);
} else {
pfm_sessions.pfs_sys_use_dbregs--;
}
}
pfm_sessions.pfs_sys_sessions--;
} else {
pfm_sessions.pfs_task_sessions--;
}
DPRINT(("out sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
pfm_sessions.pfs_sys_sessions,
pfm_sessions.pfs_task_sessions,
pfm_sessions.pfs_sys_use_dbregs,
is_syswide,
cpu));
/*
* if possible, enable default_idle() to go into PAL_HALT
*/
if (pfm_sessions.pfs_task_sessions == 0 && pfm_sessions.pfs_sys_sessions == 0)
update_pal_halt_status(1);
UNLOCK_PFS(flags);
return 0;
}
/*
* removes virtual mapping of the sampling buffer.
* IMPORTANT: cannot be called with interrupts disable, e.g. inside
* a PROTECT_CTX() section.
*/
static int
pfm_remove_smpl_mapping(void *vaddr, unsigned long size)
{
struct task_struct *task = current;
int r;
/* sanity checks */
if (task->mm == NULL || size == 0UL || vaddr == NULL) {
printk(KERN_ERR "perfmon: pfm_remove_smpl_mapping [%d] invalid context mm=%p\n", task_pid_nr(task), task->mm);
return -EINVAL;
}
DPRINT(("smpl_vaddr=%p size=%lu\n", vaddr, size));
/*
* does the actual unmapping
*/
r = vm_munmap((unsigned long)vaddr, size);
if (r !=0) {
printk(KERN_ERR "perfmon: [%d] unable to unmap sampling buffer @%p size=%lu\n", task_pid_nr(task), vaddr, size);
}
DPRINT(("do_unmap(%p, %lu)=%d\n", vaddr, size, r));
return 0;
}
/*
* free actual physical storage used by sampling buffer
*/
#if 0
static int
pfm_free_smpl_buffer(pfm_context_t *ctx)
{
pfm_buffer_fmt_t *fmt;
if (ctx->ctx_smpl_hdr == NULL) goto invalid_free;
/*
* we won't use the buffer format anymore
*/
fmt = ctx->ctx_buf_fmt;
DPRINT(("sampling buffer @%p size %lu vaddr=%p\n",
ctx->ctx_smpl_hdr,
ctx->ctx_smpl_size,
ctx->ctx_smpl_vaddr));
pfm_buf_fmt_exit(fmt, current, NULL, NULL);
/*
* free the buffer
*/
pfm_rvfree(ctx->ctx_smpl_hdr, ctx->ctx_smpl_size);
ctx->ctx_smpl_hdr = NULL;
ctx->ctx_smpl_size = 0UL;
return 0;
invalid_free:
printk(KERN_ERR "perfmon: pfm_free_smpl_buffer [%d] no buffer\n", task_pid_nr(current));
return -EINVAL;
}
#endif
static inline void
pfm_exit_smpl_buffer(pfm_buffer_fmt_t *fmt)
{
if (fmt == NULL) return;
pfm_buf_fmt_exit(fmt, current, NULL, NULL);
}
/*
* pfmfs should _never_ be mounted by userland - too much of security hassle,
* no real gain from having the whole whorehouse mounted. So we don't need
* any operations on the root directory. However, we need a non-trivial
* d_name - pfm: will go nicely and kill the special-casing in procfs.
*/
static struct vfsmount *pfmfs_mnt __read_mostly;
static int __init
init_pfm_fs(void)
{
int err = register_filesystem(&pfm_fs_type);
if (!err) {
pfmfs_mnt = kern_mount(&pfm_fs_type);
err = PTR_ERR(pfmfs_mnt);
if (IS_ERR(pfmfs_mnt))
unregister_filesystem(&pfm_fs_type);
else
err = 0;
}
return err;
}
static ssize_t
pfm_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
pfm_context_t *ctx;
pfm_msg_t *msg;
ssize_t ret;
unsigned long flags;
DECLARE_WAITQUEUE(wait, current);
if (PFM_IS_FILE(filp) == 0) {
printk(KERN_ERR "perfmon: pfm_poll: bad magic [%d]\n", task_pid_nr(current));
return -EINVAL;
}
ctx = filp->private_data;
if (ctx == NULL) {
printk(KERN_ERR "perfmon: pfm_read: NULL ctx [%d]\n", task_pid_nr(current));
return -EINVAL;
}
/*
* check even when there is no message
*/
if (size < sizeof(pfm_msg_t)) {
DPRINT(("message is too small ctx=%p (>=%ld)\n", ctx, sizeof(pfm_msg_t)));
return -EINVAL;
}
PROTECT_CTX(ctx, flags);
/*
* put ourselves on the wait queue
*/
add_wait_queue(&ctx->ctx_msgq_wait, &wait);
for(;;) {
/*
* check wait queue
*/
set_current_state(TASK_INTERRUPTIBLE);
DPRINT(("head=%d tail=%d\n", ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
ret = 0;
if(PFM_CTXQ_EMPTY(ctx) == 0) break;
UNPROTECT_CTX(ctx, flags);
/*
* check non-blocking read
*/
ret = -EAGAIN;
if(filp->f_flags & O_NONBLOCK) break;
/*
* check pending signals
*/
if(signal_pending(current)) {
ret = -EINTR;
break;
}
/*
* no message, so wait
*/
schedule();
PROTECT_CTX(ctx, flags);
}
DPRINT(("[%d] back to running ret=%ld\n", task_pid_nr(current), ret));
set_current_state(TASK_RUNNING);
remove_wait_queue(&ctx->ctx_msgq_wait, &wait);
if (ret < 0) goto abort;
ret = -EINVAL;
msg = pfm_get_next_msg(ctx);
if (msg == NULL) {
printk(KERN_ERR "perfmon: pfm_read no msg for ctx=%p [%d]\n", ctx, task_pid_nr(current));
goto abort_locked;
}
DPRINT(("fd=%d type=%d\n", msg->pfm_gen_msg.msg_ctx_fd, msg->pfm_gen_msg.msg_type));
ret = -EFAULT;
if(copy_to_user(buf, msg, sizeof(pfm_msg_t)) == 0) ret = sizeof(pfm_msg_t);
abort_locked:
UNPROTECT_CTX(ctx, flags);
abort:
return ret;
}
static ssize_t
pfm_write(struct file *file, const char __user *ubuf,
size_t size, loff_t *ppos)
{
DPRINT(("pfm_write called\n"));
return -EINVAL;
}
static unsigned int
pfm_poll(struct file *filp, poll_table * wait)
{
pfm_context_t *ctx;
unsigned long flags;
unsigned int mask = 0;
if (PFM_IS_FILE(filp) == 0) {
printk(KERN_ERR "perfmon: pfm_poll: bad magic [%d]\n", task_pid_nr(current));
return 0;
}
ctx = filp->private_data;
if (ctx == NULL) {
printk(KERN_ERR "perfmon: pfm_poll: NULL ctx [%d]\n", task_pid_nr(current));
return 0;
}
DPRINT(("pfm_poll ctx_fd=%d before poll_wait\n", ctx->ctx_fd));
poll_wait(filp, &ctx->ctx_msgq_wait, wait);
PROTECT_CTX(ctx, flags);
if (PFM_CTXQ_EMPTY(ctx) == 0)
mask = POLLIN | POLLRDNORM;
UNPROTECT_CTX(ctx, flags);
DPRINT(("pfm_poll ctx_fd=%d mask=0x%x\n", ctx->ctx_fd, mask));
return mask;
}
static long
pfm_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
DPRINT(("pfm_ioctl called\n"));
return -EINVAL;
}
/*
* interrupt cannot be masked when coming here
*/
static inline int
pfm_do_fasync(int fd, struct file *filp, pfm_context_t *ctx, int on)
{
int ret;
ret = fasync_helper (fd, filp, on, &ctx->ctx_async_queue);
DPRINT(("pfm_fasync called by [%d] on ctx_fd=%d on=%d async_queue=%p ret=%d\n",
task_pid_nr(current),
fd,
on,
ctx->ctx_async_queue, ret));
return ret;
}
static int
pfm_fasync(int fd, struct file *filp, int on)
{
pfm_context_t *ctx;
int ret;
if (PFM_IS_FILE(filp) == 0) {
printk(KERN_ERR "perfmon: pfm_fasync bad magic [%d]\n", task_pid_nr(current));
return -EBADF;
}
ctx = filp->private_data;
if (ctx == NULL) {
printk(KERN_ERR "perfmon: pfm_fasync NULL ctx [%d]\n", task_pid_nr(current));
return -EBADF;
}
/*
* we cannot mask interrupts during this call because this may
* may go to sleep if memory is not readily avalaible.
*
* We are protected from the conetxt disappearing by the get_fd()/put_fd()
* done in caller. Serialization of this function is ensured by caller.
*/
ret = pfm_do_fasync(fd, filp, ctx, on);
DPRINT(("pfm_fasync called on ctx_fd=%d on=%d async_queue=%p ret=%d\n",
fd,
on,
ctx->ctx_async_queue, ret));
return ret;
}
#ifdef CONFIG_SMP
/*
* this function is exclusively called from pfm_close().
* The context is not protected at that time, nor are interrupts
* on the remote CPU. That's necessary to avoid deadlocks.
*/
static void
pfm_syswide_force_stop(void *info)
{
pfm_context_t *ctx = (pfm_context_t *)info;
struct pt_regs *regs = task_pt_regs(current);
struct task_struct *owner;
unsigned long flags;
int ret;
if (ctx->ctx_cpu != smp_processor_id()) {
printk(KERN_ERR "perfmon: pfm_syswide_force_stop for CPU%d but on CPU%d\n",
ctx->ctx_cpu,
smp_processor_id());
return;
}
owner = GET_PMU_OWNER();
if (owner != ctx->ctx_task) {
printk(KERN_ERR "perfmon: pfm_syswide_force_stop CPU%d unexpected owner [%d] instead of [%d]\n",
smp_processor_id(),
task_pid_nr(owner), task_pid_nr(ctx->ctx_task));
return;
}
if (GET_PMU_CTX() != ctx) {
printk(KERN_ERR "perfmon: pfm_syswide_force_stop CPU%d unexpected ctx %p instead of %p\n",
smp_processor_id(),
GET_PMU_CTX(), ctx);
return;
}
DPRINT(("on CPU%d forcing system wide stop for [%d]\n", smp_processor_id(), task_pid_nr(ctx->ctx_task)));
/*
* the context is already protected in pfm_close(), we simply
* need to mask interrupts to avoid a PMU interrupt race on
* this CPU
*/
local_irq_save(flags);
ret = pfm_context_unload(ctx, NULL, 0, regs);
if (ret) {
DPRINT(("context_unload returned %d\n", ret));
}
/*
* unmask interrupts, PMU interrupts are now spurious here
*/
local_irq_restore(flags);
}
static void
pfm_syswide_cleanup_other_cpu(pfm_context_t *ctx)
{
int ret;
DPRINT(("calling CPU%d for cleanup\n", ctx->ctx_cpu));
ret = smp_call_function_single(ctx->ctx_cpu, pfm_syswide_force_stop, ctx, 1);
DPRINT(("called CPU%d for cleanup ret=%d\n", ctx->ctx_cpu, ret));
}
#endif /* CONFIG_SMP */
/*
* called for each close(). Partially free resources.
* When caller is self-monitoring, the context is unloaded.
*/
static int
pfm_flush(struct file *filp, fl_owner_t id)
{
pfm_context_t *ctx;
struct task_struct *task;
struct pt_regs *regs;
unsigned long flags;
unsigned long smpl_buf_size = 0UL;
void *smpl_buf_vaddr = NULL;
int state, is_system;
if (PFM_IS_FILE(filp) == 0) {
DPRINT(("bad magic for\n"));
return -EBADF;
}
ctx = filp->private_data;
if (ctx == NULL) {
printk(KERN_ERR "perfmon: pfm_flush: NULL ctx [%d]\n", task_pid_nr(current));
return -EBADF;
}
/*
* remove our file from the async queue, if we use this mode.
* This can be done without the context being protected. We come
* here when the context has become unreachable by other tasks.
*
* We may still have active monitoring at this point and we may
* end up in pfm_overflow_handler(). However, fasync_helper()
* operates with interrupts disabled and it cleans up the
* queue. If the PMU handler is called prior to entering
* fasync_helper() then it will send a signal. If it is
* invoked after, it will find an empty queue and no
* signal will be sent. In both case, we are safe
*/
PROTECT_CTX(ctx, flags);
state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
task = PFM_CTX_TASK(ctx);
regs = task_pt_regs(task);
DPRINT(("ctx_state=%d is_current=%d\n",
state,
task == current ? 1 : 0));
/*
* if state == UNLOADED, then task is NULL
*/
/*
* we must stop and unload because we are losing access to the context.
*/
if (task == current) {
#ifdef CONFIG_SMP
/*
* the task IS the owner but it migrated to another CPU: that's bad
* but we must handle this cleanly. Unfortunately, the kernel does
* not provide a mechanism to block migration (while the context is loaded).
*
* We need to release the resource on the ORIGINAL cpu.
*/
if (is_system && ctx->ctx_cpu != smp_processor_id()) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
/*
* keep context protected but unmask interrupt for IPI
*/
local_irq_restore(flags);
pfm_syswide_cleanup_other_cpu(ctx);
/*
* restore interrupt masking
*/
local_irq_save(flags);
/*
* context is unloaded at this point
*/
} else
#endif /* CONFIG_SMP */
{
DPRINT(("forcing unload\n"));
/*
* stop and unload, returning with state UNLOADED
* and session unreserved.
*/
pfm_context_unload(ctx, NULL, 0, regs);
DPRINT(("ctx_state=%d\n", ctx->ctx_state));
}
}
/*
* remove virtual mapping, if any, for the calling task.
* cannot reset ctx field until last user is calling close().
*
* ctx_smpl_vaddr must never be cleared because it is needed
* by every task with access to the context
*
* When called from do_exit(), the mm context is gone already, therefore
* mm is NULL, i.e., the VMA is already gone and we do not have to
* do anything here
*/
if (ctx->ctx_smpl_vaddr && current->mm) {
smpl_buf_vaddr = ctx->ctx_smpl_vaddr;
smpl_buf_size = ctx->ctx_smpl_size;
}
UNPROTECT_CTX(ctx, flags);
/*
* if there was a mapping, then we systematically remove it
* at this point. Cannot be done inside critical section
* because some VM function reenables interrupts.
*
*/
if (smpl_buf_vaddr) pfm_remove_smpl_mapping(smpl_buf_vaddr, smpl_buf_size);
return 0;
}
/*
* called either on explicit close() or from exit_files().
* Only the LAST user of the file gets to this point, i.e., it is
* called only ONCE.
*
* IMPORTANT: we get called ONLY when the refcnt on the file gets to zero
* (fput()),i.e, last task to access the file. Nobody else can access the
* file at this point.
*
* When called from exit_files(), the VMA has been freed because exit_mm()
* is executed before exit_files().
*
* When called from exit_files(), the current task is not yet ZOMBIE but we
* flush the PMU state to the context.
*/
static int
pfm_close(struct inode *inode, struct file *filp)
{
pfm_context_t *ctx;
struct task_struct *task;
struct pt_regs *regs;
DECLARE_WAITQUEUE(wait, current);
unsigned long flags;
unsigned long smpl_buf_size = 0UL;
void *smpl_buf_addr = NULL;
int free_possible = 1;
int state, is_system;
DPRINT(("pfm_close called private=%p\n", filp->private_data));
if (PFM_IS_FILE(filp) == 0) {
DPRINT(("bad magic\n"));
return -EBADF;
}
ctx = filp->private_data;
if (ctx == NULL) {
printk(KERN_ERR "perfmon: pfm_close: NULL ctx [%d]\n", task_pid_nr(current));
return -EBADF;
}
PROTECT_CTX(ctx, flags);
state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
task = PFM_CTX_TASK(ctx);
regs = task_pt_regs(task);
DPRINT(("ctx_state=%d is_current=%d\n",
state,
task == current ? 1 : 0));
/*
* if task == current, then pfm_flush() unloaded the context
*/
if (state == PFM_CTX_UNLOADED) goto doit;
/*
* context is loaded/masked and task != current, we need to
* either force an unload or go zombie
*/
/*
* The task is currently blocked or will block after an overflow.
* we must force it to wakeup to get out of the
* MASKED state and transition to the unloaded state by itself.
*
* This situation is only possible for per-task mode
*/
if (state == PFM_CTX_MASKED && CTX_OVFL_NOBLOCK(ctx) == 0) {
/*
* set a "partial" zombie state to be checked
* upon return from down() in pfm_handle_work().
*
* We cannot use the ZOMBIE state, because it is checked
* by pfm_load_regs() which is called upon wakeup from down().
* In such case, it would free the context and then we would
* return to pfm_handle_work() which would access the
* stale context. Instead, we set a flag invisible to pfm_load_regs()
* but visible to pfm_handle_work().
*
* For some window of time, we have a zombie context with
* ctx_state = MASKED and not ZOMBIE
*/
ctx->ctx_fl_going_zombie = 1;
/*
* force task to wake up from MASKED state
*/
complete(&ctx->ctx_restart_done);
DPRINT(("waking up ctx_state=%d\n", state));
/*
* put ourself to sleep waiting for the other
* task to report completion
*
* the context is protected by mutex, therefore there
* is no risk of being notified of completion before
* begin actually on the waitq.
*/
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&ctx->ctx_zombieq, &wait);
UNPROTECT_CTX(ctx, flags);
/*
* XXX: check for signals :
* - ok for explicit close
* - not ok when coming from exit_files()
*/
schedule();
PROTECT_CTX(ctx, flags);
remove_wait_queue(&ctx->ctx_zombieq, &wait);
set_current_state(TASK_RUNNING);
/*
* context is unloaded at this point
*/
DPRINT(("after zombie wakeup ctx_state=%d for\n", state));
}
else if (task != current) {
#ifdef CONFIG_SMP
/*
* switch context to zombie state
*/
ctx->ctx_state = PFM_CTX_ZOMBIE;
DPRINT(("zombie ctx for [%d]\n", task_pid_nr(task)));
/*
* cannot free the context on the spot. deferred until
* the task notices the ZOMBIE state
*/
free_possible = 0;
#else
pfm_context_unload(ctx, NULL, 0, regs);
#endif
}
doit:
/* reload state, may have changed during opening of critical section */
state = ctx->ctx_state;
/*
* the context is still attached to a task (possibly current)
* we cannot destroy it right now
*/
/*
* we must free the sampling buffer right here because
* we cannot rely on it being cleaned up later by the
* monitored task. It is not possible to free vmalloc'ed
* memory in pfm_load_regs(). Instead, we remove the buffer
* now. should there be subsequent PMU overflow originally
* meant for sampling, the will be converted to spurious
* and that's fine because the monitoring tools is gone anyway.
*/
if (ctx->ctx_smpl_hdr) {
smpl_buf_addr = ctx->ctx_smpl_hdr;
smpl_buf_size = ctx->ctx_smpl_size;
/* no more sampling */
ctx->ctx_smpl_hdr = NULL;
ctx->ctx_fl_is_sampling = 0;
}
DPRINT(("ctx_state=%d free_possible=%d addr=%p size=%lu\n",
state,
free_possible,
smpl_buf_addr,
smpl_buf_size));
if (smpl_buf_addr) pfm_exit_smpl_buffer(ctx->ctx_buf_fmt);
/*
* UNLOADED that the session has already been unreserved.
*/
if (state == PFM_CTX_ZOMBIE) {
pfm_unreserve_session(ctx, ctx->ctx_fl_system , ctx->ctx_cpu);
}
/*
* disconnect file descriptor from context must be done
* before we unlock.
*/
filp->private_data = NULL;
/*
* if we free on the spot, the context is now completely unreachable
* from the callers side. The monitored task side is also cut, so we
* can freely cut.
*
* If we have a deferred free, only the caller side is disconnected.
*/
UNPROTECT_CTX(ctx, flags);
/*
* All memory free operations (especially for vmalloc'ed memory)
* MUST be done with interrupts ENABLED.
*/
if (smpl_buf_addr) pfm_rvfree(smpl_buf_addr, smpl_buf_size);
/*
* return the memory used by the context
*/
if (free_possible) pfm_context_free(ctx);
return 0;
}
static int
pfm_no_open(struct inode *irrelevant, struct file *dontcare)
{
DPRINT(("pfm_no_open called\n"));
return -ENXIO;
}
static const struct file_operations pfm_file_ops = {
.llseek = no_llseek,
.read = pfm_read,
.write = pfm_write,
.poll = pfm_poll,
.unlocked_ioctl = pfm_ioctl,
.open = pfm_no_open, /* special open code to disallow open via /proc */
.fasync = pfm_fasync,
.release = pfm_close,
.flush = pfm_flush
};
static int
pfmfs_delete_dentry(const struct dentry *dentry)
{
return 1;
}
static char *pfmfs_dname(struct dentry *dentry, char *buffer, int buflen)
{
return dynamic_dname(dentry, buffer, buflen, "pfm:[%lu]",
dentry->d_inode->i_ino);
}
static const struct dentry_operations pfmfs_dentry_operations = {
.d_delete = pfmfs_delete_dentry,
.d_dname = pfmfs_dname,
};
static struct file *
pfm_alloc_file(pfm_context_t *ctx)
{
struct file *file;
struct inode *inode;
struct path path;
struct qstr this = { .name = "" };
/*
* allocate a new inode
*/
inode = new_inode(pfmfs_mnt->mnt_sb);
if (!inode)
return ERR_PTR(-ENOMEM);
DPRINT(("new inode ino=%ld @%p\n", inode->i_ino, inode));
inode->i_mode = S_IFCHR|S_IRUGO;
inode->i_uid = current_fsuid();
inode->i_gid = current_fsgid();
/*
* allocate a new dcache entry
*/
path.dentry = d_alloc(pfmfs_mnt->mnt_root, &this);
if (!path.dentry) {
iput(inode);
return ERR_PTR(-ENOMEM);
}
path.mnt = mntget(pfmfs_mnt);
d_add(path.dentry, inode);
file = alloc_file(&path, FMODE_READ, &pfm_file_ops);
if (!file) {
path_put(&path);
return ERR_PTR(-ENFILE);
}
file->f_flags = O_RDONLY;
file->private_data = ctx;
return file;
}
static int
pfm_remap_buffer(struct vm_area_struct *vma, unsigned long buf, unsigned long addr, unsigned long size)
{
DPRINT(("CPU%d buf=0x%lx addr=0x%lx size=%ld\n", smp_processor_id(), buf, addr, size));
while (size > 0) {
unsigned long pfn = ia64_tpa(buf) >> PAGE_SHIFT;
if (remap_pfn_range(vma, addr, pfn, PAGE_SIZE, PAGE_READONLY))
return -ENOMEM;
addr += PAGE_SIZE;
buf += PAGE_SIZE;
size -= PAGE_SIZE;
}
return 0;
}
/*
* allocate a sampling buffer and remaps it into the user address space of the task
*/
static int
pfm_smpl_buffer_alloc(struct task_struct *task, struct file *filp, pfm_context_t *ctx, unsigned long rsize, void **user_vaddr)
{
struct mm_struct *mm = task->mm;
struct vm_area_struct *vma = NULL;
unsigned long size;
void *smpl_buf;
/*
* the fixed header + requested size and align to page boundary
*/
size = PAGE_ALIGN(rsize);
DPRINT(("sampling buffer rsize=%lu size=%lu bytes\n", rsize, size));
/*
* check requested size to avoid Denial-of-service attacks
* XXX: may have to refine this test
* Check against address space limit.
*
* if ((mm->total_vm << PAGE_SHIFT) + len> task->rlim[RLIMIT_AS].rlim_cur)
* return -ENOMEM;
*/
if (size > task_rlimit(task, RLIMIT_MEMLOCK))
return -ENOMEM;
/*
* We do the easy to undo allocations first.
*
* pfm_rvmalloc(), clears the buffer, so there is no leak
*/
smpl_buf = pfm_rvmalloc(size);
if (smpl_buf == NULL) {
DPRINT(("Can't allocate sampling buffer\n"));
return -ENOMEM;
}
DPRINT(("smpl_buf @%p\n", smpl_buf));
/* allocate vma */
vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (!vma) {
DPRINT(("Cannot allocate vma\n"));
goto error_kmem;
}
INIT_LIST_HEAD(&vma->anon_vma_chain);
/*
* partially initialize the vma for the sampling buffer
*/
vma->vm_mm = mm;
vma->vm_file = filp;
vma->vm_flags = VM_READ| VM_MAYREAD |VM_RESERVED;
vma->vm_page_prot = PAGE_READONLY; /* XXX may need to change */
/*
* Now we have everything we need and we can initialize
* and connect all the data structures
*/
ctx->ctx_smpl_hdr = smpl_buf;
ctx->ctx_smpl_size = size; /* aligned size */
/*
* Let's do the difficult operations next.
*
* now we atomically find some area in the address space and
* remap the buffer in it.
*/
down_write(&task->mm->mmap_sem);
/* find some free area in address space, must have mmap sem held */
vma->vm_start = pfm_get_unmapped_area(NULL, 0, size, 0, MAP_PRIVATE|MAP_ANONYMOUS, 0);
if (vma->vm_start == 0UL) {
DPRINT(("Cannot find unmapped area for size %ld\n", size));
up_write(&task->mm->mmap_sem);
goto error;
}
vma->vm_end = vma->vm_start + size;
vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
DPRINT(("aligned size=%ld, hdr=%p mapped @0x%lx\n", size, ctx->ctx_smpl_hdr, vma->vm_start));
/* can only be applied to current task, need to have the mm semaphore held when called */
if (pfm_remap_buffer(vma, (unsigned long)smpl_buf, vma->vm_start, size)) {
DPRINT(("Can't remap buffer\n"));
up_write(&task->mm->mmap_sem);
goto error;
}
get_file(filp);
/*
* now insert the vma in the vm list for the process, must be
* done with mmap lock held
*/
insert_vm_struct(mm, vma);
mm->total_vm += size >> PAGE_SHIFT;
vm_stat_account(vma->vm_mm, vma->vm_flags, vma->vm_file,
vma_pages(vma));
up_write(&task->mm->mmap_sem);
/*
* keep track of user level virtual address
*/
ctx->ctx_smpl_vaddr = (void *)vma->vm_start;
*(unsigned long *)user_vaddr = vma->vm_start;
return 0;
error:
kmem_cache_free(vm_area_cachep, vma);
error_kmem:
pfm_rvfree(smpl_buf, size);
return -ENOMEM;
}
/*
* XXX: do something better here
*/
static int
pfm_bad_permissions(struct task_struct *task)
{
const struct cred *tcred;
uid_t uid = current_uid();
gid_t gid = current_gid();
int ret;
rcu_read_lock();
tcred = __task_cred(task);
/* inspired by ptrace_attach() */
DPRINT(("cur: uid=%d gid=%d task: euid=%d suid=%d uid=%d egid=%d sgid=%d\n",
uid,
gid,
tcred->euid,
tcred->suid,
tcred->uid,
tcred->egid,
tcred->sgid));
ret = ((uid != tcred->euid)
|| (uid != tcred->suid)
|| (uid != tcred->uid)
|| (gid != tcred->egid)
|| (gid != tcred->sgid)
|| (gid != tcred->gid)) && !capable(CAP_SYS_PTRACE);
rcu_read_unlock();
return ret;
}
static int
pfarg_is_sane(struct task_struct *task, pfarg_context_t *pfx)
{
int ctx_flags;
/* valid signal */
ctx_flags = pfx->ctx_flags;
if (ctx_flags & PFM_FL_SYSTEM_WIDE) {
/*
* cannot block in this mode
*/
if (ctx_flags & PFM_FL_NOTIFY_BLOCK) {
DPRINT(("cannot use blocking mode when in system wide monitoring\n"));
return -EINVAL;
}
} else {
}
/* probably more to add here */
return 0;
}
static int
pfm_setup_buffer_fmt(struct task_struct *task, struct file *filp, pfm_context_t *ctx, unsigned int ctx_flags,
unsigned int cpu, pfarg_context_t *arg)
{
pfm_buffer_fmt_t *fmt = NULL;
unsigned long size = 0UL;
void *uaddr = NULL;
void *fmt_arg = NULL;
int ret = 0;
#define PFM_CTXARG_BUF_ARG(a) (pfm_buffer_fmt_t *)(a+1)
/* invoke and lock buffer format, if found */
fmt = pfm_find_buffer_fmt(arg->ctx_smpl_buf_id);
if (fmt == NULL) {
DPRINT(("[%d] cannot find buffer format\n", task_pid_nr(task)));
return -EINVAL;
}
/*
* buffer argument MUST be contiguous to pfarg_context_t
*/
if (fmt->fmt_arg_size) fmt_arg = PFM_CTXARG_BUF_ARG(arg);
ret = pfm_buf_fmt_validate(fmt, task, ctx_flags, cpu, fmt_arg);
DPRINT(("[%d] after validate(0x%x,%d,%p)=%d\n", task_pid_nr(task), ctx_flags, cpu, fmt_arg, ret));
if (ret) goto error;
/* link buffer format and context */
ctx->ctx_buf_fmt = fmt;
ctx->ctx_fl_is_sampling = 1; /* assume record() is defined */
/*
* check if buffer format wants to use perfmon buffer allocation/mapping service
*/
ret = pfm_buf_fmt_getsize(fmt, task, ctx_flags, cpu, fmt_arg, &size);
if (ret) goto error;
if (size) {
/*
* buffer is always remapped into the caller's address space
*/
ret = pfm_smpl_buffer_alloc(current, filp, ctx, size, &uaddr);
if (ret) goto error;
/* keep track of user address of buffer */
arg->ctx_smpl_vaddr = uaddr;
}
ret = pfm_buf_fmt_init(fmt, task, ctx->ctx_smpl_hdr, ctx_flags, cpu, fmt_arg);
error:
return ret;
}
static void
pfm_reset_pmu_state(pfm_context_t *ctx)
{
int i;
/*
* install reset values for PMC.
*/
for (i=1; PMC_IS_LAST(i) == 0; i++) {
if (PMC_IS_IMPL(i) == 0) continue;
ctx->ctx_pmcs[i] = PMC_DFL_VAL(i);
DPRINT(("pmc[%d]=0x%lx\n", i, ctx->ctx_pmcs[i]));
}
/*
* PMD registers are set to 0UL when the context in memset()
*/
/*
* On context switched restore, we must restore ALL pmc and ALL pmd even
* when they are not actively used by the task. In UP, the incoming process
* may otherwise pick up left over PMC, PMD state from the previous process.
* As opposed to PMD, stale PMC can cause harm to the incoming
* process because they may change what is being measured.
* Therefore, we must systematically reinstall the entire
* PMC state. In SMP, the same thing is possible on the
* same CPU but also on between 2 CPUs.
*
* The problem with PMD is information leaking especially
* to user level when psr.sp=0
*
* There is unfortunately no easy way to avoid this problem
* on either UP or SMP. This definitively slows down the
* pfm_load_regs() function.
*/
/*
* bitmask of all PMCs accessible to this context
*
* PMC0 is treated differently.
*/
ctx->ctx_all_pmcs[0] = pmu_conf->impl_pmcs[0] & ~0x1;
/*
* bitmask of all PMDs that are accessible to this context
*/
ctx->ctx_all_pmds[0] = pmu_conf->impl_pmds[0];
DPRINT(("<%d> all_pmcs=0x%lx all_pmds=0x%lx\n", ctx->ctx_fd, ctx->ctx_all_pmcs[0],ctx->ctx_all_pmds[0]));
/*
* useful in case of re-enable after disable
*/
ctx->ctx_used_ibrs[0] = 0UL;
ctx->ctx_used_dbrs[0] = 0UL;
}
static int
pfm_ctx_getsize(void *arg, size_t *sz)
{
pfarg_context_t *req = (pfarg_context_t *)arg;
pfm_buffer_fmt_t *fmt;
*sz = 0;
if (!pfm_uuid_cmp(req->ctx_smpl_buf_id, pfm_null_uuid)) return 0;
fmt = pfm_find_buffer_fmt(req->ctx_smpl_buf_id);
if (fmt == NULL) {
DPRINT(("cannot find buffer format\n"));
return -EINVAL;
}
/* get just enough to copy in user parameters */
*sz = fmt->fmt_arg_size;
DPRINT(("arg_size=%lu\n", *sz));
return 0;
}
/*
* cannot attach if :
* - kernel task
* - task not owned by caller
* - task incompatible with context mode
*/
static int
pfm_task_incompatible(pfm_context_t *ctx, struct task_struct *task)
{
/*
* no kernel task or task not owner by caller
*/
if (task->mm == NULL) {
DPRINT(("task [%d] has not memory context (kernel thread)\n", task_pid_nr(task)));
return -EPERM;
}
if (pfm_bad_permissions(task)) {
DPRINT(("no permission to attach to [%d]\n", task_pid_nr(task)));
return -EPERM;
}
/*
* cannot block in self-monitoring mode
*/
if (CTX_OVFL_NOBLOCK(ctx) == 0 && task == current) {
DPRINT(("cannot load a blocking context on self for [%d]\n", task_pid_nr(task)));
return -EINVAL;
}
if (task->exit_state == EXIT_ZOMBIE) {
DPRINT(("cannot attach to zombie task [%d]\n", task_pid_nr(task)));
return -EBUSY;
}
/*
* always ok for self
*/
if (task == current) return 0;
if (!task_is_stopped_or_traced(task)) {
DPRINT(("cannot attach to non-stopped task [%d] state=%ld\n", task_pid_nr(task), task->state));
return -EBUSY;
}
/*
* make sure the task is off any CPU
*/
wait_task_inactive(task, 0);
/* more to come... */
return 0;
}
static int
pfm_get_task(pfm_context_t *ctx, pid_t pid, struct task_struct **task)
{
struct task_struct *p = current;
int ret;
/* XXX: need to add more checks here */
if (pid < 2) return -EPERM;
if (pid != task_pid_vnr(current)) {
read_lock(&tasklist_lock);
p = find_task_by_vpid(pid);
/* make sure task cannot go away while we operate on it */
if (p) get_task_struct(p);
read_unlock(&tasklist_lock);
if (p == NULL) return -ESRCH;
}
ret = pfm_task_incompatible(ctx, p);
if (ret == 0) {
*task = p;
} else if (p != current) {
pfm_put_task(p);
}
return ret;
}
static int
pfm_context_create(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
pfarg_context_t *req = (pfarg_context_t *)arg;
struct file *filp;
struct path path;
int ctx_flags;
int fd;
int ret;
/* let's check the arguments first */
ret = pfarg_is_sane(current, req);
if (ret < 0)
return ret;
ctx_flags = req->ctx_flags;
ret = -ENOMEM;
fd = get_unused_fd();
if (fd < 0)
return fd;
ctx = pfm_context_alloc(ctx_flags);
if (!ctx)
goto error;
filp = pfm_alloc_file(ctx);
if (IS_ERR(filp)) {
ret = PTR_ERR(filp);
goto error_file;
}
req->ctx_fd = ctx->ctx_fd = fd;
/*
* does the user want to sample?
*/
if (pfm_uuid_cmp(req->ctx_smpl_buf_id, pfm_null_uuid)) {
ret = pfm_setup_buffer_fmt(current, filp, ctx, ctx_flags, 0, req);
if (ret)
goto buffer_error;
}
DPRINT(("ctx=%p flags=0x%x system=%d notify_block=%d excl_idle=%d no_msg=%d ctx_fd=%d\n",
ctx,
ctx_flags,
ctx->ctx_fl_system,
ctx->ctx_fl_block,
ctx->ctx_fl_excl_idle,
ctx->ctx_fl_no_msg,
ctx->ctx_fd));
/*
* initialize soft PMU state
*/
pfm_reset_pmu_state(ctx);
fd_install(fd, filp);
return 0;
buffer_error:
path = filp->f_path;
put_filp(filp);
path_put(&path);
if (ctx->ctx_buf_fmt) {
pfm_buf_fmt_exit(ctx->ctx_buf_fmt, current, NULL, regs);
}
error_file:
pfm_context_free(ctx);
error:
put_unused_fd(fd);
return ret;
}
static inline unsigned long
pfm_new_counter_value (pfm_counter_t *reg, int is_long_reset)
{
unsigned long val = is_long_reset ? reg->long_reset : reg->short_reset;
unsigned long new_seed, old_seed = reg->seed, mask = reg->mask;
extern unsigned long carta_random32 (unsigned long seed);
if (reg->flags & PFM_REGFL_RANDOM) {
new_seed = carta_random32(old_seed);
val -= (old_seed & mask); /* counter values are negative numbers! */
if ((mask >> 32) != 0)
/* construct a full 64-bit random value: */
new_seed |= carta_random32(old_seed >> 32) << 32;
reg->seed = new_seed;
}
reg->lval = val;
return val;
}
static void
pfm_reset_regs_masked(pfm_context_t *ctx, unsigned long *ovfl_regs, int is_long_reset)
{
unsigned long mask = ovfl_regs[0];
unsigned long reset_others = 0UL;
unsigned long val;
int i;
/*
* now restore reset value on sampling overflowed counters
*/
mask >>= PMU_FIRST_COUNTER;
for(i = PMU_FIRST_COUNTER; mask; i++, mask >>= 1) {
if ((mask & 0x1UL) == 0UL) continue;
ctx->ctx_pmds[i].val = val = pfm_new_counter_value(ctx->ctx_pmds+ i, is_long_reset);
reset_others |= ctx->ctx_pmds[i].reset_pmds[0];
DPRINT_ovfl((" %s reset ctx_pmds[%d]=%lx\n", is_long_reset ? "long" : "short", i, val));
}
/*
* Now take care of resetting the other registers
*/
for(i = 0; reset_others; i++, reset_others >>= 1) {
if ((reset_others & 0x1) == 0) continue;
ctx->ctx_pmds[i].val = val = pfm_new_counter_value(ctx->ctx_pmds + i, is_long_reset);
DPRINT_ovfl(("%s reset_others pmd[%d]=%lx\n",
is_long_reset ? "long" : "short", i, val));
}
}
static void
pfm_reset_regs(pfm_context_t *ctx, unsigned long *ovfl_regs, int is_long_reset)
{
unsigned long mask = ovfl_regs[0];
unsigned long reset_others = 0UL;
unsigned long val;
int i;
DPRINT_ovfl(("ovfl_regs=0x%lx is_long_reset=%d\n", ovfl_regs[0], is_long_reset));
if (ctx->ctx_state == PFM_CTX_MASKED) {
pfm_reset_regs_masked(ctx, ovfl_regs, is_long_reset);
return;
}
/*
* now restore reset value on sampling overflowed counters
*/
mask >>= PMU_FIRST_COUNTER;
for(i = PMU_FIRST_COUNTER; mask; i++, mask >>= 1) {
if ((mask & 0x1UL) == 0UL) continue;
val = pfm_new_counter_value(ctx->ctx_pmds+ i, is_long_reset);
reset_others |= ctx->ctx_pmds[i].reset_pmds[0];
DPRINT_ovfl((" %s reset ctx_pmds[%d]=%lx\n", is_long_reset ? "long" : "short", i, val));
pfm_write_soft_counter(ctx, i, val);
}
/*
* Now take care of resetting the other registers
*/
for(i = 0; reset_others; i++, reset_others >>= 1) {
if ((reset_others & 0x1) == 0) continue;
val = pfm_new_counter_value(ctx->ctx_pmds + i, is_long_reset);
if (PMD_IS_COUNTING(i)) {
pfm_write_soft_counter(ctx, i, val);
} else {
ia64_set_pmd(i, val);
}
DPRINT_ovfl(("%s reset_others pmd[%d]=%lx\n",
is_long_reset ? "long" : "short", i, val));
}
ia64_srlz_d();
}
static int
pfm_write_pmcs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task;
pfarg_reg_t *req = (pfarg_reg_t *)arg;
unsigned long value, pmc_pm;
unsigned long smpl_pmds, reset_pmds, impl_pmds;
unsigned int cnum, reg_flags, flags, pmc_type;
int i, can_access_pmu = 0, is_loaded, is_system, expert_mode;
int is_monitor, is_counting, state;
int ret = -EINVAL;
pfm_reg_check_t wr_func;
#define PFM_CHECK_PMC_PM(x, y, z) ((x)->ctx_fl_system ^ PMC_PM(y, z))
state = ctx->ctx_state;
is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
is_system = ctx->ctx_fl_system;
task = ctx->ctx_task;
impl_pmds = pmu_conf->impl_pmds[0];
if (state == PFM_CTX_ZOMBIE) return -EINVAL;
if (is_loaded) {
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (is_system && ctx->ctx_cpu != smp_processor_id()) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
}
expert_mode = pfm_sysctl.expert_mode;
for (i = 0; i < count; i++, req++) {
cnum = req->reg_num;
reg_flags = req->reg_flags;
value = req->reg_value;
smpl_pmds = req->reg_smpl_pmds[0];
reset_pmds = req->reg_reset_pmds[0];
flags = 0;
if (cnum >= PMU_MAX_PMCS) {
DPRINT(("pmc%u is invalid\n", cnum));
goto error;
}
pmc_type = pmu_conf->pmc_desc[cnum].type;
pmc_pm = (value >> pmu_conf->pmc_desc[cnum].pm_pos) & 0x1;
is_counting = (pmc_type & PFM_REG_COUNTING) == PFM_REG_COUNTING ? 1 : 0;
is_monitor = (pmc_type & PFM_REG_MONITOR) == PFM_REG_MONITOR ? 1 : 0;
/*
* we reject all non implemented PMC as well
* as attempts to modify PMC[0-3] which are used
* as status registers by the PMU
*/
if ((pmc_type & PFM_REG_IMPL) == 0 || (pmc_type & PFM_REG_CONTROL) == PFM_REG_CONTROL) {
DPRINT(("pmc%u is unimplemented or no-access pmc_type=%x\n", cnum, pmc_type));
goto error;
}
wr_func = pmu_conf->pmc_desc[cnum].write_check;
/*
* If the PMC is a monitor, then if the value is not the default:
* - system-wide session: PMCx.pm=1 (privileged monitor)
* - per-task : PMCx.pm=0 (user monitor)
*/
if (is_monitor && value != PMC_DFL_VAL(cnum) && is_system ^ pmc_pm) {
DPRINT(("pmc%u pmc_pm=%lu is_system=%d\n",
cnum,
pmc_pm,
is_system));
goto error;
}
if (is_counting) {
/*
* enforce generation of overflow interrupt. Necessary on all
* CPUs.
*/
value |= 1 << PMU_PMC_OI;
if (reg_flags & PFM_REGFL_OVFL_NOTIFY) {
flags |= PFM_REGFL_OVFL_NOTIFY;
}
if (reg_flags & PFM_REGFL_RANDOM) flags |= PFM_REGFL_RANDOM;
/* verify validity of smpl_pmds */
if ((smpl_pmds & impl_pmds) != smpl_pmds) {
DPRINT(("invalid smpl_pmds 0x%lx for pmc%u\n", smpl_pmds, cnum));
goto error;
}
/* verify validity of reset_pmds */
if ((reset_pmds & impl_pmds) != reset_pmds) {
DPRINT(("invalid reset_pmds 0x%lx for pmc%u\n", reset_pmds, cnum));
goto error;
}
} else {
if (reg_flags & (PFM_REGFL_OVFL_NOTIFY|PFM_REGFL_RANDOM)) {
DPRINT(("cannot set ovfl_notify or random on pmc%u\n", cnum));
goto error;
}
/* eventid on non-counting monitors are ignored */
}
/*
* execute write checker, if any
*/
if (likely(expert_mode == 0 && wr_func)) {
ret = (*wr_func)(task, ctx, cnum, &value, regs);
if (ret) goto error;
ret = -EINVAL;
}
/*
* no error on this register
*/
PFM_REG_RETFLAG_SET(req->reg_flags, 0);
/*
* Now we commit the changes to the software state
*/
/*
* update overflow information
*/
if (is_counting) {
/*
* full flag update each time a register is programmed
*/
ctx->ctx_pmds[cnum].flags = flags;
ctx->ctx_pmds[cnum].reset_pmds[0] = reset_pmds;
ctx->ctx_pmds[cnum].smpl_pmds[0] = smpl_pmds;
ctx->ctx_pmds[cnum].eventid = req->reg_smpl_eventid;
/*
* Mark all PMDS to be accessed as used.
*
* We do not keep track of PMC because we have to
* systematically restore ALL of them.
*
* We do not update the used_monitors mask, because
* if we have not programmed them, then will be in
* a quiescent state, therefore we will not need to
* mask/restore then when context is MASKED.
*/
CTX_USED_PMD(ctx, reset_pmds);
CTX_USED_PMD(ctx, smpl_pmds);
/*
* make sure we do not try to reset on
* restart because we have established new values
*/
if (state == PFM_CTX_MASKED) ctx->ctx_ovfl_regs[0] &= ~1UL << cnum;
}
/*
* Needed in case the user does not initialize the equivalent
* PMD. Clearing is done indirectly via pfm_reset_pmu_state() so there is no
* possible leak here.
*/
CTX_USED_PMD(ctx, pmu_conf->pmc_desc[cnum].dep_pmd[0]);
/*
* keep track of the monitor PMC that we are using.
* we save the value of the pmc in ctx_pmcs[] and if
* the monitoring is not stopped for the context we also
* place it in the saved state area so that it will be
* picked up later by the context switch code.
*
* The value in ctx_pmcs[] can only be changed in pfm_write_pmcs().
*
* The value in th_pmcs[] may be modified on overflow, i.e., when
* monitoring needs to be stopped.
*/
if (is_monitor) CTX_USED_MONITOR(ctx, 1UL << cnum);
/*
* update context state
*/
ctx->ctx_pmcs[cnum] = value;
if (is_loaded) {
/*
* write thread state
*/
if (is_system == 0) ctx->th_pmcs[cnum] = value;
/*
* write hardware register if we can
*/
if (can_access_pmu) {
ia64_set_pmc(cnum, value);
}
#ifdef CONFIG_SMP
else {
/*
* per-task SMP only here
*
* we are guaranteed that the task is not running on the other CPU,
* we indicate that this PMD will need to be reloaded if the task
* is rescheduled on the CPU it ran last on.
*/
ctx->ctx_reload_pmcs[0] |= 1UL << cnum;
}
#endif
}
DPRINT(("pmc[%u]=0x%lx ld=%d apmu=%d flags=0x%x all_pmcs=0x%lx used_pmds=0x%lx eventid=%ld smpl_pmds=0x%lx reset_pmds=0x%lx reloads_pmcs=0x%lx used_monitors=0x%lx ovfl_regs=0x%lx\n",
cnum,
value,
is_loaded,
can_access_pmu,
flags,
ctx->ctx_all_pmcs[0],
ctx->ctx_used_pmds[0],
ctx->ctx_pmds[cnum].eventid,
smpl_pmds,
reset_pmds,
ctx->ctx_reload_pmcs[0],
ctx->ctx_used_monitors[0],
ctx->ctx_ovfl_regs[0]));
}
/*
* make sure the changes are visible
*/
if (can_access_pmu) ia64_srlz_d();
return 0;
error:
PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
return ret;
}
static int
pfm_write_pmds(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task;
pfarg_reg_t *req = (pfarg_reg_t *)arg;
unsigned long value, hw_value, ovfl_mask;
unsigned int cnum;
int i, can_access_pmu = 0, state;
int is_counting, is_loaded, is_system, expert_mode;
int ret = -EINVAL;
pfm_reg_check_t wr_func;
state = ctx->ctx_state;
is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
is_system = ctx->ctx_fl_system;
ovfl_mask = pmu_conf->ovfl_val;
task = ctx->ctx_task;
if (unlikely(state == PFM_CTX_ZOMBIE)) return -EINVAL;
/*
* on both UP and SMP, we can only write to the PMC when the task is
* the owner of the local PMU.
*/
if (likely(is_loaded)) {
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
}
expert_mode = pfm_sysctl.expert_mode;
for (i = 0; i < count; i++, req++) {
cnum = req->reg_num;
value = req->reg_value;
if (!PMD_IS_IMPL(cnum)) {
DPRINT(("pmd[%u] is unimplemented or invalid\n", cnum));
goto abort_mission;
}
is_counting = PMD_IS_COUNTING(cnum);
wr_func = pmu_conf->pmd_desc[cnum].write_check;
/*
* execute write checker, if any
*/
if (unlikely(expert_mode == 0 && wr_func)) {
unsigned long v = value;
ret = (*wr_func)(task, ctx, cnum, &v, regs);
if (ret) goto abort_mission;
value = v;
ret = -EINVAL;
}
/*
* no error on this register
*/
PFM_REG_RETFLAG_SET(req->reg_flags, 0);
/*
* now commit changes to software state
*/
hw_value = value;
/*
* update virtualized (64bits) counter
*/
if (is_counting) {
/*
* write context state
*/
ctx->ctx_pmds[cnum].lval = value;
/*
* when context is load we use the split value
*/
if (is_loaded) {
hw_value = value & ovfl_mask;
value = value & ~ovfl_mask;
}
}
/*
* update reset values (not just for counters)
*/
ctx->ctx_pmds[cnum].long_reset = req->reg_long_reset;
ctx->ctx_pmds[cnum].short_reset = req->reg_short_reset;
/*
* update randomization parameters (not just for counters)
*/
ctx->ctx_pmds[cnum].seed = req->reg_random_seed;
ctx->ctx_pmds[cnum].mask = req->reg_random_mask;
/*
* update context value
*/
ctx->ctx_pmds[cnum].val = value;
/*
* Keep track of what we use
*
* We do not keep track of PMC because we have to
* systematically restore ALL of them.
*/
CTX_USED_PMD(ctx, PMD_PMD_DEP(cnum));
/*
* mark this PMD register used as well
*/
CTX_USED_PMD(ctx, RDEP(cnum));
/*
* make sure we do not try to reset on
* restart because we have established new values
*/
if (is_counting && state == PFM_CTX_MASKED) {
ctx->ctx_ovfl_regs[0] &= ~1UL << cnum;
}
if (is_loaded) {
/*
* write thread state
*/
if (is_system == 0) ctx->th_pmds[cnum] = hw_value;
/*
* write hardware register if we can
*/
if (can_access_pmu) {
ia64_set_pmd(cnum, hw_value);
} else {
#ifdef CONFIG_SMP
/*
* we are guaranteed that the task is not running on the other CPU,
* we indicate that this PMD will need to be reloaded if the task
* is rescheduled on the CPU it ran last on.
*/
ctx->ctx_reload_pmds[0] |= 1UL << cnum;
#endif
}
}
DPRINT(("pmd[%u]=0x%lx ld=%d apmu=%d, hw_value=0x%lx ctx_pmd=0x%lx short_reset=0x%lx "
"long_reset=0x%lx notify=%c seed=0x%lx mask=0x%lx used_pmds=0x%lx reset_pmds=0x%lx reload_pmds=0x%lx all_pmds=0x%lx ovfl_regs=0x%lx\n",
cnum,
value,
is_loaded,
can_access_pmu,
hw_value,
ctx->ctx_pmds[cnum].val,
ctx->ctx_pmds[cnum].short_reset,
ctx->ctx_pmds[cnum].long_reset,
PMC_OVFL_NOTIFY(ctx, cnum) ? 'Y':'N',
ctx->ctx_pmds[cnum].seed,
ctx->ctx_pmds[cnum].mask,
ctx->ctx_used_pmds[0],
ctx->ctx_pmds[cnum].reset_pmds[0],
ctx->ctx_reload_pmds[0],
ctx->ctx_all_pmds[0],
ctx->ctx_ovfl_regs[0]));
}
/*
* make changes visible
*/
if (can_access_pmu) ia64_srlz_d();
return 0;
abort_mission:
/*
* for now, we have only one possibility for error
*/
PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
return ret;
}
/*
* By the way of PROTECT_CONTEXT(), interrupts are masked while we are in this function.
* Therefore we know, we do not have to worry about the PMU overflow interrupt. If an
* interrupt is delivered during the call, it will be kept pending until we leave, making
* it appears as if it had been generated at the UNPROTECT_CONTEXT(). At least we are
* guaranteed to return consistent data to the user, it may simply be old. It is not
* trivial to treat the overflow while inside the call because you may end up in
* some module sampling buffer code causing deadlocks.
*/
static int
pfm_read_pmds(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task;
unsigned long val = 0UL, lval, ovfl_mask, sval;
pfarg_reg_t *req = (pfarg_reg_t *)arg;
unsigned int cnum, reg_flags = 0;
int i, can_access_pmu = 0, state;
int is_loaded, is_system, is_counting, expert_mode;
int ret = -EINVAL;
pfm_reg_check_t rd_func;
/*
* access is possible when loaded only for
* self-monitoring tasks or in UP mode
*/
state = ctx->ctx_state;
is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
is_system = ctx->ctx_fl_system;
ovfl_mask = pmu_conf->ovfl_val;
task = ctx->ctx_task;
if (state == PFM_CTX_ZOMBIE) return -EINVAL;
if (likely(is_loaded)) {
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
/*
* this can be true when not self-monitoring only in UP
*/
can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
if (can_access_pmu) ia64_srlz_d();
}
expert_mode = pfm_sysctl.expert_mode;
DPRINT(("ld=%d apmu=%d ctx_state=%d\n",
is_loaded,
can_access_pmu,
state));
/*
* on both UP and SMP, we can only read the PMD from the hardware register when
* the task is the owner of the local PMU.
*/
for (i = 0; i < count; i++, req++) {
cnum = req->reg_num;
reg_flags = req->reg_flags;
if (unlikely(!PMD_IS_IMPL(cnum))) goto error;
/*
* we can only read the register that we use. That includes
* the one we explicitly initialize AND the one we want included
* in the sampling buffer (smpl_regs).
*
* Having this restriction allows optimization in the ctxsw routine
* without compromising security (leaks)
*/
if (unlikely(!CTX_IS_USED_PMD(ctx, cnum))) goto error;
sval = ctx->ctx_pmds[cnum].val;
lval = ctx->ctx_pmds[cnum].lval;
is_counting = PMD_IS_COUNTING(cnum);
/*
* If the task is not the current one, then we check if the
* PMU state is still in the local live register due to lazy ctxsw.
* If true, then we read directly from the registers.
*/
if (can_access_pmu){
val = ia64_get_pmd(cnum);
} else {
/*
* context has been saved
* if context is zombie, then task does not exist anymore.
* In this case, we use the full value saved in the context (pfm_flush_regs()).
*/
val = is_loaded ? ctx->th_pmds[cnum] : 0UL;
}
rd_func = pmu_conf->pmd_desc[cnum].read_check;
if (is_counting) {
/*
* XXX: need to check for overflow when loaded
*/
val &= ovfl_mask;
val += sval;
}
/*
* execute read checker, if any
*/
if (unlikely(expert_mode == 0 && rd_func)) {
unsigned long v = val;
ret = (*rd_func)(ctx->ctx_task, ctx, cnum, &v, regs);
if (ret) goto error;
val = v;
ret = -EINVAL;
}
PFM_REG_RETFLAG_SET(reg_flags, 0);
DPRINT(("pmd[%u]=0x%lx\n", cnum, val));
/*
* update register return value, abort all if problem during copy.
* we only modify the reg_flags field. no check mode is fine because
* access has been verified upfront in sys_perfmonctl().
*/
req->reg_value = val;
req->reg_flags = reg_flags;
req->reg_last_reset_val = lval;
}
return 0;
error:
PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
return ret;
}
int
pfm_mod_write_pmcs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
{
pfm_context_t *ctx;
if (req == NULL) return -EINVAL;
ctx = GET_PMU_CTX();
if (ctx == NULL) return -EINVAL;
/*
* for now limit to current task, which is enough when calling
* from overflow handler
*/
if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
return pfm_write_pmcs(ctx, req, nreq, regs);
}
EXPORT_SYMBOL(pfm_mod_write_pmcs);
int
pfm_mod_read_pmds(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
{
pfm_context_t *ctx;
if (req == NULL) return -EINVAL;
ctx = GET_PMU_CTX();
if (ctx == NULL) return -EINVAL;
/*
* for now limit to current task, which is enough when calling
* from overflow handler
*/
if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
return pfm_read_pmds(ctx, req, nreq, regs);
}
EXPORT_SYMBOL(pfm_mod_read_pmds);
/*
* Only call this function when a process it trying to
* write the debug registers (reading is always allowed)
*/
int
pfm_use_debug_registers(struct task_struct *task)
{
pfm_context_t *ctx = task->thread.pfm_context;
unsigned long flags;
int ret = 0;
if (pmu_conf->use_rr_dbregs == 0) return 0;
DPRINT(("called for [%d]\n", task_pid_nr(task)));
/*
* do it only once
*/
if (task->thread.flags & IA64_THREAD_DBG_VALID) return 0;
/*
* Even on SMP, we do not need to use an atomic here because
* the only way in is via ptrace() and this is possible only when the
* process is stopped. Even in the case where the ctxsw out is not totally
* completed by the time we come here, there is no way the 'stopped' process
* could be in the middle of fiddling with the pfm_write_ibr_dbr() routine.
* So this is always safe.
*/
if (ctx && ctx->ctx_fl_using_dbreg == 1) return -1;
LOCK_PFS(flags);
/*
* We cannot allow setting breakpoints when system wide monitoring
* sessions are using the debug registers.
*/
if (pfm_sessions.pfs_sys_use_dbregs> 0)
ret = -1;
else
pfm_sessions.pfs_ptrace_use_dbregs++;
DPRINT(("ptrace_use_dbregs=%u sys_use_dbregs=%u by [%d] ret = %d\n",
pfm_sessions.pfs_ptrace_use_dbregs,
pfm_sessions.pfs_sys_use_dbregs,
task_pid_nr(task), ret));
UNLOCK_PFS(flags);
return ret;
}
/*
* This function is called for every task that exits with the
* IA64_THREAD_DBG_VALID set. This indicates a task which was
* able to use the debug registers for debugging purposes via
* ptrace(). Therefore we know it was not using them for
* performance monitoring, so we only decrement the number
* of "ptraced" debug register users to keep the count up to date
*/
int
pfm_release_debug_registers(struct task_struct *task)
{
unsigned long flags;
int ret;
if (pmu_conf->use_rr_dbregs == 0) return 0;
LOCK_PFS(flags);
if (pfm_sessions.pfs_ptrace_use_dbregs == 0) {
printk(KERN_ERR "perfmon: invalid release for [%d] ptrace_use_dbregs=0\n", task_pid_nr(task));
ret = -1;
} else {
pfm_sessions.pfs_ptrace_use_dbregs--;
ret = 0;
}
UNLOCK_PFS(flags);
return ret;
}
static int
pfm_restart(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task;
pfm_buffer_fmt_t *fmt;
pfm_ovfl_ctrl_t rst_ctrl;
int state, is_system;
int ret = 0;
state = ctx->ctx_state;
fmt = ctx->ctx_buf_fmt;
is_system = ctx->ctx_fl_system;
task = PFM_CTX_TASK(ctx);
switch(state) {
case PFM_CTX_MASKED:
break;
case PFM_CTX_LOADED:
if (CTX_HAS_SMPL(ctx) && fmt->fmt_restart_active) break;
/* fall through */
case PFM_CTX_UNLOADED:
case PFM_CTX_ZOMBIE:
DPRINT(("invalid state=%d\n", state));
return -EBUSY;
default:
DPRINT(("state=%d, cannot operate (no active_restart handler)\n", state));
return -EINVAL;
}
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (is_system && ctx->ctx_cpu != smp_processor_id()) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
/* sanity check */
if (unlikely(task == NULL)) {
printk(KERN_ERR "perfmon: [%d] pfm_restart no task\n", task_pid_nr(current));
return -EINVAL;
}
if (task == current || is_system) {
fmt = ctx->ctx_buf_fmt;
DPRINT(("restarting self %d ovfl=0x%lx\n",
task_pid_nr(task),
ctx->ctx_ovfl_regs[0]));
if (CTX_HAS_SMPL(ctx)) {
prefetch(ctx->ctx_smpl_hdr);
rst_ctrl.bits.mask_monitoring = 0;
rst_ctrl.bits.reset_ovfl_pmds = 0;
if (state == PFM_CTX_LOADED)
ret = pfm_buf_fmt_restart_active(fmt, task, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
else
ret = pfm_buf_fmt_restart(fmt, task, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
} else {
rst_ctrl.bits.mask_monitoring = 0;
rst_ctrl.bits.reset_ovfl_pmds = 1;
}
if (ret == 0) {
if (rst_ctrl.bits.reset_ovfl_pmds)
pfm_reset_regs(ctx, ctx->ctx_ovfl_regs, PFM_PMD_LONG_RESET);
if (rst_ctrl.bits.mask_monitoring == 0) {
DPRINT(("resuming monitoring for [%d]\n", task_pid_nr(task)));
if (state == PFM_CTX_MASKED) pfm_restore_monitoring(task);
} else {
DPRINT(("keeping monitoring stopped for [%d]\n", task_pid_nr(task)));
// cannot use pfm_stop_monitoring(task, regs);
}
}
/*
* clear overflowed PMD mask to remove any stale information
*/
ctx->ctx_ovfl_regs[0] = 0UL;
/*
* back to LOADED state
*/
ctx->ctx_state = PFM_CTX_LOADED;
/*
* XXX: not really useful for self monitoring
*/
ctx->ctx_fl_can_restart = 0;
return 0;
}
/*
* restart another task
*/
/*
* When PFM_CTX_MASKED, we cannot issue a restart before the previous
* one is seen by the task.
*/
if (state == PFM_CTX_MASKED) {
if (ctx->ctx_fl_can_restart == 0) return -EINVAL;
/*
* will prevent subsequent restart before this one is
* seen by other task
*/
ctx->ctx_fl_can_restart = 0;
}
/*
* if blocking, then post the semaphore is PFM_CTX_MASKED, i.e.
* the task is blocked or on its way to block. That's the normal
* restart path. If the monitoring is not masked, then the task
* can be actively monitoring and we cannot directly intervene.
* Therefore we use the trap mechanism to catch the task and
* force it to reset the buffer/reset PMDs.
*
* if non-blocking, then we ensure that the task will go into
* pfm_handle_work() before returning to user mode.
*
* We cannot explicitly reset another task, it MUST always
* be done by the task itself. This works for system wide because
* the tool that is controlling the session is logically doing
* "self-monitoring".
*/
if (CTX_OVFL_NOBLOCK(ctx) == 0 && state == PFM_CTX_MASKED) {
DPRINT(("unblocking [%d]\n", task_pid_nr(task)));
complete(&ctx->ctx_restart_done);
} else {
DPRINT(("[%d] armed exit trap\n", task_pid_nr(task)));
ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_RESET;
PFM_SET_WORK_PENDING(task, 1);
set_notify_resume(task);
/*
* XXX: send reschedule if task runs on another CPU
*/
}
return 0;
}
static int
pfm_debug(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
unsigned int m = *(unsigned int *)arg;
pfm_sysctl.debug = m == 0 ? 0 : 1;
printk(KERN_INFO "perfmon debugging %s (timing reset)\n", pfm_sysctl.debug ? "on" : "off");
if (m == 0) {
memset(pfm_stats, 0, sizeof(pfm_stats));
for(m=0; m < NR_CPUS; m++) pfm_stats[m].pfm_ovfl_intr_cycles_min = ~0UL;
}
return 0;
}
/*
* arg can be NULL and count can be zero for this function
*/
static int
pfm_write_ibr_dbr(int mode, pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct thread_struct *thread = NULL;
struct task_struct *task;
pfarg_dbreg_t *req = (pfarg_dbreg_t *)arg;
unsigned long flags;
dbreg_t dbreg;
unsigned int rnum;
int first_time;
int ret = 0, state;
int i, can_access_pmu = 0;
int is_system, is_loaded;
if (pmu_conf->use_rr_dbregs == 0) return -EINVAL;
state = ctx->ctx_state;
is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
is_system = ctx->ctx_fl_system;
task = ctx->ctx_task;
if (state == PFM_CTX_ZOMBIE) return -EINVAL;
/*
* on both UP and SMP, we can only write to the PMC when the task is
* the owner of the local PMU.
*/
if (is_loaded) {
thread = &task->thread;
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
}
/*
* we do not need to check for ipsr.db because we do clear ibr.x, dbr.r, and dbr.w
* ensuring that no real breakpoint can be installed via this call.
*
* IMPORTANT: regs can be NULL in this function
*/
first_time = ctx->ctx_fl_using_dbreg == 0;
/*
* don't bother if we are loaded and task is being debugged
*/
if (is_loaded && (thread->flags & IA64_THREAD_DBG_VALID) != 0) {
DPRINT(("debug registers already in use for [%d]\n", task_pid_nr(task)));
return -EBUSY;
}
/*
* check for debug registers in system wide mode
*
* If though a check is done in pfm_context_load(),
* we must repeat it here, in case the registers are
* written after the context is loaded
*/
if (is_loaded) {
LOCK_PFS(flags);
if (first_time && is_system) {
if (pfm_sessions.pfs_ptrace_use_dbregs)
ret = -EBUSY;
else
pfm_sessions.pfs_sys_use_dbregs++;
}
UNLOCK_PFS(flags);
}
if (ret != 0) return ret;
/*
* mark ourself as user of the debug registers for
* perfmon purposes.
*/
ctx->ctx_fl_using_dbreg = 1;
/*
* clear hardware registers to make sure we don't
* pick up stale state.
*
* for a system wide session, we do not use
* thread.dbr, thread.ibr because this process
* never leaves the current CPU and the state
* is shared by all processes running on it
*/
if (first_time && can_access_pmu) {
DPRINT(("[%d] clearing ibrs, dbrs\n", task_pid_nr(task)));
for (i=0; i < pmu_conf->num_ibrs; i++) {
ia64_set_ibr(i, 0UL);
ia64_dv_serialize_instruction();
}
ia64_srlz_i();
for (i=0; i < pmu_conf->num_dbrs; i++) {
ia64_set_dbr(i, 0UL);
ia64_dv_serialize_data();
}
ia64_srlz_d();
}
/*
* Now install the values into the registers
*/
for (i = 0; i < count; i++, req++) {
rnum = req->dbreg_num;
dbreg.val = req->dbreg_value;
ret = -EINVAL;
if ((mode == PFM_CODE_RR && rnum >= PFM_NUM_IBRS) || ((mode == PFM_DATA_RR) && rnum >= PFM_NUM_DBRS)) {
DPRINT(("invalid register %u val=0x%lx mode=%d i=%d count=%d\n",
rnum, dbreg.val, mode, i, count));
goto abort_mission;
}
/*
* make sure we do not install enabled breakpoint
*/
if (rnum & 0x1) {
if (mode == PFM_CODE_RR)
dbreg.ibr.ibr_x = 0;
else
dbreg.dbr.dbr_r = dbreg.dbr.dbr_w = 0;
}
PFM_REG_RETFLAG_SET(req->dbreg_flags, 0);
/*
* Debug registers, just like PMC, can only be modified
* by a kernel call. Moreover, perfmon() access to those
* registers are centralized in this routine. The hardware
* does not modify the value of these registers, therefore,
* if we save them as they are written, we can avoid having
* to save them on context switch out. This is made possible
* by the fact that when perfmon uses debug registers, ptrace()
* won't be able to modify them concurrently.
*/
if (mode == PFM_CODE_RR) {
CTX_USED_IBR(ctx, rnum);
if (can_access_pmu) {
ia64_set_ibr(rnum, dbreg.val);
ia64_dv_serialize_instruction();
}
ctx->ctx_ibrs[rnum] = dbreg.val;
DPRINT(("write ibr%u=0x%lx used_ibrs=0x%x ld=%d apmu=%d\n",
rnum, dbreg.val, ctx->ctx_used_ibrs[0], is_loaded, can_access_pmu));
} else {
CTX_USED_DBR(ctx, rnum);
if (can_access_pmu) {
ia64_set_dbr(rnum, dbreg.val);
ia64_dv_serialize_data();
}
ctx->ctx_dbrs[rnum] = dbreg.val;
DPRINT(("write dbr%u=0x%lx used_dbrs=0x%x ld=%d apmu=%d\n",
rnum, dbreg.val, ctx->ctx_used_dbrs[0], is_loaded, can_access_pmu));
}
}
return 0;
abort_mission:
/*
* in case it was our first attempt, we undo the global modifications
*/
if (first_time) {
LOCK_PFS(flags);
if (ctx->ctx_fl_system) {
pfm_sessions.pfs_sys_use_dbregs--;
}
UNLOCK_PFS(flags);
ctx->ctx_fl_using_dbreg = 0;
}
/*
* install error return flag
*/
PFM_REG_RETFLAG_SET(req->dbreg_flags, PFM_REG_RETFL_EINVAL);
return ret;
}
static int
pfm_write_ibrs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
return pfm_write_ibr_dbr(PFM_CODE_RR, ctx, arg, count, regs);
}
static int
pfm_write_dbrs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
return pfm_write_ibr_dbr(PFM_DATA_RR, ctx, arg, count, regs);
}
int
pfm_mod_write_ibrs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
{
pfm_context_t *ctx;
if (req == NULL) return -EINVAL;
ctx = GET_PMU_CTX();
if (ctx == NULL) return -EINVAL;
/*
* for now limit to current task, which is enough when calling
* from overflow handler
*/
if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
return pfm_write_ibrs(ctx, req, nreq, regs);
}
EXPORT_SYMBOL(pfm_mod_write_ibrs);
int
pfm_mod_write_dbrs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
{
pfm_context_t *ctx;
if (req == NULL) return -EINVAL;
ctx = GET_PMU_CTX();
if (ctx == NULL) return -EINVAL;
/*
* for now limit to current task, which is enough when calling
* from overflow handler
*/
if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
return pfm_write_dbrs(ctx, req, nreq, regs);
}
EXPORT_SYMBOL(pfm_mod_write_dbrs);
static int
pfm_get_features(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
pfarg_features_t *req = (pfarg_features_t *)arg;
req->ft_version = PFM_VERSION;
return 0;
}
static int
pfm_stop(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct pt_regs *tregs;
struct task_struct *task = PFM_CTX_TASK(ctx);
int state, is_system;
state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
/*
* context must be attached to issue the stop command (includes LOADED,MASKED,ZOMBIE)
*/
if (state == PFM_CTX_UNLOADED) return -EINVAL;
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (is_system && ctx->ctx_cpu != smp_processor_id()) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
DPRINT(("task [%d] ctx_state=%d is_system=%d\n",
task_pid_nr(PFM_CTX_TASK(ctx)),
state,
is_system));
/*
* in system mode, we need to update the PMU directly
* and the user level state of the caller, which may not
* necessarily be the creator of the context.
*/
if (is_system) {
/*
* Update local PMU first
*
* disable dcr pp
*/
ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) & ~IA64_DCR_PP);
ia64_srlz_i();
/*
* update local cpuinfo
*/
PFM_CPUINFO_CLEAR(PFM_CPUINFO_DCR_PP);
/*
* stop monitoring, does srlz.i
*/
pfm_clear_psr_pp();
/*
* stop monitoring in the caller
*/
ia64_psr(regs)->pp = 0;
return 0;
}
/*
* per-task mode
*/
if (task == current) {
/* stop monitoring at kernel level */
pfm_clear_psr_up();
/*
* stop monitoring at the user level
*/
ia64_psr(regs)->up = 0;
} else {
tregs = task_pt_regs(task);
/*
* stop monitoring at the user level
*/
ia64_psr(tregs)->up = 0;
/*
* monitoring disabled in kernel at next reschedule
*/
ctx->ctx_saved_psr_up = 0;
DPRINT(("task=[%d]\n", task_pid_nr(task)));
}
return 0;
}
static int
pfm_start(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct pt_regs *tregs;
int state, is_system;
state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
if (state != PFM_CTX_LOADED) return -EINVAL;
/*
* In system wide and when the context is loaded, access can only happen
* when the caller is running on the CPU being monitored by the session.
* It does not have to be the owner (ctx_task) of the context per se.
*/
if (is_system && ctx->ctx_cpu != smp_processor_id()) {
DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
return -EBUSY;
}
/*
* in system mode, we need to update the PMU directly
* and the user level state of the caller, which may not
* necessarily be the creator of the context.
*/
if (is_system) {
/*
* set user level psr.pp for the caller
*/
ia64_psr(regs)->pp = 1;
/*
* now update the local PMU and cpuinfo
*/
PFM_CPUINFO_SET(PFM_CPUINFO_DCR_PP);
/*
* start monitoring at kernel level
*/
pfm_set_psr_pp();
/* enable dcr pp */
ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) | IA64_DCR_PP);
ia64_srlz_i();
return 0;
}
/*
* per-process mode
*/
if (ctx->ctx_task == current) {
/* start monitoring at kernel level */
pfm_set_psr_up();
/*
* activate monitoring at user level
*/
ia64_psr(regs)->up = 1;
} else {
tregs = task_pt_regs(ctx->ctx_task);
/*
* start monitoring at the kernel level the next
* time the task is scheduled
*/
ctx->ctx_saved_psr_up = IA64_PSR_UP;
/*
* activate monitoring at user level
*/
ia64_psr(tregs)->up = 1;
}
return 0;
}
static int
pfm_get_pmc_reset(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
pfarg_reg_t *req = (pfarg_reg_t *)arg;
unsigned int cnum;
int i;
int ret = -EINVAL;
for (i = 0; i < count; i++, req++) {
cnum = req->reg_num;
if (!PMC_IS_IMPL(cnum)) goto abort_mission;
req->reg_value = PMC_DFL_VAL(cnum);
PFM_REG_RETFLAG_SET(req->reg_flags, 0);
DPRINT(("pmc_reset_val pmc[%u]=0x%lx\n", cnum, req->reg_value));
}
return 0;
abort_mission:
PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
return ret;
}
static int
pfm_check_task_exist(pfm_context_t *ctx)
{
struct task_struct *g, *t;
int ret = -ESRCH;
read_lock(&tasklist_lock);
do_each_thread (g, t) {
if (t->thread.pfm_context == ctx) {
ret = 0;
goto out;
}
} while_each_thread (g, t);
out:
read_unlock(&tasklist_lock);
DPRINT(("pfm_check_task_exist: ret=%d ctx=%p\n", ret, ctx));
return ret;
}
static int
pfm_context_load(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task;
struct thread_struct *thread;
struct pfm_context_t *old;
unsigned long flags;
#ifndef CONFIG_SMP
struct task_struct *owner_task = NULL;
#endif
pfarg_load_t *req = (pfarg_load_t *)arg;
unsigned long *pmcs_source, *pmds_source;
int the_cpu;
int ret = 0;
int state, is_system, set_dbregs = 0;
state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
/*
* can only load from unloaded or terminated state
*/
if (state != PFM_CTX_UNLOADED) {
DPRINT(("cannot load to [%d], invalid ctx_state=%d\n",
req->load_pid,
ctx->ctx_state));
return -EBUSY;
}
DPRINT(("load_pid [%d] using_dbreg=%d\n", req->load_pid, ctx->ctx_fl_using_dbreg));
if (CTX_OVFL_NOBLOCK(ctx) == 0 && req->load_pid == current->pid) {
DPRINT(("cannot use blocking mode on self\n"));
return -EINVAL;
}
ret = pfm_get_task(ctx, req->load_pid, &task);
if (ret) {
DPRINT(("load_pid [%d] get_task=%d\n", req->load_pid, ret));
return ret;
}
ret = -EINVAL;
/*
* system wide is self monitoring only
*/
if (is_system && task != current) {
DPRINT(("system wide is self monitoring only load_pid=%d\n",
req->load_pid));
goto error;
}
thread = &task->thread;
ret = 0;
/*
* cannot load a context which is using range restrictions,
* into a task that is being debugged.
*/
if (ctx->ctx_fl_using_dbreg) {
if (thread->flags & IA64_THREAD_DBG_VALID) {
ret = -EBUSY;
DPRINT(("load_pid [%d] task is debugged, cannot load range restrictions\n", req->load_pid));
goto error;
}
LOCK_PFS(flags);
if (is_system) {
if (pfm_sessions.pfs_ptrace_use_dbregs) {
DPRINT(("cannot load [%d] dbregs in use\n",
task_pid_nr(task)));
ret = -EBUSY;
} else {
pfm_sessions.pfs_sys_use_dbregs++;
DPRINT(("load [%d] increased sys_use_dbreg=%u\n", task_pid_nr(task), pfm_sessions.pfs_sys_use_dbregs));
set_dbregs = 1;
}
}
UNLOCK_PFS(flags);
if (ret) goto error;
}
/*
* SMP system-wide monitoring implies self-monitoring.
*
* The programming model expects the task to
* be pinned on a CPU throughout the session.
* Here we take note of the current CPU at the
* time the context is loaded. No call from
* another CPU will be allowed.
*
* The pinning via shed_setaffinity()
* must be done by the calling task prior
* to this call.
*
* systemwide: keep track of CPU this session is supposed to run on
*/
the_cpu = ctx->ctx_cpu = smp_processor_id();
ret = -EBUSY;
/*
* now reserve the session
*/
ret = pfm_reserve_session(current, is_system, the_cpu);
if (ret) goto error;
/*
* task is necessarily stopped at this point.
*
* If the previous context was zombie, then it got removed in
* pfm_save_regs(). Therefore we should not see it here.
* If we see a context, then this is an active context
*
* XXX: needs to be atomic
*/
DPRINT(("before cmpxchg() old_ctx=%p new_ctx=%p\n",
thread->pfm_context, ctx));
ret = -EBUSY;
old = ia64_cmpxchg(acq, &thread->pfm_context, NULL, ctx, sizeof(pfm_context_t *));
if (old != NULL) {
DPRINT(("load_pid [%d] already has a context\n", req->load_pid));
goto error_unres;
}
pfm_reset_msgq(ctx);
ctx->ctx_state = PFM_CTX_LOADED;
/*
* link context to task
*/
ctx->ctx_task = task;
if (is_system) {
/*
* we load as stopped
*/
PFM_CPUINFO_SET(PFM_CPUINFO_SYST_WIDE);
PFM_CPUINFO_CLEAR(PFM_CPUINFO_DCR_PP);
if (ctx->ctx_fl_excl_idle) PFM_CPUINFO_SET(PFM_CPUINFO_EXCL_IDLE);
} else {
thread->flags |= IA64_THREAD_PM_VALID;
}
/*
* propagate into thread-state
*/
pfm_copy_pmds(task, ctx);
pfm_copy_pmcs(task, ctx);
pmcs_source = ctx->th_pmcs;
pmds_source = ctx->th_pmds;
/*
* always the case for system-wide
*/
if (task == current) {
if (is_system == 0) {
/* allow user level control */
ia64_psr(regs)->sp = 0;
DPRINT(("clearing psr.sp for [%d]\n", task_pid_nr(task)));
SET_LAST_CPU(ctx, smp_processor_id());
INC_ACTIVATION();
SET_ACTIVATION(ctx);
#ifndef CONFIG_SMP
/*
* push the other task out, if any
*/
owner_task = GET_PMU_OWNER();
if (owner_task) pfm_lazy_save_regs(owner_task);
#endif
}
/*
* load all PMD from ctx to PMU (as opposed to thread state)
* restore all PMC from ctx to PMU
*/
pfm_restore_pmds(pmds_source, ctx->ctx_all_pmds[0]);
pfm_restore_pmcs(pmcs_source, ctx->ctx_all_pmcs[0]);
ctx->ctx_reload_pmcs[0] = 0UL;
ctx->ctx_reload_pmds[0] = 0UL;
/*
* guaranteed safe by earlier check against DBG_VALID
*/
if (ctx->ctx_fl_using_dbreg) {
pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
}
/*
* set new ownership
*/
SET_PMU_OWNER(task, ctx);
DPRINT(("context loaded on PMU for [%d]\n", task_pid_nr(task)));
} else {
/*
* when not current, task MUST be stopped, so this is safe
*/
regs = task_pt_regs(task);
/* force a full reload */
ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
SET_LAST_CPU(ctx, -1);
/* initial saved psr (stopped) */
ctx->ctx_saved_psr_up = 0UL;
ia64_psr(regs)->up = ia64_psr(regs)->pp = 0;
}
ret = 0;
error_unres:
if (ret) pfm_unreserve_session(ctx, ctx->ctx_fl_system, the_cpu);
error:
/*
* we must undo the dbregs setting (for system-wide)
*/
if (ret && set_dbregs) {
LOCK_PFS(flags);
pfm_sessions.pfs_sys_use_dbregs--;
UNLOCK_PFS(flags);
}
/*
* release task, there is now a link with the context
*/
if (is_system == 0 && task != current) {
pfm_put_task(task);
if (ret == 0) {
ret = pfm_check_task_exist(ctx);
if (ret) {
ctx->ctx_state = PFM_CTX_UNLOADED;
ctx->ctx_task = NULL;
}
}
}
return ret;
}
/*
* in this function, we do not need to increase the use count
* for the task via get_task_struct(), because we hold the
* context lock. If the task were to disappear while having
* a context attached, it would go through pfm_exit_thread()
* which also grabs the context lock and would therefore be blocked
* until we are here.
*/
static void pfm_flush_pmds(struct task_struct *, pfm_context_t *ctx);
static int
pfm_context_unload(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
{
struct task_struct *task = PFM_CTX_TASK(ctx);
struct pt_regs *tregs;
int prev_state, is_system;
int ret;
DPRINT(("ctx_state=%d task [%d]\n", ctx->ctx_state, task ? task_pid_nr(task) : -1));
prev_state = ctx->ctx_state;
is_system = ctx->ctx_fl_system;
/*
* unload only when necessary
*/
if (prev_state == PFM_CTX_UNLOADED) {
DPRINT(("ctx_state=%d, nothing to do\n", prev_state));
return 0;
}
/*
* clear psr and dcr bits
*/
ret = pfm_stop(ctx, NULL, 0, regs);
if (ret) return ret;
ctx->ctx_state = PFM_CTX_UNLOADED;
/*
* in system mode, we need to update the PMU directly
* and the user level state of the caller, which may not
* necessarily be the creator of the context.
*/
if (is_system) {
/*
* Update cpuinfo
*
* local PMU is taken care of in pfm_stop()
*/
PFM_CPUINFO_CLEAR(PFM_CPUINFO_SYST_WIDE);
PFM_CPUINFO_CLEAR(PFM_CPUINFO_EXCL_IDLE);
/*
* save PMDs in context
* release ownership
*/
pfm_flush_pmds(current, ctx);
/*
* at this point we are done with the PMU
* so we can unreserve the resource.
*/
if (prev_state != PFM_CTX_ZOMBIE)
pfm_unreserve_session(ctx, 1 , ctx->ctx_cpu);
/*
* disconnect context from task
*/
task->thread.pfm_context = NULL;
/*
* disconnect task from context
*/
ctx->ctx_task = NULL;
/*
* There is nothing more to cleanup here.
*/
return 0;
}
/*
* per-task mode
*/
tregs = task == current ? regs : task_pt_regs(task);
if (task == current) {
/*
* cancel user level control
*/
ia64_psr(regs)->sp = 1;
DPRINT(("setting psr.sp for [%d]\n", task_pid_nr(task)));
}
/*
* save PMDs to context
* release ownership
*/
pfm_flush_pmds(task, ctx);
/*
* at this point we are done with the PMU
* so we can unreserve the resource.
*
* when state was ZOMBIE, we have already unreserved.
*/
if (prev_state != PFM_CTX_ZOMBIE)
pfm_unreserve_session(ctx, 0 , ctx->ctx_cpu);
/*
* reset activation counter and psr
*/
ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
SET_LAST_CPU(ctx, -1);
/*
* PMU state will not be restored
*/
task->thread.flags &= ~IA64_THREAD_PM_VALID;
/*
* break links between context and task
*/
task->thread.pfm_context = NULL;
ctx->ctx_task = NULL;
PFM_SET_WORK_PENDING(task, 0);
ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_NONE;
ctx->ctx_fl_can_restart = 0;
ctx->ctx_fl_going_zombie = 0;
DPRINT(("disconnected [%d] from context\n", task_pid_nr(task)));
return 0;
}
/*
* called only from exit_thread(): task == current
* we come here only if current has a context attached (loaded or masked)
*/
void
pfm_exit_thread(struct task_struct *task)
{
pfm_context_t *ctx;
unsigned long flags;
struct pt_regs *regs = task_pt_regs(task);
int ret, state;
int free_ok = 0;
ctx = PFM_GET_CTX(task);
PROTECT_CTX(ctx, flags);
DPRINT(("state=%d task [%d]\n", ctx->ctx_state, task_pid_nr(task)));
state = ctx->ctx_state;
switch(state) {
case PFM_CTX_UNLOADED:
/*
* only comes to this function if pfm_context is not NULL, i.e., cannot
* be in unloaded state
*/
printk(KERN_ERR "perfmon: pfm_exit_thread [%d] ctx unloaded\n", task_pid_nr(task));
break;
case PFM_CTX_LOADED:
case PFM_CTX_MASKED:
ret = pfm_context_unload(ctx, NULL, 0, regs);
if (ret) {
printk(KERN_ERR "perfmon: pfm_exit_thread [%d] state=%d unload failed %d\n", task_pid_nr(task), state, ret);
}
DPRINT(("ctx unloaded for current state was %d\n", state));
pfm_end_notify_user(ctx);
break;
case PFM_CTX_ZOMBIE:
ret = pfm_context_unload(ctx, NULL, 0, regs);
if (ret) {
printk(KERN_ERR "perfmon: pfm_exit_thread [%d] state=%d unload failed %d\n", task_pid_nr(task), state, ret);
}
free_ok = 1;
break;
default:
printk(KERN_ERR "perfmon: pfm_exit_thread [%d] unexpected state=%d\n", task_pid_nr(task), state);
break;
}
UNPROTECT_CTX(ctx, flags);
{ u64 psr = pfm_get_psr();
BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
BUG_ON(GET_PMU_OWNER());
BUG_ON(ia64_psr(regs)->up);
BUG_ON(ia64_psr(regs)->pp);
}
/*
* All memory free operations (especially for vmalloc'ed memory)
* MUST be done with interrupts ENABLED.
*/
if (free_ok) pfm_context_free(ctx);
}
/*
* functions MUST be listed in the increasing order of their index (see permfon.h)
*/
#define PFM_CMD(name, flags, arg_count, arg_type, getsz) { name, #name, flags, arg_count, sizeof(arg_type), getsz }
#define PFM_CMD_S(name, flags) { name, #name, flags, 0, 0, NULL }
#define PFM_CMD_PCLRWS (PFM_CMD_FD|PFM_CMD_ARG_RW|PFM_CMD_STOP)
#define PFM_CMD_PCLRW (PFM_CMD_FD|PFM_CMD_ARG_RW)
#define PFM_CMD_NONE { NULL, "no-cmd", 0, 0, 0, NULL}
static pfm_cmd_desc_t pfm_cmd_tab[]={
/* 0 */PFM_CMD_NONE,
/* 1 */PFM_CMD(pfm_write_pmcs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
/* 2 */PFM_CMD(pfm_write_pmds, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
/* 3 */PFM_CMD(pfm_read_pmds, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
/* 4 */PFM_CMD_S(pfm_stop, PFM_CMD_PCLRWS),
/* 5 */PFM_CMD_S(pfm_start, PFM_CMD_PCLRWS),
/* 6 */PFM_CMD_NONE,
/* 7 */PFM_CMD_NONE,
/* 8 */PFM_CMD(pfm_context_create, PFM_CMD_ARG_RW, 1, pfarg_context_t, pfm_ctx_getsize),
/* 9 */PFM_CMD_NONE,
/* 10 */PFM_CMD_S(pfm_restart, PFM_CMD_PCLRW),
/* 11 */PFM_CMD_NONE,
/* 12 */PFM_CMD(pfm_get_features, PFM_CMD_ARG_RW, 1, pfarg_features_t, NULL),
/* 13 */PFM_CMD(pfm_debug, 0, 1, unsigned int, NULL),
/* 14 */PFM_CMD_NONE,
/* 15 */PFM_CMD(pfm_get_pmc_reset, PFM_CMD_ARG_RW, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
/* 16 */PFM_CMD(pfm_context_load, PFM_CMD_PCLRWS, 1, pfarg_load_t, NULL),
/* 17 */PFM_CMD_S(pfm_context_unload, PFM_CMD_PCLRWS),
/* 18 */PFM_CMD_NONE,
/* 19 */PFM_CMD_NONE,
/* 20 */PFM_CMD_NONE,
/* 21 */PFM_CMD_NONE,
/* 22 */PFM_CMD_NONE,
/* 23 */PFM_CMD_NONE,
/* 24 */PFM_CMD_NONE,
/* 25 */PFM_CMD_NONE,
/* 26 */PFM_CMD_NONE,
/* 27 */PFM_CMD_NONE,
/* 28 */PFM_CMD_NONE,
/* 29 */PFM_CMD_NONE,
/* 30 */PFM_CMD_NONE,
/* 31 */PFM_CMD_NONE,
/* 32 */PFM_CMD(pfm_write_ibrs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_dbreg_t, NULL),
/* 33 */PFM_CMD(pfm_write_dbrs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_dbreg_t, NULL)
};
#define PFM_CMD_COUNT (sizeof(pfm_cmd_tab)/sizeof(pfm_cmd_desc_t))
static int
pfm_check_task_state(pfm_context_t *ctx, int cmd, unsigned long flags)
{
struct task_struct *task;
int state, old_state;
recheck:
state = ctx->ctx_state;
task = ctx->ctx_task;
if (task == NULL) {
DPRINT(("context %d no task, state=%d\n", ctx->ctx_fd, state));
return 0;
}
DPRINT(("context %d state=%d [%d] task_state=%ld must_stop=%d\n",
ctx->ctx_fd,
state,
task_pid_nr(task),
task->state, PFM_CMD_STOPPED(cmd)));
/*
* self-monitoring always ok.
*
* for system-wide the caller can either be the creator of the
* context (to one to which the context is attached to) OR
* a task running on the same CPU as the session.
*/
if (task == current || ctx->ctx_fl_system) return 0;
/*
* we are monitoring another thread
*/
switch(state) {
case PFM_CTX_UNLOADED:
/*
* if context is UNLOADED we are safe to go
*/
return 0;
case PFM_CTX_ZOMBIE:
/*
* no command can operate on a zombie context
*/
DPRINT(("cmd %d state zombie cannot operate on context\n", cmd));
return -EINVAL;
case PFM_CTX_MASKED:
/*
* PMU state has been saved to software even though
* the thread may still be running.
*/
if (cmd != PFM_UNLOAD_CONTEXT) return 0;
}
/*
* context is LOADED or MASKED. Some commands may need to have
* the task stopped.
*
* We could lift this restriction for UP but it would mean that
* the user has no guarantee the task would not run between
* two successive calls to perfmonctl(). That's probably OK.
* If this user wants to ensure the task does not run, then
* the task must be stopped.
*/
if (PFM_CMD_STOPPED(cmd)) {
if (!task_is_stopped_or_traced(task)) {
DPRINT(("[%d] task not in stopped state\n", task_pid_nr(task)));
return -EBUSY;
}
/*
* task is now stopped, wait for ctxsw out
*
* This is an interesting point in the code.
* We need to unprotect the context because
* the pfm_save_regs() routines needs to grab
* the same lock. There are danger in doing
* this because it leaves a window open for
* another task to get access to the context
* and possibly change its state. The one thing
* that is not possible is for the context to disappear
* because we are protected by the VFS layer, i.e.,
* get_fd()/put_fd().
*/
old_state = state;
UNPROTECT_CTX(ctx, flags);
wait_task_inactive(task, 0);
PROTECT_CTX(ctx, flags);
/*
* we must recheck to verify if state has changed
*/
if (ctx->ctx_state != old_state) {
DPRINT(("old_state=%d new_state=%d\n", old_state, ctx->ctx_state));
goto recheck;
}
}
return 0;
}
/*
* system-call entry point (must return long)
*/
asmlinkage long
sys_perfmonctl (int fd, int cmd, void __user *arg, int count)
{
struct file *file = NULL;
pfm_context_t *ctx = NULL;
unsigned long flags = 0UL;
void *args_k = NULL;
long ret; /* will expand int return types */
size_t base_sz, sz, xtra_sz = 0;
int narg, completed_args = 0, call_made = 0, cmd_flags;
int (*func)(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
int (*getsize)(void *arg, size_t *sz);
#define PFM_MAX_ARGSIZE 4096
/*
* reject any call if perfmon was disabled at initialization
*/
if (unlikely(pmu_conf == NULL)) return -ENOSYS;
if (unlikely(cmd < 0 || cmd >= PFM_CMD_COUNT)) {
DPRINT(("invalid cmd=%d\n", cmd));
return -EINVAL;
}
func = pfm_cmd_tab[cmd].cmd_func;
narg = pfm_cmd_tab[cmd].cmd_narg;
base_sz = pfm_cmd_tab[cmd].cmd_argsize;
getsize = pfm_cmd_tab[cmd].cmd_getsize;
cmd_flags = pfm_cmd_tab[cmd].cmd_flags;
if (unlikely(func == NULL)) {
DPRINT(("invalid cmd=%d\n", cmd));
return -EINVAL;
}
DPRINT(("cmd=%s idx=%d narg=0x%x argsz=%lu count=%d\n",
PFM_CMD_NAME(cmd),
cmd,
narg,
base_sz,
count));
/*
* check if number of arguments matches what the command expects
*/
if (unlikely((narg == PFM_CMD_ARG_MANY && count <= 0) || (narg > 0 && narg != count)))
return -EINVAL;
restart_args:
sz = xtra_sz + base_sz*count;
/*
* limit abuse to min page size
*/
if (unlikely(sz > PFM_MAX_ARGSIZE)) {
printk(KERN_ERR "perfmon: [%d] argument too big %lu\n", task_pid_nr(current), sz);
return -E2BIG;
}
/*
* allocate default-sized argument buffer
*/
if (likely(count && args_k == NULL)) {
args_k = kmalloc(PFM_MAX_ARGSIZE, GFP_KERNEL);
if (args_k == NULL) return -ENOMEM;
}
ret = -EFAULT;
/*
* copy arguments
*
* assume sz = 0 for command without parameters
*/
if (sz && copy_from_user(args_k, arg, sz)) {
DPRINT(("cannot copy_from_user %lu bytes @%p\n", sz, arg));
goto error_args;
}
/*
* check if command supports extra parameters
*/
if (completed_args == 0 && getsize) {
/*
* get extra parameters size (based on main argument)
*/
ret = (*getsize)(args_k, &xtra_sz);
if (ret) goto error_args;
completed_args = 1;
DPRINT(("restart_args sz=%lu xtra_sz=%lu\n", sz, xtra_sz));
/* retry if necessary */
if (likely(xtra_sz)) goto restart_args;
}
if (unlikely((cmd_flags & PFM_CMD_FD) == 0)) goto skip_fd;
ret = -EBADF;
file = fget(fd);
if (unlikely(file == NULL)) {
DPRINT(("invalid fd %d\n", fd));
goto error_args;
}
if (unlikely(PFM_IS_FILE(file) == 0)) {
DPRINT(("fd %d not related to perfmon\n", fd));
goto error_args;
}
ctx = file->private_data;
if (unlikely(ctx == NULL)) {
DPRINT(("no context for fd %d\n", fd));
goto error_args;
}
prefetch(&ctx->ctx_state);
PROTECT_CTX(ctx, flags);
/*
* check task is stopped
*/
ret = pfm_check_task_state(ctx, cmd, flags);
if (unlikely(ret)) goto abort_locked;
skip_fd:
ret = (*func)(ctx, args_k, count, task_pt_regs(current));
call_made = 1;
abort_locked:
if (likely(ctx)) {
DPRINT(("context unlocked\n"));
UNPROTECT_CTX(ctx, flags);
}
/* copy argument back to user, if needed */
if (call_made && PFM_CMD_RW_ARG(cmd) && copy_to_user(arg, args_k, base_sz*count)) ret = -EFAULT;
error_args:
if (file)
fput(file);
kfree(args_k);
DPRINT(("cmd=%s ret=%ld\n", PFM_CMD_NAME(cmd), ret));
return ret;
}
static void
pfm_resume_after_ovfl(pfm_context_t *ctx, unsigned long ovfl_regs, struct pt_regs *regs)
{
pfm_buffer_fmt_t *fmt = ctx->ctx_buf_fmt;
pfm_ovfl_ctrl_t rst_ctrl;
int state;
int ret = 0;
state = ctx->ctx_state;
/*
* Unlock sampling buffer and reset index atomically
* XXX: not really needed when blocking
*/
if (CTX_HAS_SMPL(ctx)) {
rst_ctrl.bits.mask_monitoring = 0;
rst_ctrl.bits.reset_ovfl_pmds = 0;
if (state == PFM_CTX_LOADED)
ret = pfm_buf_fmt_restart_active(fmt, current, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
else
ret = pfm_buf_fmt_restart(fmt, current, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
} else {
rst_ctrl.bits.mask_monitoring = 0;
rst_ctrl.bits.reset_ovfl_pmds = 1;
}
if (ret == 0) {
if (rst_ctrl.bits.reset_ovfl_pmds) {
pfm_reset_regs(ctx, &ovfl_regs, PFM_PMD_LONG_RESET);
}
if (rst_ctrl.bits.mask_monitoring == 0) {
DPRINT(("resuming monitoring\n"));
if (ctx->ctx_state == PFM_CTX_MASKED) pfm_restore_monitoring(current);
} else {
DPRINT(("stopping monitoring\n"));
//pfm_stop_monitoring(current, regs);
}
ctx->ctx_state = PFM_CTX_LOADED;
}
}
/*
* context MUST BE LOCKED when calling
* can only be called for current
*/
static void
pfm_context_force_terminate(pfm_context_t *ctx, struct pt_regs *regs)
{
int ret;
DPRINT(("entering for [%d]\n", task_pid_nr(current)));
ret = pfm_context_unload(ctx, NULL, 0, regs);
if (ret) {
printk(KERN_ERR "pfm_context_force_terminate: [%d] unloaded failed with %d\n", task_pid_nr(current), ret);
}
/*
* and wakeup controlling task, indicating we are now disconnected
*/
wake_up_interruptible(&ctx->ctx_zombieq);
/*
* given that context is still locked, the controlling
* task will only get access when we return from
* pfm_handle_work().
*/
}
static int pfm_ovfl_notify_user(pfm_context_t *ctx, unsigned long ovfl_pmds);
/*
* pfm_handle_work() can be called with interrupts enabled
* (TIF_NEED_RESCHED) or disabled. The down_interruptible
* call may sleep, therefore we must re-enable interrupts
* to avoid deadlocks. It is safe to do so because this function
* is called ONLY when returning to user level (pUStk=1), in which case
* there is no risk of kernel stack overflow due to deep
* interrupt nesting.
*/
void
pfm_handle_work(void)
{
pfm_context_t *ctx;
struct pt_regs *regs;
unsigned long flags, dummy_flags;
unsigned long ovfl_regs;
unsigned int reason;
int ret;
ctx = PFM_GET_CTX(current);
if (ctx == NULL) {
printk(KERN_ERR "perfmon: [%d] has no PFM context\n",
task_pid_nr(current));
return;
}
PROTECT_CTX(ctx, flags);
PFM_SET_WORK_PENDING(current, 0);
regs = task_pt_regs(current);
/*
* extract reason for being here and clear
*/
reason = ctx->ctx_fl_trap_reason;
ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_NONE;
ovfl_regs = ctx->ctx_ovfl_regs[0];
DPRINT(("reason=%d state=%d\n", reason, ctx->ctx_state));
/*
* must be done before we check for simple-reset mode
*/
if (ctx->ctx_fl_going_zombie || ctx->ctx_state == PFM_CTX_ZOMBIE)
goto do_zombie;
//if (CTX_OVFL_NOBLOCK(ctx)) goto skip_blocking;
if (reason == PFM_TRAP_REASON_RESET)
goto skip_blocking;
/*
* restore interrupt mask to what it was on entry.
* Could be enabled/diasbled.
*/
UNPROTECT_CTX(ctx, flags);
/*
* force interrupt enable because of down_interruptible()
*/
local_irq_enable();
DPRINT(("before block sleeping\n"));
/*
* may go through without blocking on SMP systems
* if restart has been received already by the time we call down()
*/
ret = wait_for_completion_interruptible(&ctx->ctx_restart_done);
DPRINT(("after block sleeping ret=%d\n", ret));
/*
* lock context and mask interrupts again
* We save flags into a dummy because we may have
* altered interrupts mask compared to entry in this
* function.
*/
PROTECT_CTX(ctx, dummy_flags);
/*
* we need to read the ovfl_regs only after wake-up
* because we may have had pfm_write_pmds() in between
* and that can changed PMD values and therefore
* ovfl_regs is reset for these new PMD values.
*/
ovfl_regs = ctx->ctx_ovfl_regs[0];
if (ctx->ctx_fl_going_zombie) {
do_zombie:
DPRINT(("context is zombie, bailing out\n"));
pfm_context_force_terminate(ctx, regs);
goto nothing_to_do;
}
/*
* in case of interruption of down() we don't restart anything
*/
if (ret < 0)
goto nothing_to_do;
skip_blocking:
pfm_resume_after_ovfl(ctx, ovfl_regs, regs);
ctx->ctx_ovfl_regs[0] = 0UL;
nothing_to_do:
/*
* restore flags as they were upon entry
*/
UNPROTECT_CTX(ctx, flags);
}
static int
pfm_notify_user(pfm_context_t *ctx, pfm_msg_t *msg)
{
if (ctx->ctx_state == PFM_CTX_ZOMBIE) {
DPRINT(("ignoring overflow notification, owner is zombie\n"));
return 0;
}
DPRINT(("waking up somebody\n"));
if (msg) wake_up_interruptible(&ctx->ctx_msgq_wait);
/*
* safe, we are not in intr handler, nor in ctxsw when
* we come here
*/
kill_fasync (&ctx->ctx_async_queue, SIGIO, POLL_IN);
return 0;
}
static int
pfm_ovfl_notify_user(pfm_context_t *ctx, unsigned long ovfl_pmds)
{
pfm_msg_t *msg = NULL;
if (ctx->ctx_fl_no_msg == 0) {
msg = pfm_get_new_msg(ctx);
if (msg == NULL) {
printk(KERN_ERR "perfmon: pfm_ovfl_notify_user no more notification msgs\n");
return -1;
}
msg->pfm_ovfl_msg.msg_type = PFM_MSG_OVFL;
msg->pfm_ovfl_msg.msg_ctx_fd = ctx->ctx_fd;
msg->pfm_ovfl_msg.msg_active_set = 0;
msg->pfm_ovfl_msg.msg_ovfl_pmds[0] = ovfl_pmds;
msg->pfm_ovfl_msg.msg_ovfl_pmds[1] = 0UL;
msg->pfm_ovfl_msg.msg_ovfl_pmds[2] = 0UL;
msg->pfm_ovfl_msg.msg_ovfl_pmds[3] = 0UL;
msg->pfm_ovfl_msg.msg_tstamp = 0UL;
}
DPRINT(("ovfl msg: msg=%p no_msg=%d fd=%d ovfl_pmds=0x%lx\n",
msg,
ctx->ctx_fl_no_msg,
ctx->ctx_fd,
ovfl_pmds));
return pfm_notify_user(ctx, msg);
}
static int
pfm_end_notify_user(pfm_context_t *ctx)
{
pfm_msg_t *msg;
msg = pfm_get_new_msg(ctx);
if (msg == NULL) {
printk(KERN_ERR "perfmon: pfm_end_notify_user no more notification msgs\n");
return -1;
}
/* no leak */
memset(msg, 0, sizeof(*msg));
msg->pfm_end_msg.msg_type = PFM_MSG_END;
msg->pfm_end_msg.msg_ctx_fd = ctx->ctx_fd;
msg->pfm_ovfl_msg.msg_tstamp = 0UL;
DPRINT(("end msg: msg=%p no_msg=%d ctx_fd=%d\n",
msg,
ctx->ctx_fl_no_msg,
ctx->ctx_fd));
return pfm_notify_user(ctx, msg);
}
/*
* main overflow processing routine.
* it can be called from the interrupt path or explicitly during the context switch code
*/
static void pfm_overflow_handler(struct task_struct *task, pfm_context_t *ctx,
unsigned long pmc0, struct pt_regs *regs)
{
pfm_ovfl_arg_t *ovfl_arg;
unsigned long mask;
unsigned long old_val, ovfl_val, new_val;
unsigned long ovfl_notify = 0UL, ovfl_pmds = 0UL, smpl_pmds = 0UL, reset_pmds;
unsigned long tstamp;
pfm_ovfl_ctrl_t ovfl_ctrl;
unsigned int i, has_smpl;
int must_notify = 0;
if (unlikely(ctx->ctx_state == PFM_CTX_ZOMBIE)) goto stop_monitoring;
/*
* sanity test. Should never happen
*/
if (unlikely((pmc0 & 0x1) == 0)) goto sanity_check;
tstamp = ia64_get_itc();
mask = pmc0 >> PMU_FIRST_COUNTER;
ovfl_val = pmu_conf->ovfl_val;
has_smpl = CTX_HAS_SMPL(ctx);
DPRINT_ovfl(("pmc0=0x%lx pid=%d iip=0x%lx, %s "
"used_pmds=0x%lx\n",
pmc0,
task ? task_pid_nr(task): -1,
(regs ? regs->cr_iip : 0),
CTX_OVFL_NOBLOCK(ctx) ? "nonblocking" : "blocking",
ctx->ctx_used_pmds[0]));
/*
* first we update the virtual counters
* assume there was a prior ia64_srlz_d() issued
*/
for (i = PMU_FIRST_COUNTER; mask ; i++, mask >>= 1) {
/* skip pmd which did not overflow */
if ((mask & 0x1) == 0) continue;
/*
* Note that the pmd is not necessarily 0 at this point as qualified events
* may have happened before the PMU was frozen. The residual count is not
* taken into consideration here but will be with any read of the pmd via
* pfm_read_pmds().
*/
old_val = new_val = ctx->ctx_pmds[i].val;
new_val += 1 + ovfl_val;
ctx->ctx_pmds[i].val = new_val;
/*
* check for overflow condition
*/
if (likely(old_val > new_val)) {
ovfl_pmds |= 1UL << i;
if (PMC_OVFL_NOTIFY(ctx, i)) ovfl_notify |= 1UL << i;
}
DPRINT_ovfl(("ctx_pmd[%d].val=0x%lx old_val=0x%lx pmd=0x%lx ovfl_pmds=0x%lx ovfl_notify=0x%lx\n",
i,
new_val,
old_val,
ia64_get_pmd(i) & ovfl_val,
ovfl_pmds,
ovfl_notify));
}
/*
* there was no 64-bit overflow, nothing else to do
*/
if (ovfl_pmds == 0UL) return;
/*
* reset all control bits
*/
ovfl_ctrl.val = 0;
reset_pmds = 0UL;
/*
* if a sampling format module exists, then we "cache" the overflow by
* calling the module's handler() routine.
*/
if (has_smpl) {
unsigned long start_cycles, end_cycles;
unsigned long pmd_mask;
int j, k, ret = 0;
int this_cpu = smp_processor_id();
pmd_mask = ovfl_pmds >> PMU_FIRST_COUNTER;
ovfl_arg = &ctx->ctx_ovfl_arg;
prefetch(ctx->ctx_smpl_hdr);
for(i=PMU_FIRST_COUNTER; pmd_mask && ret == 0; i++, pmd_mask >>=1) {
mask = 1UL << i;
if ((pmd_mask & 0x1) == 0) continue;
ovfl_arg->ovfl_pmd = (unsigned char )i;
ovfl_arg->ovfl_notify = ovfl_notify & mask ? 1 : 0;
ovfl_arg->active_set = 0;
ovfl_arg->ovfl_ctrl.val = 0; /* module must fill in all fields */
ovfl_arg->smpl_pmds[0] = smpl_pmds = ctx->ctx_pmds[i].smpl_pmds[0];
ovfl_arg->pmd_value = ctx->ctx_pmds[i].val;
ovfl_arg->pmd_last_reset = ctx->ctx_pmds[i].lval;
ovfl_arg->pmd_eventid = ctx->ctx_pmds[i].eventid;
/*
* copy values of pmds of interest. Sampling format may copy them
* into sampling buffer.
*/
if (smpl_pmds) {
for(j=0, k=0; smpl_pmds; j++, smpl_pmds >>=1) {
if ((smpl_pmds & 0x1) == 0) continue;
ovfl_arg->smpl_pmds_values[k++] = PMD_IS_COUNTING(j) ? pfm_read_soft_counter(ctx, j) : ia64_get_pmd(j);
DPRINT_ovfl(("smpl_pmd[%d]=pmd%u=0x%lx\n", k-1, j, ovfl_arg->smpl_pmds_values[k-1]));
}
}
pfm_stats[this_cpu].pfm_smpl_handler_calls++;
start_cycles = ia64_get_itc();
/*
* call custom buffer format record (handler) routine
*/
ret = (*ctx->ctx_buf_fmt->fmt_handler)(task, ctx->ctx_smpl_hdr, ovfl_arg, regs, tstamp);
end_cycles = ia64_get_itc();
/*
* For those controls, we take the union because they have
* an all or nothing behavior.
*/
ovfl_ctrl.bits.notify_user |= ovfl_arg->ovfl_ctrl.bits.notify_user;
ovfl_ctrl.bits.block_task |= ovfl_arg->ovfl_ctrl.bits.block_task;
ovfl_ctrl.bits.mask_monitoring |= ovfl_arg->ovfl_ctrl.bits.mask_monitoring;
/*
* build the bitmask of pmds to reset now
*/
if (ovfl_arg->ovfl_ctrl.bits.reset_ovfl_pmds) reset_pmds |= mask;
pfm_stats[this_cpu].pfm_smpl_handler_cycles += end_cycles - start_cycles;
}
/*
* when the module cannot handle the rest of the overflows, we abort right here
*/
if (ret && pmd_mask) {
DPRINT(("handler aborts leftover ovfl_pmds=0x%lx\n",
pmd_mask<<PMU_FIRST_COUNTER));
}
/*
* remove the pmds we reset now from the set of pmds to reset in pfm_restart()
*/
ovfl_pmds &= ~reset_pmds;
} else {
/*
* when no sampling module is used, then the default
* is to notify on overflow if requested by user
*/
ovfl_ctrl.bits.notify_user = ovfl_notify ? 1 : 0;
ovfl_ctrl.bits.block_task = ovfl_notify ? 1 : 0;
ovfl_ctrl.bits.mask_monitoring = ovfl_notify ? 1 : 0; /* XXX: change for saturation */
ovfl_ctrl.bits.reset_ovfl_pmds = ovfl_notify ? 0 : 1;
/*
* if needed, we reset all overflowed pmds
*/
if (ovfl_notify == 0) reset_pmds = ovfl_pmds;
}
DPRINT_ovfl(("ovfl_pmds=0x%lx reset_pmds=0x%lx\n", ovfl_pmds, reset_pmds));
/*
* reset the requested PMD registers using the short reset values
*/
if (reset_pmds) {
unsigned long bm = reset_pmds;
pfm_reset_regs(ctx, &bm, PFM_PMD_SHORT_RESET);
}
if (ovfl_notify && ovfl_ctrl.bits.notify_user) {
/*
* keep track of what to reset when unblocking
*/
ctx->ctx_ovfl_regs[0] = ovfl_pmds;
/*
* check for blocking context
*/
if (CTX_OVFL_NOBLOCK(ctx) == 0 && ovfl_ctrl.bits.block_task) {
ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_BLOCK;
/*
* set the perfmon specific checking pending work for the task
*/
PFM_SET_WORK_PENDING(task, 1);
/*
* when coming from ctxsw, current still points to the
* previous task, therefore we must work with task and not current.
*/
set_notify_resume(task);
}
/*
* defer until state is changed (shorten spin window). the context is locked
* anyway, so the signal receiver would come spin for nothing.
*/
must_notify = 1;
}
DPRINT_ovfl(("owner [%d] pending=%ld reason=%u ovfl_pmds=0x%lx ovfl_notify=0x%lx masked=%d\n",
GET_PMU_OWNER() ? task_pid_nr(GET_PMU_OWNER()) : -1,
PFM_GET_WORK_PENDING(task),
ctx->ctx_fl_trap_reason,
ovfl_pmds,
ovfl_notify,
ovfl_ctrl.bits.mask_monitoring ? 1 : 0));
/*
* in case monitoring must be stopped, we toggle the psr bits
*/
if (ovfl_ctrl.bits.mask_monitoring) {
pfm_mask_monitoring(task);
ctx->ctx_state = PFM_CTX_MASKED;
ctx->ctx_fl_can_restart = 1;
}
/*
* send notification now
*/
if (must_notify) pfm_ovfl_notify_user(ctx, ovfl_notify);
return;
sanity_check:
printk(KERN_ERR "perfmon: CPU%d overflow handler [%d] pmc0=0x%lx\n",
smp_processor_id(),
task ? task_pid_nr(task) : -1,
pmc0);
return;
stop_monitoring:
/*
* in SMP, zombie context is never restored but reclaimed in pfm_load_regs().
* Moreover, zombies are also reclaimed in pfm_save_regs(). Therefore we can
* come here as zombie only if the task is the current task. In which case, we
* can access the PMU hardware directly.
*
* Note that zombies do have PM_VALID set. So here we do the minimal.
*
* In case the context was zombified it could not be reclaimed at the time
* the monitoring program exited. At this point, the PMU reservation has been
* returned, the sampiing buffer has been freed. We must convert this call
* into a spurious interrupt. However, we must also avoid infinite overflows
* by stopping monitoring for this task. We can only come here for a per-task
* context. All we need to do is to stop monitoring using the psr bits which
* are always task private. By re-enabling secure montioring, we ensure that
* the monitored task will not be able to re-activate monitoring.
* The task will eventually be context switched out, at which point the context
* will be reclaimed (that includes releasing ownership of the PMU).
*
* So there might be a window of time where the number of per-task session is zero
* yet one PMU might have a owner and get at most one overflow interrupt for a zombie
* context. This is safe because if a per-task session comes in, it will push this one
* out and by the virtue on pfm_save_regs(), this one will disappear. If a system wide
* session is force on that CPU, given that we use task pinning, pfm_save_regs() will
* also push our zombie context out.
*
* Overall pretty hairy stuff....
*/
DPRINT(("ctx is zombie for [%d], converted to spurious\n", task ? task_pid_nr(task): -1));
pfm_clear_psr_up();
ia64_psr(regs)->up = 0;
ia64_psr(regs)->sp = 1;
return;
}
static int
pfm_do_interrupt_handler(void *arg, struct pt_regs *regs)
{
struct task_struct *task;
pfm_context_t *ctx;
unsigned long flags;
u64 pmc0;
int this_cpu = smp_processor_id();
int retval = 0;
pfm_stats[this_cpu].pfm_ovfl_intr_count++;
/*
* srlz.d done before arriving here
*/
pmc0 = ia64_get_pmc(0);
task = GET_PMU_OWNER();
ctx = GET_PMU_CTX();
/*
* if we have some pending bits set
* assumes : if any PMC0.bit[63-1] is set, then PMC0.fr = 1
*/
if (PMC0_HAS_OVFL(pmc0) && task) {
/*
* we assume that pmc0.fr is always set here
*/
/* sanity check */
if (!ctx) goto report_spurious1;
if (ctx->ctx_fl_system == 0 && (task->thread.flags & IA64_THREAD_PM_VALID) == 0)
goto report_spurious2;
PROTECT_CTX_NOPRINT(ctx, flags);
pfm_overflow_handler(task, ctx, pmc0, regs);
UNPROTECT_CTX_NOPRINT(ctx, flags);
} else {
pfm_stats[this_cpu].pfm_spurious_ovfl_intr_count++;
retval = -1;
}
/*
* keep it unfrozen at all times
*/
pfm_unfreeze_pmu();
return retval;
report_spurious1:
printk(KERN_INFO "perfmon: spurious overflow interrupt on CPU%d: process %d has no PFM context\n",
this_cpu, task_pid_nr(task));
pfm_unfreeze_pmu();
return -1;
report_spurious2:
printk(KERN_INFO "perfmon: spurious overflow interrupt on CPU%d: process %d, invalid flag\n",
this_cpu,
task_pid_nr(task));
pfm_unfreeze_pmu();
return -1;
}
static irqreturn_t
pfm_interrupt_handler(int irq, void *arg)
{
unsigned long start_cycles, total_cycles;
unsigned long min, max;
int this_cpu;
int ret;
struct pt_regs *regs = get_irq_regs();
this_cpu = get_cpu();
if (likely(!pfm_alt_intr_handler)) {
min = pfm_stats[this_cpu].pfm_ovfl_intr_cycles_min;
max = pfm_stats[this_cpu].pfm_ovfl_intr_cycles_max;
start_cycles = ia64_get_itc();
ret = pfm_do_interrupt_handler(arg, regs);
total_cycles = ia64_get_itc();
/*
* don't measure spurious interrupts
*/
if (likely(ret == 0)) {
total_cycles -= start_cycles;
if (total_cycles < min) pfm_stats[this_cpu].pfm_ovfl_intr_cycles_min = total_cycles;
if (total_cycles > max) pfm_stats[this_cpu].pfm_ovfl_intr_cycles_max = total_cycles;
pfm_stats[this_cpu].pfm_ovfl_intr_cycles += total_cycles;
}
}
else {
(*pfm_alt_intr_handler->handler)(irq, arg, regs);
}
put_cpu();
return IRQ_HANDLED;
}
/*
* /proc/perfmon interface, for debug only
*/
#define PFM_PROC_SHOW_HEADER ((void *)(long)nr_cpu_ids+1)
static void *
pfm_proc_start(struct seq_file *m, loff_t *pos)
{
if (*pos == 0) {
return PFM_PROC_SHOW_HEADER;
}
while (*pos <= nr_cpu_ids) {
if (cpu_online(*pos - 1)) {
return (void *)*pos;
}
++*pos;
}
return NULL;
}
static void *
pfm_proc_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return pfm_proc_start(m, pos);
}
static void
pfm_proc_stop(struct seq_file *m, void *v)
{
}
static void
pfm_proc_show_header(struct seq_file *m)
{
struct list_head * pos;
pfm_buffer_fmt_t * entry;
unsigned long flags;
seq_printf(m,
"perfmon version : %u.%u\n"
"model : %s\n"
"fastctxsw : %s\n"
"expert mode : %s\n"
"ovfl_mask : 0x%lx\n"
"PMU flags : 0x%x\n",
PFM_VERSION_MAJ, PFM_VERSION_MIN,
pmu_conf->pmu_name,
pfm_sysctl.fastctxsw > 0 ? "Yes": "No",
pfm_sysctl.expert_mode > 0 ? "Yes": "No",
pmu_conf->ovfl_val,
pmu_conf->flags);
LOCK_PFS(flags);
seq_printf(m,
"proc_sessions : %u\n"
"sys_sessions : %u\n"
"sys_use_dbregs : %u\n"
"ptrace_use_dbregs : %u\n",
pfm_sessions.pfs_task_sessions,
pfm_sessions.pfs_sys_sessions,
pfm_sessions.pfs_sys_use_dbregs,
pfm_sessions.pfs_ptrace_use_dbregs);
UNLOCK_PFS(flags);
spin_lock(&pfm_buffer_fmt_lock);
list_for_each(pos, &pfm_buffer_fmt_list) {
entry = list_entry(pos, pfm_buffer_fmt_t, fmt_list);
seq_printf(m, "format : %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x %s\n",
entry->fmt_uuid[0],
entry->fmt_uuid[1],
entry->fmt_uuid[2],
entry->fmt_uuid[3],
entry->fmt_uuid[4],
entry->fmt_uuid[5],
entry->fmt_uuid[6],
entry->fmt_uuid[7],
entry->fmt_uuid[8],
entry->fmt_uuid[9],
entry->fmt_uuid[10],
entry->fmt_uuid[11],
entry->fmt_uuid[12],
entry->fmt_uuid[13],
entry->fmt_uuid[14],
entry->fmt_uuid[15],
entry->fmt_name);
}
spin_unlock(&pfm_buffer_fmt_lock);
}
static int
pfm_proc_show(struct seq_file *m, void *v)
{
unsigned long psr;
unsigned int i;
int cpu;
if (v == PFM_PROC_SHOW_HEADER) {
pfm_proc_show_header(m);
return 0;
}
/* show info for CPU (v - 1) */
cpu = (long)v - 1;
seq_printf(m,
"CPU%-2d overflow intrs : %lu\n"
"CPU%-2d overflow cycles : %lu\n"
"CPU%-2d overflow min : %lu\n"
"CPU%-2d overflow max : %lu\n"
"CPU%-2d smpl handler calls : %lu\n"
"CPU%-2d smpl handler cycles : %lu\n"
"CPU%-2d spurious intrs : %lu\n"
"CPU%-2d replay intrs : %lu\n"
"CPU%-2d syst_wide : %d\n"
"CPU%-2d dcr_pp : %d\n"
"CPU%-2d exclude idle : %d\n"
"CPU%-2d owner : %d\n"
"CPU%-2d context : %p\n"
"CPU%-2d activations : %lu\n",
cpu, pfm_stats[cpu].pfm_ovfl_intr_count,
cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles,
cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles_min,
cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles_max,
cpu, pfm_stats[cpu].pfm_smpl_handler_calls,
cpu, pfm_stats[cpu].pfm_smpl_handler_cycles,
cpu, pfm_stats[cpu].pfm_spurious_ovfl_intr_count,
cpu, pfm_stats[cpu].pfm_replay_ovfl_intr_count,
cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_SYST_WIDE ? 1 : 0,
cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_DCR_PP ? 1 : 0,
cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_EXCL_IDLE ? 1 : 0,
cpu, pfm_get_cpu_data(pmu_owner, cpu) ? pfm_get_cpu_data(pmu_owner, cpu)->pid: -1,
cpu, pfm_get_cpu_data(pmu_ctx, cpu),
cpu, pfm_get_cpu_data(pmu_activation_number, cpu));
if (num_online_cpus() == 1 && pfm_sysctl.debug > 0) {
psr = pfm_get_psr();
ia64_srlz_d();
seq_printf(m,
"CPU%-2d psr : 0x%lx\n"
"CPU%-2d pmc0 : 0x%lx\n",
cpu, psr,
cpu, ia64_get_pmc(0));
for (i=0; PMC_IS_LAST(i) == 0; i++) {
if (PMC_IS_COUNTING(i) == 0) continue;
seq_printf(m,
"CPU%-2d pmc%u : 0x%lx\n"
"CPU%-2d pmd%u : 0x%lx\n",
cpu, i, ia64_get_pmc(i),
cpu, i, ia64_get_pmd(i));
}
}
return 0;
}
const struct seq_operations pfm_seq_ops = {
.start = pfm_proc_start,
.next = pfm_proc_next,
.stop = pfm_proc_stop,
.show = pfm_proc_show
};
static int
pfm_proc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &pfm_seq_ops);
}
/*
* we come here as soon as local_cpu_data->pfm_syst_wide is set. this happens
* during pfm_enable() hence before pfm_start(). We cannot assume monitoring
* is active or inactive based on mode. We must rely on the value in
* local_cpu_data->pfm_syst_info
*/
void
pfm_syst_wide_update_task(struct task_struct *task, unsigned long info, int is_ctxswin)
{
struct pt_regs *regs;
unsigned long dcr;
unsigned long dcr_pp;
dcr_pp = info & PFM_CPUINFO_DCR_PP ? 1 : 0;
/*
* pid 0 is guaranteed to be the idle task. There is one such task with pid 0
* on every CPU, so we can rely on the pid to identify the idle task.
*/
if ((info & PFM_CPUINFO_EXCL_IDLE) == 0 || task->pid) {
regs = task_pt_regs(task);
ia64_psr(regs)->pp = is_ctxswin ? dcr_pp : 0;
return;
}
/*
* if monitoring has started
*/
if (dcr_pp) {
dcr = ia64_getreg(_IA64_REG_CR_DCR);
/*
* context switching in?
*/
if (is_ctxswin) {
/* mask monitoring for the idle task */
ia64_setreg(_IA64_REG_CR_DCR, dcr & ~IA64_DCR_PP);
pfm_clear_psr_pp();
ia64_srlz_i();
return;
}
/*
* context switching out
* restore monitoring for next task
*
* Due to inlining this odd if-then-else construction generates
* better code.
*/
ia64_setreg(_IA64_REG_CR_DCR, dcr |IA64_DCR_PP);
pfm_set_psr_pp();
ia64_srlz_i();
}
}
#ifdef CONFIG_SMP
static void
pfm_force_cleanup(pfm_context_t *ctx, struct pt_regs *regs)
{
struct task_struct *task = ctx->ctx_task;
ia64_psr(regs)->up = 0;
ia64_psr(regs)->sp = 1;
if (GET_PMU_OWNER() == task) {
DPRINT(("cleared ownership for [%d]\n",
task_pid_nr(ctx->ctx_task)));
SET_PMU_OWNER(NULL, NULL);
}
/*
* disconnect the task from the context and vice-versa
*/
PFM_SET_WORK_PENDING(task, 0);
task->thread.pfm_context = NULL;
task->thread.flags &= ~IA64_THREAD_PM_VALID;
DPRINT(("force cleanup for [%d]\n", task_pid_nr(task)));
}
/*
* in 2.6, interrupts are masked when we come here and the runqueue lock is held
*/
void
pfm_save_regs(struct task_struct *task)
{
pfm_context_t *ctx;
unsigned long flags;
u64 psr;
ctx = PFM_GET_CTX(task);
if (ctx == NULL) return;
/*
* we always come here with interrupts ALREADY disabled by
* the scheduler. So we simply need to protect against concurrent
* access, not CPU concurrency.
*/
flags = pfm_protect_ctx_ctxsw(ctx);
if (ctx->ctx_state == PFM_CTX_ZOMBIE) {
struct pt_regs *regs = task_pt_regs(task);
pfm_clear_psr_up();
pfm_force_cleanup(ctx, regs);
BUG_ON(ctx->ctx_smpl_hdr);
pfm_unprotect_ctx_ctxsw(ctx, flags);
pfm_context_free(ctx);
return;
}
/*
* save current PSR: needed because we modify it
*/
ia64_srlz_d();
psr = pfm_get_psr();
BUG_ON(psr & (IA64_PSR_I));
/*
* stop monitoring:
* This is the last instruction which may generate an overflow
*
* We do not need to set psr.sp because, it is irrelevant in kernel.
* It will be restored from ipsr when going back to user level
*/
pfm_clear_psr_up();
/*
* keep a copy of psr.up (for reload)
*/
ctx->ctx_saved_psr_up = psr & IA64_PSR_UP;
/*
* release ownership of this PMU.
* PM interrupts are masked, so nothing
* can happen.
*/
SET_PMU_OWNER(NULL, NULL);
/*
* we systematically save the PMD as we have no
* guarantee we will be schedule at that same
* CPU again.
*/
pfm_save_pmds(ctx->th_pmds, ctx->ctx_used_pmds[0]);
/*
* save pmc0 ia64_srlz_d() done in pfm_save_pmds()
* we will need it on the restore path to check
* for pending overflow.
*/
ctx->th_pmcs[0] = ia64_get_pmc(0);
/*
* unfreeze PMU if had pending overflows
*/
if (ctx->th_pmcs[0] & ~0x1UL) pfm_unfreeze_pmu();
/*
* finally, allow context access.
* interrupts will still be masked after this call.
*/
pfm_unprotect_ctx_ctxsw(ctx, flags);
}
#else /* !CONFIG_SMP */
void
pfm_save_regs(struct task_struct *task)
{
pfm_context_t *ctx;
u64 psr;
ctx = PFM_GET_CTX(task);
if (ctx == NULL) return;
/*
* save current PSR: needed because we modify it
*/
psr = pfm_get_psr();
BUG_ON(psr & (IA64_PSR_I));
/*
* stop monitoring:
* This is the last instruction which may generate an overflow
*
* We do not need to set psr.sp because, it is irrelevant in kernel.
* It will be restored from ipsr when going back to user level
*/
pfm_clear_psr_up();
/*
* keep a copy of psr.up (for reload)
*/
ctx->ctx_saved_psr_up = psr & IA64_PSR_UP;
}
static void
pfm_lazy_save_regs (struct task_struct *task)
{
pfm_context_t *ctx;
unsigned long flags;
{ u64 psr = pfm_get_psr();
BUG_ON(psr & IA64_PSR_UP);
}
ctx = PFM_GET_CTX(task);
/*
* we need to mask PMU overflow here to
* make sure that we maintain pmc0 until
* we save it. overflow interrupts are
* treated as spurious if there is no
* owner.
*
* XXX: I don't think this is necessary
*/
PROTECT_CTX(ctx,flags);
/*
* release ownership of this PMU.
* must be done before we save the registers.
*
* after this call any PMU interrupt is treated
* as spurious.
*/
SET_PMU_OWNER(NULL, NULL);
/*
* save all the pmds we use
*/
pfm_save_pmds(ctx->th_pmds, ctx->ctx_used_pmds[0]);
/*
* save pmc0 ia64_srlz_d() done in pfm_save_pmds()
* it is needed to check for pended overflow
* on the restore path
*/
ctx->th_pmcs[0] = ia64_get_pmc(0);
/*
* unfreeze PMU if had pending overflows
*/
if (ctx->th_pmcs[0] & ~0x1UL) pfm_unfreeze_pmu();
/*
* now get can unmask PMU interrupts, they will
* be treated as purely spurious and we will not
* lose any information
*/
UNPROTECT_CTX(ctx,flags);
}
#endif /* CONFIG_SMP */
#ifdef CONFIG_SMP
/*
* in 2.6, interrupts are masked when we come here and the runqueue lock is held
*/
void
pfm_load_regs (struct task_struct *task)
{
pfm_context_t *ctx;
unsigned long pmc_mask = 0UL, pmd_mask = 0UL;
unsigned long flags;
u64 psr, psr_up;
int need_irq_resend;
ctx = PFM_GET_CTX(task);
if (unlikely(ctx == NULL)) return;
BUG_ON(GET_PMU_OWNER());
/*
* possible on unload
*/
if (unlikely((task->thread.flags & IA64_THREAD_PM_VALID) == 0)) return;
/*
* we always come here with interrupts ALREADY disabled by
* the scheduler. So we simply need to protect against concurrent
* access, not CPU concurrency.
*/
flags = pfm_protect_ctx_ctxsw(ctx);
psr = pfm_get_psr();
need_irq_resend = pmu_conf->flags & PFM_PMU_IRQ_RESEND;
BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
BUG_ON(psr & IA64_PSR_I);
if (unlikely(ctx->ctx_state == PFM_CTX_ZOMBIE)) {
struct pt_regs *regs = task_pt_regs(task);
BUG_ON(ctx->ctx_smpl_hdr);
pfm_force_cleanup(ctx, regs);
pfm_unprotect_ctx_ctxsw(ctx, flags);
/*
* this one (kmalloc'ed) is fine with interrupts disabled
*/
pfm_context_free(ctx);
return;
}
/*
* we restore ALL the debug registers to avoid picking up
* stale state.
*/
if (ctx->ctx_fl_using_dbreg) {
pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
}
/*
* retrieve saved psr.up
*/
psr_up = ctx->ctx_saved_psr_up;
/*
* if we were the last user of the PMU on that CPU,
* then nothing to do except restore psr
*/
if (GET_LAST_CPU(ctx) == smp_processor_id() && ctx->ctx_last_activation == GET_ACTIVATION()) {
/*
* retrieve partial reload masks (due to user modifications)
*/
pmc_mask = ctx->ctx_reload_pmcs[0];
pmd_mask = ctx->ctx_reload_pmds[0];
} else {
/*
* To avoid leaking information to the user level when psr.sp=0,
* we must reload ALL implemented pmds (even the ones we don't use).
* In the kernel we only allow PFM_READ_PMDS on registers which
* we initialized or requested (sampling) so there is no risk there.
*/
pmd_mask = pfm_sysctl.fastctxsw ? ctx->ctx_used_pmds[0] : ctx->ctx_all_pmds[0];
/*
* ALL accessible PMCs are systematically reloaded, unused registers
* get their default (from pfm_reset_pmu_state()) values to avoid picking
* up stale configuration.
*
* PMC0 is never in the mask. It is always restored separately.
*/
pmc_mask = ctx->ctx_all_pmcs[0];
}
/*
* when context is MASKED, we will restore PMC with plm=0
* and PMD with stale information, but that's ok, nothing
* will be captured.
*
* XXX: optimize here
*/
if (pmd_mask) pfm_restore_pmds(ctx->th_pmds, pmd_mask);
if (pmc_mask) pfm_restore_pmcs(ctx->th_pmcs, pmc_mask);
/*
* check for pending overflow at the time the state
* was saved.
*/
if (unlikely(PMC0_HAS_OVFL(ctx->th_pmcs[0]))) {
/*
* reload pmc0 with the overflow information
* On McKinley PMU, this will trigger a PMU interrupt
*/
ia64_set_pmc(0, ctx->th_pmcs[0]);
ia64_srlz_d();
ctx->th_pmcs[0] = 0UL;
/*
* will replay the PMU interrupt
*/
if (need_irq_resend) ia64_resend_irq(IA64_PERFMON_VECTOR);
pfm_stats[smp_processor_id()].pfm_replay_ovfl_intr_count++;
}
/*
* we just did a reload, so we reset the partial reload fields
*/
ctx->ctx_reload_pmcs[0] = 0UL;
ctx->ctx_reload_pmds[0] = 0UL;
SET_LAST_CPU(ctx, smp_processor_id());
/*
* dump activation value for this PMU
*/
INC_ACTIVATION();
/*
* record current activation for this context
*/
SET_ACTIVATION(ctx);
/*
* establish new ownership.
*/
SET_PMU_OWNER(task, ctx);
/*
* restore the psr.up bit. measurement
* is active again.
* no PMU interrupt can happen at this point
* because we still have interrupts disabled.
*/
if (likely(psr_up)) pfm_set_psr_up();
/*
* allow concurrent access to context
*/
pfm_unprotect_ctx_ctxsw(ctx, flags);
}
#else /* !CONFIG_SMP */
/*
* reload PMU state for UP kernels
* in 2.5 we come here with interrupts disabled
*/
void
pfm_load_regs (struct task_struct *task)
{
pfm_context_t *ctx;
struct task_struct *owner;
unsigned long pmd_mask, pmc_mask;
u64 psr, psr_up;
int need_irq_resend;
owner = GET_PMU_OWNER();
ctx = PFM_GET_CTX(task);
psr = pfm_get_psr();
BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
BUG_ON(psr & IA64_PSR_I);
/*
* we restore ALL the debug registers to avoid picking up
* stale state.
*
* This must be done even when the task is still the owner
* as the registers may have been modified via ptrace()
* (not perfmon) by the previous task.
*/
if (ctx->ctx_fl_using_dbreg) {
pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
}
/*
* retrieved saved psr.up
*/
psr_up = ctx->ctx_saved_psr_up;
need_irq_resend = pmu_conf->flags & PFM_PMU_IRQ_RESEND;
/*
* short path, our state is still there, just
* need to restore psr and we go
*
* we do not touch either PMC nor PMD. the psr is not touched
* by the overflow_handler. So we are safe w.r.t. to interrupt
* concurrency even without interrupt masking.
*/
if (likely(owner == task)) {
if (likely(psr_up)) pfm_set_psr_up();
return;
}
/*
* someone else is still using the PMU, first push it out and
* then we'll be able to install our stuff !
*
* Upon return, there will be no owner for the current PMU
*/
if (owner) pfm_lazy_save_regs(owner);
/*
* To avoid leaking information to the user level when psr.sp=0,
* we must reload ALL implemented pmds (even the ones we don't use).
* In the kernel we only allow PFM_READ_PMDS on registers which
* we initialized or requested (sampling) so there is no risk there.
*/
pmd_mask = pfm_sysctl.fastctxsw ? ctx->ctx_used_pmds[0] : ctx->ctx_all_pmds[0];
/*
* ALL accessible PMCs are systematically reloaded, unused registers
* get their default (from pfm_reset_pmu_state()) values to avoid picking
* up stale configuration.
*
* PMC0 is never in the mask. It is always restored separately
*/
pmc_mask = ctx->ctx_all_pmcs[0];
pfm_restore_pmds(ctx->th_pmds, pmd_mask);
pfm_restore_pmcs(ctx->th_pmcs, pmc_mask);
/*
* check for pending overflow at the time the state
* was saved.
*/
if (unlikely(PMC0_HAS_OVFL(ctx->th_pmcs[0]))) {
/*
* reload pmc0 with the overflow information
* On McKinley PMU, this will trigger a PMU interrupt
*/
ia64_set_pmc(0, ctx->th_pmcs[0]);
ia64_srlz_d();
ctx->th_pmcs[0] = 0UL;
/*
* will replay the PMU interrupt
*/
if (need_irq_resend) ia64_resend_irq(IA64_PERFMON_VECTOR);
pfm_stats[smp_processor_id()].pfm_replay_ovfl_intr_count++;
}
/*
* establish new ownership.
*/
SET_PMU_OWNER(task, ctx);
/*
* restore the psr.up bit. measurement
* is active again.
* no PMU interrupt can happen at this point
* because we still have interrupts disabled.
*/
if (likely(psr_up)) pfm_set_psr_up();
}
#endif /* CONFIG_SMP */
/*
* this function assumes monitoring is stopped
*/
static void
pfm_flush_pmds(struct task_struct *task, pfm_context_t *ctx)
{
u64 pmc0;
unsigned long mask2, val, pmd_val, ovfl_val;
int i, can_access_pmu = 0;
int is_self;
/*
* is the caller the task being monitored (or which initiated the
* session for system wide measurements)
*/
is_self = ctx->ctx_task == task ? 1 : 0;
/*
* can access PMU is task is the owner of the PMU state on the current CPU
* or if we are running on the CPU bound to the context in system-wide mode
* (that is not necessarily the task the context is attached to in this mode).
* In system-wide we always have can_access_pmu true because a task running on an
* invalid processor is flagged earlier in the call stack (see pfm_stop).
*/
can_access_pmu = (GET_PMU_OWNER() == task) || (ctx->ctx_fl_system && ctx->ctx_cpu == smp_processor_id());
if (can_access_pmu) {
/*
* Mark the PMU as not owned
* This will cause the interrupt handler to do nothing in case an overflow
* interrupt was in-flight
* This also guarantees that pmc0 will contain the final state
* It virtually gives us full control on overflow processing from that point
* on.
*/
SET_PMU_OWNER(NULL, NULL);
DPRINT(("releasing ownership\n"));
/*
* read current overflow status:
*
* we are guaranteed to read the final stable state
*/
ia64_srlz_d();
pmc0 = ia64_get_pmc(0); /* slow */
/*
* reset freeze bit, overflow status information destroyed
*/
pfm_unfreeze_pmu();
} else {
pmc0 = ctx->th_pmcs[0];
/*
* clear whatever overflow status bits there were
*/
ctx->th_pmcs[0] = 0;
}
ovfl_val = pmu_conf->ovfl_val;
/*
* we save all the used pmds
* we take care of overflows for counting PMDs
*
* XXX: sampling situation is not taken into account here
*/
mask2 = ctx->ctx_used_pmds[0];
DPRINT(("is_self=%d ovfl_val=0x%lx mask2=0x%lx\n", is_self, ovfl_val, mask2));
for (i = 0; mask2; i++, mask2>>=1) {
/* skip non used pmds */
if ((mask2 & 0x1) == 0) continue;
/*
* can access PMU always true in system wide mode
*/
val = pmd_val = can_access_pmu ? ia64_get_pmd(i) : ctx->th_pmds[i];
if (PMD_IS_COUNTING(i)) {
DPRINT(("[%d] pmd[%d] ctx_pmd=0x%lx hw_pmd=0x%lx\n",
task_pid_nr(task),
i,
ctx->ctx_pmds[i].val,
val & ovfl_val));
/*
* we rebuild the full 64 bit value of the counter
*/
val = ctx->ctx_pmds[i].val + (val & ovfl_val);
/*
* now everything is in ctx_pmds[] and we need
* to clear the saved context from save_regs() such that
* pfm_read_pmds() gets the correct value
*/
pmd_val = 0UL;
/*
* take care of overflow inline
*/
if (pmc0 & (1UL << i)) {
val += 1 + ovfl_val;
DPRINT(("[%d] pmd[%d] overflowed\n", task_pid_nr(task), i));
}
}
DPRINT(("[%d] ctx_pmd[%d]=0x%lx pmd_val=0x%lx\n", task_pid_nr(task), i, val, pmd_val));
if (is_self) ctx->th_pmds[i] = pmd_val;
ctx->ctx_pmds[i].val = val;
}
}
static struct irqaction perfmon_irqaction = {
.handler = pfm_interrupt_handler,
.flags = IRQF_DISABLED,
.name = "perfmon"
};
static void
pfm_alt_save_pmu_state(void *data)
{
struct pt_regs *regs;
regs = task_pt_regs(current);
DPRINT(("called\n"));
/*
* should not be necessary but
* let's take not risk
*/
pfm_clear_psr_up();
pfm_clear_psr_pp();
ia64_psr(regs)->pp = 0;
/*
* This call is required
* May cause a spurious interrupt on some processors
*/
pfm_freeze_pmu();
ia64_srlz_d();
}
void
pfm_alt_restore_pmu_state(void *data)
{
struct pt_regs *regs;
regs = task_pt_regs(current);
DPRINT(("called\n"));
/*
* put PMU back in state expected
* by perfmon
*/
pfm_clear_psr_up();
pfm_clear_psr_pp();
ia64_psr(regs)->pp = 0;
/*
* perfmon runs with PMU unfrozen at all times
*/
pfm_unfreeze_pmu();
ia64_srlz_d();
}
int
pfm_install_alt_pmu_interrupt(pfm_intr_handler_desc_t *hdl)
{
int ret, i;
int reserve_cpu;
/* some sanity checks */
if (hdl == NULL || hdl->handler == NULL) return -EINVAL;
/* do the easy test first */
if (pfm_alt_intr_handler) return -EBUSY;
/* one at a time in the install or remove, just fail the others */
if (!spin_trylock(&pfm_alt_install_check)) {
return -EBUSY;
}
/* reserve our session */
for_each_online_cpu(reserve_cpu) {
ret = pfm_reserve_session(NULL, 1, reserve_cpu);
if (ret) goto cleanup_reserve;
}
/* save the current system wide pmu states */
ret = on_each_cpu(pfm_alt_save_pmu_state, NULL, 1);
if (ret) {
DPRINT(("on_each_cpu() failed: %d\n", ret));
goto cleanup_reserve;
}
/* officially change to the alternate interrupt handler */
pfm_alt_intr_handler = hdl;
spin_unlock(&pfm_alt_install_check);
return 0;
cleanup_reserve:
for_each_online_cpu(i) {
/* don't unreserve more than we reserved */
if (i >= reserve_cpu) break;
pfm_unreserve_session(NULL, 1, i);
}
spin_unlock(&pfm_alt_install_check);
return ret;
}
EXPORT_SYMBOL_GPL(pfm_install_alt_pmu_interrupt);
int
pfm_remove_alt_pmu_interrupt(pfm_intr_handler_desc_t *hdl)
{
int i;
int ret;
if (hdl == NULL) return -EINVAL;
/* cannot remove someone else's handler! */
if (pfm_alt_intr_handler != hdl) return -EINVAL;
/* one at a time in the install or remove, just fail the others */
if (!spin_trylock(&pfm_alt_install_check)) {
return -EBUSY;
}
pfm_alt_intr_handler = NULL;
ret = on_each_cpu(pfm_alt_restore_pmu_state, NULL, 1);
if (ret) {
DPRINT(("on_each_cpu() failed: %d\n", ret));
}
for_each_online_cpu(i) {
pfm_unreserve_session(NULL, 1, i);
}
spin_unlock(&pfm_alt_install_check);
return 0;
}
EXPORT_SYMBOL_GPL(pfm_remove_alt_pmu_interrupt);
/*
* perfmon initialization routine, called from the initcall() table
*/
static int init_pfm_fs(void);
static int __init
pfm_probe_pmu(void)
{
pmu_config_t **p;
int family;
family = local_cpu_data->family;
p = pmu_confs;
while(*p) {
if ((*p)->probe) {
if ((*p)->probe() == 0) goto found;
} else if ((*p)->pmu_family == family || (*p)->pmu_family == 0xff) {
goto found;
}
p++;
}
return -1;
found:
pmu_conf = *p;
return 0;
}
static const struct file_operations pfm_proc_fops = {
.open = pfm_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
int __init
pfm_init(void)
{
unsigned int n, n_counters, i;
printk("perfmon: version %u.%u IRQ %u\n",
PFM_VERSION_MAJ,
PFM_VERSION_MIN,
IA64_PERFMON_VECTOR);
if (pfm_probe_pmu()) {
printk(KERN_INFO "perfmon: disabled, there is no support for processor family %d\n",
local_cpu_data->family);
return -ENODEV;
}
/*
* compute the number of implemented PMD/PMC from the
* description tables
*/
n = 0;
for (i=0; PMC_IS_LAST(i) == 0; i++) {
if (PMC_IS_IMPL(i) == 0) continue;
pmu_conf->impl_pmcs[i>>6] |= 1UL << (i&63);
n++;
}
pmu_conf->num_pmcs = n;
n = 0; n_counters = 0;
for (i=0; PMD_IS_LAST(i) == 0; i++) {
if (PMD_IS_IMPL(i) == 0) continue;
pmu_conf->impl_pmds[i>>6] |= 1UL << (i&63);
n++;
if (PMD_IS_COUNTING(i)) n_counters++;
}
pmu_conf->num_pmds = n;
pmu_conf->num_counters = n_counters;
/*
* sanity checks on the number of debug registers
*/
if (pmu_conf->use_rr_dbregs) {
if (pmu_conf->num_ibrs > IA64_NUM_DBG_REGS) {
printk(KERN_INFO "perfmon: unsupported number of code debug registers (%u)\n", pmu_conf->num_ibrs);
pmu_conf = NULL;
return -1;
}
if (pmu_conf->num_dbrs > IA64_NUM_DBG_REGS) {
printk(KERN_INFO "perfmon: unsupported number of data debug registers (%u)\n", pmu_conf->num_ibrs);
pmu_conf = NULL;
return -1;
}
}
printk("perfmon: %s PMU detected, %u PMCs, %u PMDs, %u counters (%lu bits)\n",
pmu_conf->pmu_name,
pmu_conf->num_pmcs,
pmu_conf->num_pmds,
pmu_conf->num_counters,
ffz(pmu_conf->ovfl_val));
/* sanity check */
if (pmu_conf->num_pmds >= PFM_NUM_PMD_REGS || pmu_conf->num_pmcs >= PFM_NUM_PMC_REGS) {
printk(KERN_ERR "perfmon: not enough pmc/pmd, perfmon disabled\n");
pmu_conf = NULL;
return -1;
}
/*
* create /proc/perfmon (mostly for debugging purposes)
*/
perfmon_dir = proc_create("perfmon", S_IRUGO, NULL, &pfm_proc_fops);
if (perfmon_dir == NULL) {
printk(KERN_ERR "perfmon: cannot create /proc entry, perfmon disabled\n");
pmu_conf = NULL;
return -1;
}
/*
* create /proc/sys/kernel/perfmon (for debugging purposes)
*/
pfm_sysctl_header = register_sysctl_table(pfm_sysctl_root);
/*
* initialize all our spinlocks
*/
spin_lock_init(&pfm_sessions.pfs_lock);
spin_lock_init(&pfm_buffer_fmt_lock);
init_pfm_fs();
for(i=0; i < NR_CPUS; i++) pfm_stats[i].pfm_ovfl_intr_cycles_min = ~0UL;
return 0;
}
__initcall(pfm_init);
/*
* this function is called before pfm_init()
*/
void
pfm_init_percpu (void)
{
static int first_time=1;
/*
* make sure no measurement is active
* (may inherit programmed PMCs from EFI).
*/
pfm_clear_psr_pp();
pfm_clear_psr_up();
/*
* we run with the PMU not frozen at all times
*/
pfm_unfreeze_pmu();
if (first_time) {
register_percpu_irq(IA64_PERFMON_VECTOR, &perfmon_irqaction);
first_time=0;
}
ia64_setreg(_IA64_REG_CR_PMV, IA64_PERFMON_VECTOR);
ia64_srlz_d();
}
/*
* used for debug purposes only
*/
void
dump_pmu_state(const char *from)
{
struct task_struct *task;
struct pt_regs *regs;
pfm_context_t *ctx;
unsigned long psr, dcr, info, flags;
int i, this_cpu;
local_irq_save(flags);
this_cpu = smp_processor_id();
regs = task_pt_regs(current);
info = PFM_CPUINFO_GET();
dcr = ia64_getreg(_IA64_REG_CR_DCR);
if (info == 0 && ia64_psr(regs)->pp == 0 && (dcr & IA64_DCR_PP) == 0) {
local_irq_restore(flags);
return;
}
printk("CPU%d from %s() current [%d] iip=0x%lx %s\n",
this_cpu,
from,
task_pid_nr(current),
regs->cr_iip,
current->comm);
task = GET_PMU_OWNER();
ctx = GET_PMU_CTX();
printk("->CPU%d owner [%d] ctx=%p\n", this_cpu, task ? task_pid_nr(task) : -1, ctx);
psr = pfm_get_psr();
printk("->CPU%d pmc0=0x%lx psr.pp=%d psr.up=%d dcr.pp=%d syst_info=0x%lx user_psr.up=%d user_psr.pp=%d\n",
this_cpu,
ia64_get_pmc(0),
psr & IA64_PSR_PP ? 1 : 0,
psr & IA64_PSR_UP ? 1 : 0,
dcr & IA64_DCR_PP ? 1 : 0,
info,
ia64_psr(regs)->up,
ia64_psr(regs)->pp);
ia64_psr(regs)->up = 0;
ia64_psr(regs)->pp = 0;
for (i=1; PMC_IS_LAST(i) == 0; i++) {
if (PMC_IS_IMPL(i) == 0) continue;
printk("->CPU%d pmc[%d]=0x%lx thread_pmc[%d]=0x%lx\n", this_cpu, i, ia64_get_pmc(i), i, ctx->th_pmcs[i]);
}
for (i=1; PMD_IS_LAST(i) == 0; i++) {
if (PMD_IS_IMPL(i) == 0) continue;
printk("->CPU%d pmd[%d]=0x%lx thread_pmd[%d]=0x%lx\n", this_cpu, i, ia64_get_pmd(i), i, ctx->th_pmds[i]);
}
if (ctx) {
printk("->CPU%d ctx_state=%d vaddr=%p addr=%p fd=%d ctx_task=[%d] saved_psr_up=0x%lx\n",
this_cpu,
ctx->ctx_state,
ctx->ctx_smpl_vaddr,
ctx->ctx_smpl_hdr,
ctx->ctx_msgq_head,
ctx->ctx_msgq_tail,
ctx->ctx_saved_psr_up);
}
local_irq_restore(flags);
}
/*
* called from process.c:copy_thread(). task is new child.
*/
void
pfm_inherit(struct task_struct *task, struct pt_regs *regs)
{
struct thread_struct *thread;
DPRINT(("perfmon: pfm_inherit clearing state for [%d]\n", task_pid_nr(task)));
thread = &task->thread;
/*
* cut links inherited from parent (current)
*/
thread->pfm_context = NULL;
PFM_SET_WORK_PENDING(task, 0);
/*
* the psr bits are already set properly in copy_threads()
*/
}
#else /* !CONFIG_PERFMON */
asmlinkage long
sys_perfmonctl (int fd, int cmd, void *arg, int count)
{
return -ENOSYS;
}
#endif /* CONFIG_PERFMON */
| leftrepo/Owl-Kernel-for-Xperia-Sola | arch/ia64/kernel/perfmon.c | C | gpl-2.0 | 172,407 |
require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb')
given "a message exists" do
Message.all.destroy!
request(resource(:messages), :method => "POST",
:params => { :message => { :id => nil }})
end
describe "resource(:messages)" do
describe "GET" do
before(:each) do
@response = request(resource(:messages))
end
it "responds successfully" do
@response.should be_successful
end
it "contains a list of messages" do
pending
@response.should have_xpath("//ul")
end
end
describe "GET", :given => "a message exists" do
before(:each) do
@response = request(resource(:messages))
end
it "has a list of messages" do
pending
@response.should have_xpath("//ul/li")
end
end
describe "a successful POST" do
before(:each) do
Message.all.destroy!
@response = request(resource(:messages), :method => "POST",
:params => { :message => { :id => nil }})
end
it "redirects to resource(:messages)" do
@response.should redirect_to(resource(Message.first), :message => {:notice => "message was successfully created"})
end
end
end
describe "resource(@message)" do
describe "a successful DELETE", :given => "a message exists" do
before(:each) do
@response = request(resource(Message.first), :method => "DELETE")
end
it "should redirect to the index action" do
@response.should redirect_to(resource(:messages))
end
end
end
describe "resource(:messages, :new)" do
before(:each) do
@response = request(resource(:messages, :new))
end
it "responds successfully" do
@response.should be_successful
end
end
describe "resource(@message, :edit)", :given => "a message exists" do
before(:each) do
@response = request(resource(Message.first, :edit))
end
it "responds successfully" do
@response.should be_successful
end
end
describe "resource(@message)", :given => "a message exists" do
describe "GET" do
before(:each) do
@response = request(resource(Message.first))
end
it "responds successfully" do
@response.should be_successful
end
end
describe "PUT" do
before(:each) do
@message = Message.first
@response = request(resource(@message), :method => "PUT",
:params => { :message => {:id => @message.id} })
end
it "redirect to the article show action" do
@response.should redirect_to(resource(@message))
end
end
end
| alfanick/irc-logger | spec/requests/messages_spec.rb | Ruby | gpl-2.0 | 2,551 |
<?php
if (isset($_POST['_wpcf7_mail_sent'])) {
$expire=time()+60*60*24*30*2;
setcookie("surveySent2", "true", $expire, '/');
}
/*************
!!!!!!!IMPORTANT!!!!!!!!
If you change the styles then edit the stylesheet querystring here!
*************/
?><!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 profile="http://gmpg.org/xfn/11">
<title><?php bloginfo('name'); ?><?php wp_title(); ?></title>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<link rel="stylesheet" href="/wp-content/themes/aparatus/css.php?a=16" type="text/css" media="screen" />
<?php global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] );
}
} ?>
<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="<?php bloginfo('rss2_url'); ?>" />
<link rel="alternate" type="text/xml" title="RSS .92" href="<?php bloginfo('rss_url'); ?>" />
<link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="<?php bloginfo('atom_url'); ?>" />
<!--[if gte IE 7]>
<link href="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_directory')); ?>/forie8.css" rel="stylesheet" type="text/css" media="screen" title="no title" charset="utf-8"/>
<![endif]-->
<!--[if lt IE 7]>
<link href="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_directory')); ?>/forie6.css" rel="stylesheet" type="text/css" media="screen" title="no title" charset="utf-8"/>
<![endif]-->
<!--[if IE 7]>
<link href="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_directory')); ?>/forie7.css" rel="stylesheet" type="text/css" media="screen" title="no title" charset="utf-8"/>
<![endif]-->
<!--Css SmoothGallery-->
<link rel="stylesheet" href="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url')); ?>/gallery-css/jd.gallery.css" type="text/css" media="screen"/>
<?php wp_enqueue_script("jquery"); ?>
<script type="text/javascript" src="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url')); ?>/scripts/mootools.js"></script>
<script type="text/javascript" src="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url')); ?>/scripts/jd.gallery.js"></script>
<script type="text/javascript" src="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url')); ?>/scripts/mootabs1.2.js"></script>
<script type="text/javascript" src="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url'));; ?>/scripts/cufon-yui.js"></script>
<script type="text/javascript" src="<?php echo str_replace("http://www.thephotographyparlour.com/","/",get_bloginfo('template_url')); ?>/scripts/League_Gothic_400.font.js"></script>
<?php wp_get_archives('type=monthly&format=link'); ?>
<?php //comments_popup_script(); // off by default ?>
<?php wp_head(); ?>
<script type="text/javascript">/*<![CDATA[*/Cufon.replace('a#logo',{fontSize:'98px',lineHeight:'98px'});/*]]>*/</script>
<script type="text/javascript">/*<![CDATA[*/
jQuery(document).ready(function () {
jQuery('#nav2 ul li').each(function (i) {
jQuery(this).mouseenter(function () {
jQuery(this).addClass("sfhover");
});
jQuery(this).mouseleave(function () {
jQuery(this).removeClass("sfhover");
});
});
});
<?php /* old code
<?php } else { ?>
sfHover = function() {
var sfEls = document.getElementById("nav2").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhoverb"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
<?php } ?>
<?php */ ?>
/*]]>*/
</script>
<script type="text/javascript" charset="utf-8">/*<![CDATA[*/
window.addEvent('domready', init);
function init() {
myTabs1 = new mootabs('myTabs', {height: '320px', width: '300px', changeTransition: Fx.Transitions.Back.easeOut, mouseOverClass: 'over'});
}
/*]]>*/</script>
<meta name="google-site-verification" content="QlCldWYkiMZwNFqnwTJ-dPgrwhlKK7S8VXQniIfqoD8" />
<meta name="generator" content="WordPress <?php bloginfo('version'); ?>" />
<?php wp_head();flush(); ?>
</head>
<body>
<div class="bodywrapper">
<div id="header"><?php
/** header **/
?><div id="twitter-badge"><a href="http://twitter.com/<?php if ($apa_Twitter == ''){echo '_fearlessflyer';}else{echo $apa_Twitter;} ?>" onclick="pageTracker._trackEvent('Twitter', 'Follow me');" >follow</a></div><!--twitter-badge-->
<?php if (is_front_page()) { ?><h1><?php } ?><a id="logo" href="<?php bloginfo('url');?>"><?php bloginfo('name');?></a><?php if (is_front_page()) { ?></h1><?php } ?>
<?php if (is_front_page()) { ?><h2 style="float:left;margin:-20px 0 10px 10px;font-family:verdana,arial,helvetica;font-size:10px;font-weight:bold;">Where aspiring photographers <span style="font-size:11px;font-style:italic;color:#750000">click</span> with the pros</h2><?php } else { ?>
<p style="float:left;margin:-20px 0 10px 10px;font-family:verdana,arial,helvetica;font-size:10px;font-weight:bold;">Where aspiring photographers <span style="color:#750000;font-style:italic;font-size:11px;">click</span> with the pros</p>
<?php } ?>
<div id="navigation">
<div id="page-nav">
<ul>
<li id="welcome" class="current_page_item2"><a href="<?php bloginfo('url');?>" title="Home">Welcome</a></li>
<li class="cat-item cat-page<?php if (is_page('2')) { ?> current-cat<?php } ?>"><a href="/about/" title="About the Photography Parlour">About</a></li>
<li class="cat-item cat-page"><a href="/forum/" title="photography forum">Forum</a></li>
<li class="cat-item cat-page"><a href="/shop/" title="photography shop">Shop</a></li>
<li class="cat-item cat-page"><a href="/info-for-advertisers/" title="photography Advertising Information">Advertise</a></li>
<li class="cat-item cat-page"><a href="/media-center/" title="Photography Media Center">Media Center</a></li>
<li class="cat-item cat-page"><a href="/2010/05/contribute-to-the-photography-parlour/1937" title="Contribute to The Photography Parlour">Contribute</a></li>
<li class="cat-item cat-page"><a href="/contact/" title="contact the photography parlour team">Contact</a></li>
</ul>
<span id="login"><?php /* <a href="<?php echo get_option('home'); ?>/wp-admin/">Login to Site</a>
<a href="/info-for-advertisers/" title="Information for Advertisers">Advertising Info</a>*/ ?>
<a href="http://www.twitter.com/photoparlour/" onclick="pageTracker._trackEvent('Twitter', 'twitter sign up');" title="follow us on twitter" class="toptwitter"></a><a href="http://www.facebook.com/thephotographyparlour/" title="follow us on facebook" class="topfacebook" onclick="pageTracker._trackEvent('facebook', 'facebook sign up');"></a>
<a class="rss" href="http://feeds.feedburner.com/thephotographyparlour" onclick="pageTracker._trackEvent('RSS', 'RSS FEED sign up');"></a>
</span>
</div><!--page-nav-->
<script type="text/javascript">/*<![CDATA[*/Cufon.now();/*]]>*/</script>
<div id="cat-nav">
<ul id="nav2">
<?php wp_list_categories('title_li=&sort_column=menu_order&exclude=1,114,115');?>
</ul>
</div><!--cat-nav-->
</div><!--navigation-->
</div><!--header-->
<div id="wrap">
<?php
Forumticker();
| leeparsons/tpp | wp-content/themes/aparatus/header.php | PHP | gpl-2.0 | 7,679 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
/// <summary>
/// An AND gate class to store the correct image and
/// calculate the appropriate output
/// </summary>
public class AndGate : Gate
{
/// <summary>
/// Constructor
/// </summary>
public AndGate()
{
this.Input = new InputPoint[2];
this.Input[0] = new InputPoint(-45, -9, 10, this);
this.Input[1] = new InputPoint(-45, 8, 10, this);
this.Output = new OutputPoint(44, 0, 20, this);
this.Img[0] = CircuitSimLib.Properties.Resources.and;
}
/// <summary>
/// Calculates the output for an AND gate
/// </summary>
/// <returns>Returns a calculated int</returns>
public override bool CalculateOutput()
{
return Input[0].ConnectedElementsOutput() && Input[1].ConnectedElementsOutput();
}
}
| Dominykasrr/Logic-Circuit-Sim | Circuit Simulator/CircuitSimLib/GeneratedCode/AndGate.cs | C# | gpl-2.0 | 944 |
<?php
$social_channels = $view_data['settings']['right_tab']['social_channels'];
$bar_layout_design = $view_data['settings']['right_tab']['bar_layout_design'];
$call_to_action = $view_data['settings']['right_tab']['call_to_action'];
$visibility_settings = $view_data['settings']['right_tab']['visibility_settings'];
$channels = array(
'Facebook'=>'Facebook',
'Twitter'=>'Twitter',
'Google'=>'Google',
'Linkedin'=>'Linkedin',
'Pinterest'=>'Pinterest',
'Digg'=>'Digg',
'Myspace'=>'Myspace',
'Stumbleupon'=>'Stumbleupon',
'Bebo'=>'Bebo',
'Blogger'=>'Blogger',
'Delicious'=>'Delicious',
'Xing'=>'Xing',
'Tumblr'=>'Tumblr',
'Technorati'=>'Technorati',
'Reddit'=>'Reddit',
'Netlog'=>'Netlog',
'Identi'=>'Identi',
'Friendfeed'=>'Friendfeed',
'Evernote'=>'Evernote',
'Diigo'=>'Diigo',
'VK'=>'VK',
'Email'=>'Email',
);
?>
<div id="right_tab_social_channels" class="modal widget-settings" tabindex="-1" role="dialog" aria-labelledby="registerShareLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3><?php echo $social_channels['settings_category']; ?></h3>
</div>
<div class="modal-body">
<div class="drag-links row">
<div class="col-md-5">
<h5>Active channels</h5>
<form class="form-horizontal" id="social-channels-right_tab" novalidate="novalidate" title="<?php echo $social_channels['settings_category']; ?>">
<ul id="socialsuse" class="connected list" style="margin:0;">
<?php
$socials = explode(',', $social_channels['socials']);
foreach($socials as $social){
echo '<li class="'.$social.'"><div class="share-icns"></div><span>'.$social.'</span><input type="hidden" id="socials" name="options[socials][]" value="'.$social.'" /></li>';
unset($channels["{$social}"]);
}
?>
</ul>
<div class="form-group" id="socials_target-group" style="margin-top: 20px;">
<h5>Open channel sharing in</h5>
<select class="selectpicker form-control" name="options[socials_target]" id="socials_target" data-style="btn-default">
<option value="window" <?php echo($social_channels['socials_target'] == 'window')? 'selected': ''; ?>>New window</option>
<option value="tab" <?php echo($social_channels['socials_target'] == 'tab')? 'selected': ''; ?>>New tab</option>
</select>
</div>
</form>
</div>
<div class="col-md-1">
<div class="between-connected">Drag to activate <span class="appz-point-left"></span></div>
</div>
<div class="col-md-5">
<h5>Inactive channels</h5>
<ul class="connected list no2" style="margin:0;">
<?php
foreach($channels as $channel){
echo '<li class="'.$channel.'"><div class="share-icns"></div><span>'.$channel.'</span><input type="hidden" id="socials" name="options[socials][]" value="'.$channel.'" /></li>';
}
?>
</ul>
</div>
</div>
<div style="clear:both;"></div>
</div>
<div class="modal-footer">
<button class="btn btn-icon btn-default circle_remove" data-dismiss="modal" aria-hidden="true"><i class="appz-close-3"></i> Close</button>
<button type="submit" class="btn btn-icon btn-primary circle_ok save-widget-settings" settings="#social-channels-right_tab" layout="right_tab" data-loading-text="loading..."><i class="appz-checkmark-circle-2"></i> Save</button>
</div>
</div>
</div>
</div><!--/Social Channels Settings-->
<div id="right_tab_bar_layout_design" class="modal widget-settings" tabindex="-1" role="dialog" aria-labelledby="registerShareLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3><?php echo $bar_layout_design['settings_category']; ?></h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="bar-layout-right_tab" novalidate="novalidate" title="<?php echo $bar_layout_design['settings_category']; ?>">
<div class="row">
<div class="col-md-6">
<div class="form-group" id="bgcolor-group">
<h5>Background color</h5>
<div class="input-group">
<input type="text" id="bgcolor-right_tab" name="options[bgcolor]" value="<?php echo $bar_layout_design['bgcolor']; ?>" class="form-control"/>
<span class="input-group-btn">
<button href="javascript:void(0)" class="btn undo-color" target="#bgcolor-right_tab" original="<?php echo $bar_layout_design['bgcolor']; ?>"><i class="appz-undo"></i> Undo</button>
</span>
</div>
<br/><br/>
<div class="palette" target="#bgcolor-right_tab"></div>
</div>
<div class="form-group span11" id="icons-group">
<h5>Icons style</h5>
<select style="width: 100%;" id="icons" name="options[icons]" class="select-icons" layout="right_tab">
<option value="white" <?php echo($bar_layout_design['icons'] == 'white')? 'selected': ''; ?>>White</option>
<option value="black" <?php echo($bar_layout_design['icons'] == 'black')? 'selected': ''; ?>>Black</option>
<option value="icons" <?php echo($bar_layout_design['icons'] == 'icons')? 'selected': ''; ?>>Shiny</option>
<option value="variety" <?php echo($bar_layout_design['icons'] == 'variety')? 'selected': ''; ?>>Variety</option>
<option value="satin" <?php echo($bar_layout_design['icons'] == 'satin')? 'selected': ''; ?>>Satin</option>
<option value="shiny2" <?php echo($bar_layout_design['icons'] == 'shiny2')? 'selected': ''; ?>>Shiny 2</option>
<option value="elegant" <?php echo($bar_layout_design['icons'] == 'elegant')? 'selected': ''; ?>>Elegant</option>
<option value="metro" <?php echo($bar_layout_design['icons'] == 'metro')? 'selected': ''; ?>>Metro</option>
<option value="milky" <?php echo($bar_layout_design['icons'] == 'milky')? 'selected': ''; ?>>Milky</option>
<option value="bald" <?php echo($bar_layout_design['icons'] == 'bald')? 'selected': ''; ?>>Bald</option>
<option value="round" <?php echo($bar_layout_design['icons'] == 'round')? 'selected': ''; ?>>Round</option>
</select>
</div>
<div class="form-group" id="toolstyle-group">
<h5>Tooltip style</h5>
<select class="selectpicker form-control" name="options[toolstyle]" id="toolstyle" data-style="btn-default">
<option value="darkminimal" <?php echo($bar_layout_design['toolstyle'] == 'darkminimal')? 'selected': ''; ?>>Dark minimal</option>
<option value="lightminimal" <?php echo($bar_layout_design['toolstyle'] == 'lightminimal')? 'selected': ''; ?>>Light minimal</option>
<option value="darkgray" <?php echo($bar_layout_design['toolstyle'] == 'darkgray')? 'selected': ''; ?>>Dark gray</option>
</select>
</div>
</div><!--/span6-->
<div class="col-md-6">
<div class="form-group" id="textcolor-group">
<h5>Text color</h5>
<div class="input-group">
<input type="text" id="textcolor-right_tab" name="options[textcolor]" value="<?php echo $bar_layout_design['textcolor']; ?>" class="form-control"/>
<span class="input-group-btn">
<button href="javascript:void(0)" class="btn undo-color" target="#textcolor-right_tab" original="<?php echo $bar_layout_design['textcolor']; ?>"><i class="appz-undo"></i> Undo</button>
</span>
</div>
<br/><br/>
<div class="palette" target="#textcolor-right_tab"></div>
</div>
<div class="form-group" id="position-group">
<h5>Bar position</h5>
<select class="selectpicker form-control" name="options[position]" id="position" data-style="btn-default">
<option value="center" <?php echo($bar_layout_design['position'] == 'center')? 'selected': ''; ?>>Center</option>
<option value="top" <?php echo($bar_layout_design['position'] == 'top')? 'selected': ''; ?>>Top</option>
<option value="bottom" <?php echo($bar_layout_design['position'] == 'bottom')? 'selected': ''; ?>>Bottom</option>
</select>
</div>
</div><!--/span6-->
</div><!--/row-->
</form>
</div>
<div class="modal-footer">
<button class="btn btn-icon btn-default circle_remove" data-dismiss="modal" aria-hidden="true"><i class="appz-close-3"></i> Close</button>
<button type="submit" class="btn btn-icon btn-primary circle_ok save-widget-settings" settings="#bar-layout-right_tab" layout="right_tab" data-loading-text="loading..."><i class="appz-checkmark-circle-2"></i> Save</button>
</div>
</div>
</div>
</div><!--/Bar layout design Settings-->
<div id="right_tab_visibility_settings" class="modal widget-settings" tabindex="-1" role="dialog" aria-labelledby="registerShareLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3><?php echo $visibility_settings['settings_category']; ?></h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="visibility-settings-right_tab" novalidate="novalidate" title="Visibility settings">
<?php if( $view_data['site_list'] != NULL ): ?>
<div class="row">
<div class="col-md-12">
<div class="form-group span11" id="exclude_blogs-group">
<h5>WPMU - Hide widget on specific blogs</h5>
<select name="options[exclude_blogs][]" id="exclude_blogs" multiple ui_select style="width: 100%;" data-placeholder="Click to select blogs">
<?php
foreach ( $view_data['site_list'] as $bid ) {
$current_blog_details = get_blog_details( array( 'blog_id' => $bid->blog_id ) );
$option = '<option value="' . $bid->blog_id . '" '.((in_array($bid->blog_id, explode(',', $visibility_settings['exclude_blogs'])))? 'selected' : '').'>';
$option .= $current_blog_details->blogname;
$option .= '</option>';
echo $option;
}
?>
</select>
</div>
</div>
</div>
<?php endif; ?>
<div class="row">
<div class="col-md-6">
<div class="form-group span11" id="exclude_pages-group">
<h5>Hide widget on specific pages</h5>
<select name="options[exclude_pages][]" id="exclude_pages" multiple ui_select style="width: 100%;" <?php echo(($view_data['site_list'] != NULL)? 'disabled' : 'data-placeholder="Click to select pages"'); ?>>
<?php
if($view_data['site_list'] == NULL) {
$pages = get_pages();
foreach ( $pages as $page ) {
$option = '<option value="' . $page->ID . '" '.((in_array($page->ID, explode(',', $visibility_settings['exclude_pages'])))? 'selected' : '').'>';
$option .= $page->post_title;
$option .= '</option>';
echo $option;
}
}
else {
echo '<option selected="selected">Temporary disabled for WPMU</option>';
}
?>
</select>
</div>
<div class="form-group span11" id="on_home-group">
<h5>Show widget on Home page</h5>
<div class="toggle-button" data-toggleButton-style-enabled="info">
<input data-toggle="value" target_id="on_home-right_tab" target_name="options[on_home]" type="checkbox" value="1" <?php echo($visibility_settings['on_home'] == 0)? '': 'checked="checked"'; ?>/>
</div>
</div>
<div class="form-group span11" id="on_posts-group">
<h5>Show widget on posts</h5>
<div class="toggle-button" data-toggleButton-style-enabled="info">
<input data-toggle="value" target_id="on_posts-right_tab" target_name="options[on_posts]" type="checkbox" value="1" <?php echo($visibility_settings['on_posts'] == 0)? '': 'checked="checked"'; ?>/>
</div>
</div>
</div><!--/span6-->
<div class="col-md-6">
<div class="form-group span11" id="exclude_pages-group">
<h5>Hide widget on specific posts</h5>
<select name="options[exclude_posts][]" id="exclude_posts" multiple ui_select style="width: 100%;" <?php echo(($view_data['site_list'] != NULL)? 'disabled' : 'data-placeholder="Click to select posts"'); ?>>
<?php
if($view_data['site_list'] == NULL) {
$posts = get_posts();
foreach ( $posts as $post ) {
$option = '<option value="' . $post->ID . '" '.((in_array($post->ID, explode(',', $visibility_settings['exclude_posts'])))? 'selected' : '').'>';
$option .= $post->post_title;
$option .= '</option>';
echo $option;
}
}
else {
echo '<option selected="selected">Temporary disabled for WPMU</option>';
}
?>
</select>
</div>
<div class="form-group span11" id="on_pages-group">
<h5>Show widget on pages</h5>
<div class="toggle-button" data-toggleButton-style-enabled="info">
<input data-toggle="value" target_id="on_pages-bottom_tab" target_name="options[on_pages]" type="checkbox" value="1" <?php echo($visibility_settings['on_pages'] == 0)? '': 'checked="checked"'; ?>/>
</div>
</div>
<div class="form-group span11" id="on_custom-group">
<h5>Show widget on custom post types</h5>
<select name="options[on_custom][]" id="on_custom" multiple ui_select style="width: 100%;" <?php echo(($view_data['site_list'] != NULL)? 'disabled' : 'data-placeholder="Click to select post types"'); ?>>
<?php
if($view_data['site_list'] == NULL) {
$args=array(
'public' => true,
'_builtin' => false
);
$post_types=get_post_types($args,'names');
foreach ( $post_types as $post_type ) {
$option = '<option value="' . $post_type . '" '.((in_array($post_type, explode(',', $visibility_settings['on_custom'])))? 'selected' : '').'>';
$option .= $post_type;
$option .= '</option>';
echo $option;
}
}
else {
echo '<option selected="selected">Temporary disabled for WPMU</option>';
}
?>
</select>
</div>
</div><!--/span6-->
</div><!--/row-->
</form>
</div>
<div class="modal-footer">
<button class="btn btn-icon btn-default circle_remove" data-dismiss="modal" aria-hidden="true"><i class="appz-close-3"></i> Close</button>
<button type="submit" class="btn btn-icon btn-primary circle_ok save-widget-settings" settings="#visibility-settings-right_tab" layout="right_tab" data-loading-text="loading..."><i class="appz-checkmark-circle-2"></i> Save</button>
</div>
</div>
</div>
</div><!--/Visibility Settings-->
<!---Preview Widget--->
<div id="preview_right_tab" class="modal widget-preview-modal" tabindex="-1" role="dialog" wp_address="<?php echo get_site_url(); ?>/?cunjo=right_tab" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Preview</h3>
</div>
<div class="modal-body">
Preview here
</div>
<div class="modal-footer">
<button class="btn btn-icon btn-default circle_remove" data-dismiss="modal" aria-hidden="true"><i class="appz-close-3"></i> Close</button>
</div>
</div>
</div>
</div><!--/Preview Widget-->
<?php //echo '<pre>'.print_r($view_data, true).'</pre>'; ?> | suneeshps/wordpress | wp-content/plugins/share-social/views/tab_modals/right_tab_modals.php | PHP | gpl-2.0 | 21,979 |
import os
from collections import OrderedDict
from .sqldatabase import SqlDatabase
from .retrieve_core_info import retrieveCoreInfo
# Root class that all SQL table updaters derive from
class SqlTableUpdater():
def __init__(self, tableName, tableColumns=[], coreInfo={}):
self.tableName = tableName
self.columnsDict = OrderedDict(tableColumns)
self.dbFile = os.path.join(os.getcwd().replace("python", "metadata"), "libretro.sqlite")
self.dbFileExists = os.path.isfile(self.dbFile)
self.coreInfo = coreInfo
# self.filterUnusedCores()
def updateTable(self):
pass
def updateColumns(self, database, additionalStatement: str = ""):
if not self.dbFileExists:
database.createTable(self.tableName, self.columnsDict, additionalStatement)
else:
try:
database.deleteTable(self.tableName)
except:
database.createTable(self.tableName, self.columnsDict, additionalStatement)
def __del__(self):
print("Updated " + self.tableName + " table.")
def libretroSystemList(self):
systems = []
for k, v in self.coreInfo['cores'].items():
if "categories" not in v or v["categories"] != "Emulator":
continue
if "database" in v:
name = v["database"].split("|")
for n in name:
systems.append(n)
# Split console and manufacturer names
# Not really necessary for Libretro identifiers
#tup = n.split(" - ")
#
## "MAME"
#if len(tup) == 1:
# systems.append(tup[0])
#
## Nearly every one
#elif len(tup) == 2:
# systems.append(tup[1])
#
## Sega - Master System - Mark III
## Sega - Mega Drive - Genesis
#elif len(tup) == 3:
# systems.append(tup[1])
# There are some cores that do not have "database" defined
elif "systemname" in v:
systems.append(v["systemname"])
systems = list(set(systems))
systems.sort()
return systems
# This map defines all Libretro-based systems that Phoenix supports. If it isn't in here, it isn't supported by Phoenix!
# TODO: Place this information into an entirely separate database
# WARNING: Do NOT change Phoenix UUIDs (1st column), even if there are spelling mistakes. Change friendlyName if you really need to.
phoenixSystemDatabase = {
# friendlyName: North American console name without manufacturer
# shortName: Abbreviation (typically 3 letters)
# enabled: True iff a core is available, Phoenix can run it, and the game scanner can find it (extensions set)
# Everything else
"Arcade": {"enabled": False, "defaultCore": "mame_libretro", "friendlyName": "", "shortName": "", "manufacturer": "(Various)" },
# Conspicuously missing from No-Intro
"Amstrad - CPC": {"enabled": False, "defaultCore": "cap32_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Amstrad" },
"Atari - 2600": {"enabled": True, "defaultCore": "stella_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Capcom - CP System I": {"enabled": False, "defaultCore": "fb_alpha_cps1_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Capcom" },
"Capcom - CP System II": {"enabled": False, "defaultCore": "fb_alpha_cps2_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Capcom" },
"Capcom - CP System III": {"enabled": False, "defaultCore": "fbalpha2012_cps3_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Capcom" },
"Capcom - CPS Changer": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Capcom" },
"CHIP-8": {"enabled": False, "defaultCore": "emux_chip8_libretro", "friendlyName": "", "shortName": "", "manufacturer": "(Various)" },
"DOS": {"enabled": False, "defaultCore": "dosbox_libretro", "friendlyName": "", "shortName": "", "manufacturer": "(Various)" },
"Mattel - Intellivision": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Mattel" },
"Nintendo - Game & Watch": {"enabled": False, "defaultCore": "gw_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Sinclair - ZX81": {"enabled": False, "defaultCore": "81_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sinclair" },
"SNK - Neo Geo": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "SNK" },
# No-Intro, both official and non-official (ROM-based games)
"Atari - 5200": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Atari - 7800": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Atari - Jaguar": {"enabled": True, "defaultCore": "virtualjaguar_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Atari - Lynx": {"enabled": True, "defaultCore": "mednafen_lynx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Atari - ST": {"enabled": True, "defaultCore": "hatari_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Atari" },
"Bandai - WonderSwan Color": {"enabled": True, "defaultCore": "mednafen_wswan_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Bandai" },
"Bandai - WonderSwan": {"enabled": True, "defaultCore": "mednafen_wswan_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Bandai" },
"Casio - Loopy": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Casio" },
"Casio - PV-1000": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Casio" },
"Coleco - ColecoVision": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Coleco" },
#"Commodore - 64 (PP)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
#"Commodore - 64 (Tapes)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - 64": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - Amiga": {"enabled": True, "defaultCore": "puae_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - Plus-4": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - VIC-20": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Emerson - Arcadia 2001": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Emerson" },
"Entex - Adventure Vision": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Entex" },
"Epoch - Super Cassette Vision": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Epoch" },
"Fairchild - Channel F": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Fairchild" },
"Funtech - Super Acan": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Funtech" },
"GamePark - GP32": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "GamePark" },
"GCE - Vectrex": {"enabled": True, "defaultCore": "vecx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "GCE" },
"Hartung - Game Master": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Hartung" },
"LeapFrog - Leapster Learning Game System": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "LeapFrog" },
"Magnavox - Odyssey2": {"enabled": False, "defaultCore": "o2em_libretro", "friendlyName": u"Odyssey²", "shortName": "", "manufacturer": "Magnavox" },
"Microsoft - MSX 2": {"enabled": False, "defaultCore": "bluemsx_libretro", "friendlyName": "MSX2", "shortName": "", "manufacturer": "Microsoft" },
"Microsoft - MSX": {"enabled": False, "defaultCore": "bluemsx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
#"Microsoft - XBOX 360 (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
#"Microsoft - XBOX 360 (Games on Demand)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
#"Microsoft - XBOX 360 (Title Updates)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
"NEC - PC Engine - TurboGrafx 16": {"enabled": True, "defaultCore": "mednafen_pce_fast_libretro", "friendlyName": "TurboGrafx 16", "shortName": "", "manufacturer": "NEC" },
"NEC - Super Grafx": {"enabled": True, "defaultCore": "mednafen_supergrafx_libretro", "friendlyName": "SuperGrafx", "shortName": "", "manufacturer": "NEC" },
#"Nintendo - Famicom Disk System": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Game Boy Advance (e-Cards)": {"enabled": True, "defaultCore": "vbam_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Game Boy Advance": {"enabled": True, "defaultCore": "vbam_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Game Boy Color": {"enabled": True, "defaultCore": "gambatte_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Game Boy": {"enabled": True, "defaultCore": "gambatte_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
#"Nintendo - New Nintendo 3DS (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - New Nintendo 3DS": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
#"Nintendo - Nintendo 3DS (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Nintendo 3DS": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Nintendo 64": {"enabled": True, "defaultCore": "mupen64plus_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
#"Nintendo - Nintendo DS (Download Play) (BETA)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Nintendo DS": {"enabled": True, "defaultCore": "desmume_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
#"Nintendo - Nintendo DSi (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Nintendo DSi": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Nintendo Entertainment System": {"enabled": True, "defaultCore": "fceumm_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
#"Nintendo - Nintendo Wii (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Pokemon Mini": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Satellaview": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Sufami Turbo": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Super Nintendo Entertainment System": {"enabled": True, "defaultCore": "bsnes_mercury_balanced_libretro", "friendlyName": "Super Nintendo", "shortName": "", "manufacturer": "Nintendo" },
"Nintendo - Virtual Boy": {"enabled": True, "defaultCore": "mednafen_vb_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Nokia - N-Gage": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nokia" },
"Philips - Videopac+": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Philips" },
"RCA - Studio II": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "RCA" },
"Sega - 32X": {"enabled": True, "defaultCore": "picodrive_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Game Gear": {"enabled": True, "defaultCore": "genesis_plus_gx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Master System - Mark III": {"enabled": False, "defaultCore": "emux_sms_libretro", "friendlyName": "Master System", "shortName": "", "manufacturer": "Sega" },
"Sega - Mega Drive - Genesis": {"enabled": True, "defaultCore": "genesis_plus_gx_libretro", "friendlyName": "Genesis", "shortName": "", "manufacturer": "Sega" },
"Sega - PICO": {"enabled": True, "defaultCore": "picodrive_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - SG-1000": {"enabled": True, "defaultCore": "genesis_plus_gx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sinclair - ZX Spectrum +3": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sinclair" },
"SNK - Neo Geo Pocket Color": {"enabled": True, "defaultCore": "mednafen_ngp_libretro", "friendlyName": "", "shortName": "", "manufacturer": "SNK" },
"SNK - Neo Geo Pocket": {"enabled": True, "defaultCore": "mednafen_ngp_libretro", "friendlyName": "", "shortName": "", "manufacturer": "SNK" },
#"Sony - PlayStation 3 (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation 3 (Downloadable)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation 3 (PSN)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation Portable (DLC)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation Portable (PSN)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation Portable (PSX2PSP)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation Portable (UMD Music)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
#"Sony - PlayStation Portable (UMD Video)": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
"Sony - PlayStation Portable": {"enabled": True, "defaultCore": "ppsspp_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
"Tiger - Game.com": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Tiger" },
"Tiger - Gizmondo": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Tiger" },
"VTech - CreatiVision": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "VTech" },
"VTech - V.Smile": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "VTech" },
"Watara - Supervision": {"enabled": True, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Watara" },
# Redump.org (disc-based games)
"Apple - Macintosh": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Apple" },
"Bandai - Playdia": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Bandai" },
"Bandai / Apple - Pippin": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Bandai / Apple" },
"Commodore - Amiga CD": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - Amiga CD32": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Commodore - Amiga CDTV": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Commodore" },
"Fujitsu - FM Towns series": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Fujitsu" },
"IBM PC compatible": {"enabled": False, "defaultCore": "", "friendlyName": "PC", "shortName": "", "manufacturer": "(Various)" },
"Mattel - HyperScan": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Mattel" },
"Microsoft - Xbox": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
"Namco / Sega / Nintendo - Triforce": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"NEC - PC Engine CD - TurboGrafx-CD": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "TurboGrafx-CD", "shortName": "", "manufacturer": "NEC" },
"NEC - PC-88 series": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "NEC" },
"NEC - PC-98 series": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "NEC" },
"NEC - PC-FX - PC-FXGA": {"enabled": False, "defaultCore": "mednafen_pcfx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "NEC" },
"Nintendo - GameCube": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Palm OS": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Palm" },
"Panasonic - 3DO Interactive Multiplayer": {"enabled": False, "defaultCore": "4do_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Panasonic" },
"Philips - CD-i": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Philips" },
"Photo - CD": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "(Various)" },
"Sega - Chihiro": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Dreamcast": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Lindbergh": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Mega-CD": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Naomi": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"Sega - Saturn": {"enabled": True, "defaultCore": "yabause_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sega" },
"SNK - Neo Geo CD": {"enabled": False, "defaultCore": "mess2014_libretro", "friendlyName": "", "shortName": "", "manufacturer": "SNK" },
"Sony - PlayStation 2": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
"Sony - PlayStation": {"enabled": True, "defaultCore": "mednafen_psx_libretro", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
"VTech - V.Flash": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "VTech" },
# Seventh-generation consoles (circa 2005)
"Microsoft - Xbox 360": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
"Nintendo - Wii": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Sony - PlayStation 3": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
# Eighth-generation consoles (circa 2012)
"Microsoft - Xbox One": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
"Nintendo - Wii U": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
"Sony - PlayStation 4": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Sony" },
# Ninth-generation consoles (circa 2017)
"Microsoft - Xbox One X": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Microsoft" },
"Nintendo - Switch": {"enabled": False, "defaultCore": "", "friendlyName": "", "shortName": "", "manufacturer": "Nintendo" },
}
def phoenixSystems(self):
return OrderedDict(sorted(self.phoenixSystemDatabase.items(), key=lambda t: t[0]))
def libretroToPhoenix(self, libretroSystem):
return self.libretroToPhoenixMap[libretroSystem]
# This map essentially says "Register this Libretro core for this (these) Phoenix system(s)" when a .info file claims support for that system
# If a core claims support for some Libretro ID, register that core for each Phoenix ID
libretroToPhoenixMap = {
"3DO": {"Panasonic - 3DO Interactive Multiplayer"},
"Arcade (various)": {"Arcade"},
"Atari - 2600": {"Atari - 2600"},
"Atari - 5200": {"Atari - 5200"},
"Atari - 7800": {"Atari - 7800"},
"Atari - Jaguar": {"Atari - Jaguar"},
"Atari - Lynx": {"Atari - Lynx"},
"Atari ST/STE/TT/Falcon": {"Atari - ST"},
"Bandai - WonderSwan Color": {"Bandai - WonderSwan Color"},
"Bandai - WonderSwan": {"Bandai - WonderSwan"},
"CHIP-8": {"CHIP-8"},
"Commodore Amiga": {"Commodore - Amiga"},
"Commodore - C128": {"Arcade"},
"Commodore - 64": {"Commodore - 64"},
"CP System I": {"Capcom - CP System I"},
"CP System II": {"Capcom - CP System II"},
"CP System III": {"Capcom - CP System III"},
"CPC": {"Amstrad - CPC"},
"DOS": {"DOS"},
"FB Alpha - Arcade Games": {"Arcade"},
"GCE - Vectrex": {"GCE - Vectrex"},
"Handheld Electronic Game": {"Nintendo - Game & Watch"},
"IBM PC compatible": {"IBM PC compatible"},
"Magnavox - Odyssey2": {"Magnavox - Odyssey2"},
"MAME": {"Arcade"},
"MAME2003": {"Arcade"},
"Microsoft - MSX 2": {"Microsoft - MSX 2"},
"Microsoft - MSX2": {"Microsoft - MSX 2"},
"Microsoft - MSX": {"Microsoft - MSX"},
# MESS and UME
# http://nonmame.retrogames.com/
"MULTI (various)": {
"Atari - 2600",
"Atari - 5200",
"Atari - 7800",
"Atari - Lynx",
"Bandai - WonderSwan Color"
"Bandai - WonderSwan",
"Capcom - CPS Changer",
"Coleco - ColecoVision",
"Fujitsu - FM Towns series",
"Magnavox - Odyssey2",
"Mattel - Intellivision",
"NEC - PC Engine - TurboGrafx 16",
"NEC - PC Engine CD - TurboGrafx-CD",
"NEC - Super Grafx",
"Nintendo - Game Boy Advance",
"Nintendo - Game Boy",
"Philips - Videopac+",
"RCA - Studio II",
"Sega - Game Gear",
"Sega - Master System - Mark III",
"Sega - Mega Drive - Genesis",
"Sega - PICO",
"Sega - SG-1000",
"SNK - Neo Geo CD",
"SNK - Neo Geo",
"Watara - Supervision",
},
"NEC - PC Engine - TurboGrafx 16": {"NEC - PC Engine - TurboGrafx 16"},
"NEC - PC Engine SuperGrafx": {"NEC - Super Grafx"},
"NEC - PC Engine CD - TurboGrafx-CD": {"NEC - Super Grafx"},
"NEC - PC-FX": {"NEC - PC-FX - PC-FXGA"},
"NEC - Super Grafx": {"NEC - Super Grafx"},
"Neo Geo": {"SNK - Neo Geo"},
"Nintendo - 3DS": {"Nintendo - Nintendo 3DS"},
"Nintendo - Family Computer Disk System": {"Nintendo - Nintendo Entertainment System"},
"Nintendo - Famicom Disk System": {"Nintendo - Nintendo Entertainment System"},
"Nintendo - Game & Watch": {"Nintendo - Game & Watch"},
"Nintendo - Game Boy Advance (e-Cards)": {"Nintendo - Game Boy Advance (e-Cards)"},
"Nintendo - Game Boy Advance": {"Nintendo - Game Boy Advance"},
"Nintendo - Game Boy Color": {"Nintendo - Game Boy Color"},
"Nintendo - Game Boy": {"Nintendo - Game Boy"},
"Nintendo - GameCube": {"Nintendo - GameCube"},
"Nintendo - Nintendo 64": {"Nintendo - Nintendo 64"},
"Nintendo - Nintendo 64DD": {"Nintendo - Nintendo 64"},
"Nintendo - Nintendo DS": {"Nintendo - Nintendo DS"},
"Nintendo - Nintendo DS (Download Play)": {"Nintendo - Nintendo DS"},
"Nintendo - Nintendo DS (Download Play) (BETA)": {"Nintendo - Nintendo DS"},
"Nintendo - Nintendo DS Decrypted": {"Nintendo - Nintendo DS"},
"Nintendo - Nintendo Entertainment System": {"Nintendo - Nintendo Entertainment System"},
"Nintendo - Pokemon Mini": {"Nintendo - Pokemon Mini"},
"Nintendo - Sufami Turbo": {"Nintendo - Sufami Turbo"},
"Nintendo - Super Nintendo Entertainment System": {"Nintendo - Super Nintendo Entertainment System"},
"Nintendo - Virtual Boy": {"Nintendo - Virtual Boy"},
"Nintendo - Wii": {"Nintendo - Wii"},
"PC": {"IBM PC compatible"},
"PC-FX": {"NEC - PC-FX - PC-FXGA"},
"PC-98": {"NEC - PC-98 series"},
"Phillips - Videopac+": {"Philips - Videopac+"},
"Sega - 32X": {"Sega - 32X"},
"Sega - Dreamcast": {"Sega - Dreamcast"},
"Sega - Game Gear": {"Sega - Game Gear"},
"Sega - Master System - Mark III": {"Sega - Master System - Mark III"},
"Sega - Mega Drive - Genesis": {"Sega - Mega Drive - Genesis"},
"Sega - Mega-CD - Sega CD": {"Sega - Mega-CD"},
"Sega - NAOMI": {"Sega - Naomi"},
"Sega - PICO": {"Sega - PICO"},
"Sega - Saturn": {"Sega - Saturn"},
"Sega - SG-1000": {"Sega - SG-1000"},
"Sharp - X68000": {"Arcade"},
"Sinclair - ZX 81": {"Sinclair - ZX81"},
"Sinclair - ZX Spectrum": {"Sinclair - ZX Spectrum +3"},
"Sinclair - ZX Spectrum +3": {"Sinclair - ZX Spectrum +3"},
"SNK - Neo Geo Pocket Color": {"SNK - Neo Geo Pocket Color"},
"SNK - Neo Geo Pocket": {"SNK - Neo Geo Pocket"},
"Sony - PlayStation Portable": {"Sony - PlayStation Portable"},
"Sony - PlayStation": {"Sony - PlayStation"},
"The 3DO Company - 3DO": {"Panasonic - 3DO Interactive Multiplayer"},
"Uzebox": {"Arcade"},
"ZX Spectrum (various)": {"Sinclair - ZX Spectrum +3"},
}
# Not all Phoenix IDs are availble in OpenVGDB, fail silently and gracefully if a match isn't found
def phoenixToOpenVGDB(self, phoenixID):
ret = ""
try:
ret = self.phoenixToOpenVGDBMap[phoenixID]
except KeyError:
ret = ""
return ret
phoenixToOpenVGDBMap = {
"Panasonic - 3DO Interactive Multiplayer": "3DO Interactive Multiplayer",
"Arcade": "Arcade",
"Atari - 2600": "Atari 2600",
"Atari - 5200": "Atari 5200",
"Atari - 7800": "Atari 7800",
"Atari - Jaguar": "Atari Jaguar CD",
"Atari - Jaguar": "Atari Jaguar",
"Atari - Lynx": "Atari Lynx",
"Bandai - WonderSwan Color": "Bandai WonderSwan Color",
"Bandai - WonderSwan": "Bandai WonderSwan",
"Coleco - ColecoVision": "Coleco ColecoVision",
"GCE - Vectrex": "GCE Vectrex",
"Mattel - Intellivision": "Intellivision",
"Magnavox - Odyssey2": "Magnavox Odyssey2",
"NEC - PC Engine CD - TurboGrafx-CD": "NEC PC Engine CD/TurboGrafx-CD",
"NEC - PC Engine - TurboGrafx 16": "NEC PC Engine/TurboGrafx-16",
"NEC - PC-FX - PC-FXGA": "NEC PC-FX",
"NEC - Super Grafx": "NEC SuperGrafx",
"Nintendo - Nintendo 64": "Nintendo 64",
"Nintendo - Nintendo DS": "Nintendo DS",
"Nintendo - Nintendo Entertainment System": "Nintendo Entertainment System",
"Nintendo - Nintendo Entertainment System": "Nintendo Famicom Disk System",
"Nintendo - Game Boy Advance": "Nintendo Game Boy Advance",
"Nintendo - Game Boy Color": "Nintendo Game Boy Color",
"Nintendo - Game Boy": "Nintendo Game Boy",
"Nintendo - GameCube": "Nintendo GameCube",
"Nintendo - Super Nintendo Entertainment System": "Nintendo Super Nintendo Entertainment System",
"Nintendo - Virtual Boy": "Nintendo Virtual Boy",
"Nintendo - Wii": "Nintendo Wii",
"Sega - 32X": "Sega 32X",
"Sega - Mega-CD": "Sega CD/Mega-CD",
"Sega - Game Gear": "Sega Game Gear",
"Sega - Mega Drive - Genesis": "Sega Genesis/Mega Drive",
"Sega - Master System - Mark III": "Sega Master System",
"Sega - Saturn": "Sega Saturn",
"Sega - SG-1000": "Sega SG-1000",
"SNK - Neo Geo Pocket Color": "SNK Neo Geo Pocket Color",
"SNK - Neo Geo Pocket": "SNK Neo Geo Pocket",
"Sony - PlayStation Portable": "Sony PlayStation Portable",
"Sony - PlayStation": "Sony PlayStation",
}
def getOpenVGDBToPhoenixMap(self):
return OrderedDict(sorted(self.openVGDBToPhoenixMap.items(), key=lambda t: t[0]))
openVGDBToPhoenixMap = {
"3DO Interactive Multiplayer": "Panasonic - 3DO Interactive Multiplayer",
"Arcade": "Arcade",
"Atari 2600": "Atari - 2600",
"Atari 5200": "Atari - 5200",
"Atari 7800": "Atari - 7800",
"Atari Jaguar CD": "Atari - Jaguar",
"Atari Jaguar": "Atari - Jaguar",
"Atari Lynx": "Atari - Lynx",
"Bandai WonderSwan Color": "Bandai - WonderSwan Color",
"Bandai WonderSwan": "Bandai - WonderSwan",
"Coleco ColecoVision": "Coleco - ColecoVision",
"GCE Vectrex": "GCE - Vectrex",
"Intellivision": "Mattel - Intellivision",
"Magnavox Odyssey2": "Magnavox - Odyssey2",
"NEC PC Engine CD/TurboGrafx-CD": "NEC - PC Engine CD - TurboGrafx-CD",
"NEC PC Engine/TurboGrafx-16": "NEC - PC Engine - TurboGrafx 16",
"NEC PC-FX": "NEC - PC-FX - PC-FXGA",
"NEC SuperGrafx": "NEC - Super Grafx",
"Nintendo 64": "Nintendo - Nintendo 64",
"Nintendo DS": "Nintendo - Nintendo DS",
"Nintendo Entertainment System": "Nintendo - Nintendo Entertainment System",
"Nintendo Famicom Disk System": "Nintendo - Nintendo Entertainment System",
"Nintendo Game Boy Advance": "Nintendo - Game Boy Advance",
"Nintendo Game Boy Color": "Nintendo - Game Boy Color",
"Nintendo Game Boy": "Nintendo - Game Boy",
"Nintendo GameCube": "Nintendo - GameCube",
"Nintendo Super Nintendo Entertainment System": "Nintendo - Super Nintendo Entertainment System",
"Nintendo Virtual Boy": "Nintendo - Virtual Boy",
"Nintendo Wii": "Nintendo - Wii",
"Sega 32X": "Sega - 32X",
"Sega CD/Mega-CD": "Sega - Mega-CD",
"Sega Game Gear": "Sega - Game Gear",
"Sega Genesis/Mega Drive": "Sega - Mega Drive - Genesis",
"Sega Master System": "Sega - Master System - Mark III",
"Sega Saturn": "Sega - Saturn",
"Sega SG-1000": "Sega - SG-1000",
"SNK Neo Geo Pocket Color": "SNK - Neo Geo Pocket Color",
"SNK Neo Geo Pocket": "SNK - Neo Geo Pocket",
"Sony PlayStation Portable": "Sony - PlayStation Portable",
"Sony PlayStation": "Sony - PlayStation",
}
def filterUnusedCores(self):
for key in self.coreInfo["cores"].keys():
if (
# No reason specified
#"4do_libretro" == key
# or "81_libretro" == key
# or "bluemsx_libretro" == key
# or "bsnes_accuracy_libretro" == key
# or "bsnes_balanced_libretro" == key
# or "bsnes_performance_libretro" == key
# or "cap32_libretro" == key
# or "catsfc_libretro" == key
# or "dosbox_libretro" == key
# or "emux_chip8_libretro" == key
# or "fb_alpha_cps1_libretro" == key
# or "fb_alpha_cps2_libretro" == key
# or "fmsx_libretro" == key
# or "gpsp_libretro" == key
# or "gw_libretro" == key
# or "handy_libretro" == key
# or "hatari_libretro" == key
# or "imame4all_libretro" == key
# or "mame078_libretro" == key
# or "mame2010_libretro" == key
# or "mame2014_libretro" == key
# or "meteor_libretro" == key
# or "o2em_libretro" == key
# or "prosystem_libretro" == key
# or "puae_libretro" == key
# or "ume2014_libretro" == key
# or "vecx_libretro" == key
# or "virtualjaguar_libretro" == key
# ARM cores
"pcsx" in key
or "pocketsnes_libretro" == key
):
del self.coreInfo["cores"][key]
| team-phoenix/Phoenix | frontend/python/updaters/sqlTableUpdater.py | Python | gpl-2.0 | 50,004 |
/* sd2iec - SD/MMC to Commodore serial bus interface/controller
Copyright (C) 2007-2015 Ingo Korb <[email protected]>
Inspired by MMC2IEC by Lars Pontoppidan et al.
FAT filesystem access based on code from ChaN and Jim Brain, see ff.c|h.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License only.
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
bus.h: Common IEC/IEEE bus definitions
*/
#ifndef BUS_H
#define BUS_H
extern uint8_t device_address;
void bus_interface_init(void);
void bus_init(void);
void __attribute__((noreturn)) bus_mainloop(void);
#endif
| ivanovp/sd2iec | src/bus.h | C | gpl-2.0 | 1,133 |
// -*-C++ -*-
/** \file
********************************************************************
* Device shape base class for route window.
*
* \author Rüdiger Krauße,
* Tobias Schlemmer <[email protected]>
* \license GPL
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
********************************************************************
*\addtogroup GUIroute
*\{
********************************************************************/
#include "src/kernel/Defs.h"
#include "src/kernel/error.h"
#include "src/wxGUI/MutFrame.h"
#include "src/wxGUI/Routing/GUIRoute.h"
#include "src/wxGUI/Routing/DeviceShape.h"
#include "src/wxGUI/Routing/RouteIcons.h"
#include "src/wxGUI/Routing/DebugRoute.h"
#include "src/wxGUI/Routing/BoxChannelShape.h"
#include "src/wxGUI/Routing/BoxDlg.h"
#include "src/wxGUI/Routing/InputDevDlg.h"
#include "src/wxGUI/Routing/OutputDevDlg.h"
#include "src/wxGUI/Routing/GUIRoute-inlines.h"
#include <algorithm>
#include "wx/defs.h"
#include "wx/bmpbuttn.h"
#include "wx/msgdlg.h"
//#include "MutApp.h"
//#include "MutIcon.h"
//#include "MutRouteWnd.h"
//#include "InputDevDlg.h"
//#include "Device.h"
// common part of the macros below
#define wxIMPLEMENT_CLASS_COMMON_TEMPLATE1(name, basename, baseclsinfo2, func, T1) \
template<> \
wxClassInfo name<T1>::ms_classInfo(wxT(#name "<" #T1 ">"), \
&basename::ms_classInfo, \
baseclsinfo2, \
(int) sizeof(name<T1>), \
(wxObjectConstructorFn) func); \
template<> \
wxClassInfo *name<T1>::GetClassInfo() const \
{ return &name<T1>::ms_classInfo; }
#define wxIMPLEMENT_CLASS_COMMON1_TEMPLATE1(name, basename, func, T1) \
wxIMPLEMENT_CLASS_COMMON_TEMPLATE1(name, basename, NULL, func, T1)
// Single inheritance with one base class
#define IMPLEMENT_ABSTRACT_CLASS_TEMPLATE1(name, basename, T1) \
wxIMPLEMENT_CLASS_COMMON1_TEMPLATE1(name, basename, NULL, T1)
// Single inheritance with one base class
#define IMPLEMENT_DYNAMIC_CLASS_TEMPLATE1(name, basename, T1) \
template<> \
wxObject* name<T1>::wxCreateObject() \
{ return new name<T1>; } \
wxIMPLEMENT_CLASS_COMMON1_TEMPLATE1(name, basename, \
name<T1>::wxCreateObject, T1)
using namespace mutaborGUI;
using namespace mutabor;
BEGIN_EVENT_TABLE_TEMPLATE1(MutDeviceShape, MutIconShape, T)
EVT_KEY_DOWN(MutDeviceShape::OnKeyDown)
EVT_LEFT_DCLICK(MutDeviceShape::LeftDblClickEvent)
EVT_MENU(CM_MOVE_UP, MutDeviceShape::CmMoveIcon)
EVT_MENU(CM_MOVE_DOWN, MutDeviceShape::CmMoveIcon)
EVT_MENU(CM_DEVICE_STATE_CHANGED, MutDeviceShape::CmDeviceNotification)
EVT_BUTTON(CM_PLAYDEVICE, MutDeviceShape::PlayButtonPressed)
EVT_BUTTON(CM_PAUSEDEVICE, MutDeviceShape::PlayButtonPressed)
EVT_BUTTON(CM_STOPDEVICE, MutDeviceShape::PlayButtonPressed)
END_EVENT_TABLE()
MUTABOR_NAMESPACE(mutaborGUI)
template<class T>
MutDeviceShape<T>::~MutDeviceShape() {
TRACEC;
if (device) {
try {
disconnect(device,this);
TRACEC;
} catch (const mutabor::error::unreachable_exception & e) {
mutabor::unhandled_exception_handler();
}
}
if (playbuttons) delete playbuttons;
TRACEC;
}
template<class T>
bool MutDeviceShape<T>::Create (wxWindow * parent,
wxWindowID id,
devicetype & d)
{
if (!d) return false;
DEBUGLOG (other, ("Checking icon"));
mutASSERT(MidiInputDevBitmap.IsOk());
mutASSERT(MidiOutputDevBitmap.IsOk());
TRACEC;
bool fine =
Create (parent, id, d->GetName());
TRACEC;
if (fine)
connect(d,this);
TRACEC;
return fine;
}
template<class T>
void MutDeviceShape<T>::Add(MutBoxChannelShape * route)
{
#ifdef DEBUG
MutBoxChannelShapeList::iterator pos =
std::find(routes.begin(),routes.end(),route);
mutASSERT(pos == routes.end());
#endif
routes.push_back(route);
// ClearPerimeterPoints();
Refresh();
Update();
}
template<class T>
bool MutDeviceShape<T>::Replace(MutBoxChannelShape * oldroute,
MutBoxChannelShape * newroute)
{
#ifdef DEBUG
MutBoxChannelShapeList::iterator pos =
std::find(routes.begin(),routes.end(),oldroute);
mutASSERT(pos != routes.end());
#endif
bool retval = Remove(oldroute);
Add(newroute);
Recompute();
return retval;
}
template<class T>
bool MutDeviceShape<T>::Remove(MutBoxChannelShape * route)
{
MutBoxChannelShapeList::iterator pos =
std::find(routes.begin(),routes.end(),route);
if (pos == routes.end()) {
UNREACHABLEC;
return false;
} else {
routes.erase(pos);
}
Recompute();
return true;
}
template<class T>
bool MutDeviceShape<T>::MoveRoutes (MutDeviceShape * newclass)
{
routes.swap(newclass->routes);
Recompute();
return true;
}
template<class T>
bool MutDeviceShape<T>::Recompute()
{
// ClearPerimeterPoints();
SetIcon(GetMutIcon());
// SetLabel (filename.GetFullName());
return GetIcon().IsOk();
}
template<class T>
void MutDeviceShape<T>::ReadPanel(FilterPanel * panel,
MutBoxChannelShape * channel)
{
mutASSERT(panel);
mutASSERT(channel);
if (!panel || !channel) return;
bool active = panel->IsShown();
thistype * newShape = panel->GetCurrentSelection();
Route & route = channel->GetRoute();
if (!active) {
TRACEC;
disconnect(channel,this);
TRACEC;
return;
} else if (newShape != this) {
TRACEC;
reconnect(channel,this,newShape);
TRACEC;
}
if (newShape) {
wxWindow * subpanel = panel->GetCurrentDevicePage();
if (!panel) {
UNREACHABLEC;
return;
}
TRACEC;
newShape->ReadFilterPanel(subpanel,route);
}
TRACEC;
}
template<class T>
void MutDeviceShape<T>::OnKeyDown (wxKeyEvent & event) {
if (event.HasModifiers()) {
event.Skip();
return;
}
/* Other inspirations:
case WXK_DELETE:
// cursor keys
*/
switch (event.GetKeyCode()) {
case WXK_NUMPAD_ENTER:
case WXK_RETURN:
case WXK_SPACE:
case WXK_NUMPAD_SPACE:
case WXK_NUMPAD_ADD:
case WXK_ADD:
case WXK_WINDOWS_MENU:
case WXK_MENU:
{
wxCommandEvent command(wxEVT_COMMAND_MENU_SELECTED,
CM_LEFT_DOUBLE_CLICK);
wxPostEvent(this,command);
return;
}
default:
event.Skip();
}
}
/**
* Move the corresponding device in the device list and
* update the GUI according to the new order.
*
* \param event wxCommandEvent containing the request
*/
template <class T>
void MutDeviceShape<T>::CmMoveIcon (wxCommandEvent & event) {
switch (event.GetId()) {
case CM_MOVE_UP:
MoveDevice(-1);
break;
case CM_MOVE_DOWN:
MoveDevice(+1);
break;
}
}
template <class T>
void MutDeviceShape<T>::DoDeviceNotification(wxCommandEvent & mutUNUSED(event))
{
if (!device || !playbuttons) return;
MutaborModeType mode = device->GetMode();
bool open = device->IsOpen();
bool hidePlay = !open;
bool hidePause = hidePlay,
hideStop = hidePlay;
if (open) {
switch (mode) {
case DevicePlay:
hidePlay = true;
break;
case DeviceStop:
hideStop = true;
break;
case DevicePause:
hidePause = true;
break;
case DeviceKilled:
case DeviceUnregistered:
case DeviceInitializing:
case DeviceCompileError:
case DeviceTimingError:
return;
}
}
bool dolayout = false;
wxSizerItemList & playlist = playbuttons->GetChildren();
for (wxSizerItemList::iterator i = playlist.begin();
i != playlist.end(); i++) {
wxWindow * button = (*i)->GetWindow();
bool hide = !open;
switch (button -> GetId()) {
case CM_PLAYDEVICE:
hide = hidePlay;
break;
case CM_STOPDEVICE:
hide = hideStop;
break;
case CM_PAUSEDEVICE:
hide = hidePause;
break;
}
if (hide) {
if (playbuttons->IsShown(button)) {
playbuttons->Hide(button);
dolayout = true;
}
} else {
if (!playbuttons->IsShown(button)) {
playbuttons->Show(button);
dolayout = true;
}
}
}
if (dolayout) {
playbuttons->Layout();
wxSize size = playbuttons->GetMinSize();
playbuttons->SetDimension(0,0,size.GetWidth(),size.GetHeight());
Update();
}
}
template <class T>
void MutDeviceShape<T>::createPlayButtons()
{
mutASSERT(!playbuttons);
playbuttons = new wxBoxSizer(wxVERTICAL);
if (!playbuttons) return;
wxBitmapButton * button =
new wxBitmapButton(this,CM_PLAYDEVICE,DevicePlayBitmap);
playbuttons->Add(button);
button =
new wxBitmapButton(this,CM_PAUSEDEVICE,DevicePauseBitmap);
playbuttons->Add(button);
button =
new wxBitmapButton(this,CM_STOPDEVICE,DeviceStopBitmap);
playbuttons->Add(button);
playbuttons->Layout();
wxSize size = playbuttons->GetMinSize();
playbuttons->SetDimension(0,0,size.GetWidth(),size.GetHeight());
}
template <class T>
void MutDeviceShape<T>::createPauseButton()
{
mutASSERT(!playbuttons);
playbuttons = new wxBoxSizer(wxVERTICAL);
if (!playbuttons) return;
wxBitmapButton * button =
new wxBitmapButton(this,CM_PAUSEDEVICE,DevicePauseBitmap);
playbuttons->Add(button);
playbuttons->Layout();
wxSize size = playbuttons->GetMinSize();
playbuttons->SetDimension(0,0,size.GetWidth(),size.GetHeight());
}
template <class T>
void MutDeviceShape<T>::createRecordButtons()
{
mutASSERT(!playbuttons);
playbuttons = new wxBoxSizer(wxVERTICAL);
if (!playbuttons) return;
wxBitmapButton * button =
new wxBitmapButton(this,CM_PLAYDEVICE,DeviceRecordBitmap);
playbuttons->Add(button);
button =
new wxBitmapButton(this,CM_PAUSEDEVICE,DevicePauseBitmap);
playbuttons->Add(button);
button =
new wxBitmapButton(this,CM_STOPDEVICE,DeviceStopBitmap);
playbuttons->Add(button);
playbuttons->Layout();
wxSize size = playbuttons->GetMinSize();
playbuttons->SetDimension(0,0,size.GetWidth(),size.GetHeight());
}
template <class T>
void MutDeviceShape<T>::PlayButtonPressed(wxCommandEvent & event)
{
if (!device) return;
if (!device->IsOpen()) return;
switch (event.GetId()) {
case CM_PLAYDEVICE:
device -> Play();
break;
case CM_PAUSEDEVICE:
device -> Pause();
break;
case CM_STOPDEVICE:
device -> Stop();
break;
}
}
template <class T>
void MutDeviceShape<T>::DoLeftDblClick() {
TRACEC;
DeviceDialog * dlg = ShowDeviceDialog();
int Res = dlg->ShowModal();
TRACEC;
bool destroySelf = false;
wxWindow * parent = m_parent; // to be availlable after deleten.
TRACEC;
if (Res == wxID_OK) {
DevType type = dlg->GetType();
if (CanHandleType (type)) {
TRACEC;
readDialog (dlg);
} else if (type != DTNotSet) { // assure type is set.
TRACEC;
devicetype dev =
DeviceFactory::Create<devicetype>(type);
if (dev) {
TRACEC;
thistype * newdev =
GUIDeviceFactory::CreateShape (dev,
GetParent());
if (! newdev) {
dlg->Destroy();
UNREACHABLEC;
return;
}
mutASSERT(newdev->device);
TRACEC;
newdev -> readDialog (dlg);
if (LogicOn && !(newdev->device->IsOpen()))
newdev->device->Open();
TRACEC;
destroySelf = replaceSelfBy (newdev);
}
}
} else if (Res == ::wxID_REMOVE) {
TRACEC;
device -> Destroy();
}
// Now, we may be deleted.
dlg->Destroy();
DebugCheckRoutes();
TRACEC;
if (Res != ::wxID_REMOVE && !destroySelf) {
Layout();
InvalidateBestSize();
Fit();
Refresh();
}
if (parent) {
parent->InvalidateBestSize();
parent->Layout();
parent->FitInside();
parent->Refresh();
parent->Update();
} else if (Res != ::wxID_REMOVE && !destroySelf) Update();
/* we don't need to destroy this control.
This should have been done during device destruction
*/
TRACE;
}
template<class T>
typename MutDeviceShape<T>::DeviceDialog * MutDeviceShape<T>::ShowDeviceDialog() {
ABSTRACT_FUNCTIONC;
abort();
}
template <class T>
bool MutDeviceShape<T>::DetachDevice ()
{
wxWindow * parent = m_parent;
wxSizer * sizer = GetContainingSizer();
Hide();
if (sizer) {
sizer -> Detach(this);
}
if (parent) {
parent->Layout();
parent->FitInside();
parent->SetVirtualSize(wxDefaultSize);
parent->Refresh();
parent->Update();
}
TRACEC;
device->Destroy();
TRACEC;
return true;
}
template<class T>
bool MutDeviceShape<T>::replaceSelfBy (thistype * newshape)
{
/** \todo transfer this function to GUIRoute */
mutASSERT (newshape);
mutASSERT (newshape->device);
TRACEC;
if (device) // might be zero as in MutNewInputDeviceShape
device->MoveRoutes(newshape->GetDevice());
TRACEC;
newshape->MoveBeforeInTabOrder (this);
wxSizer * sizer = GetContainingSizer();
sizer -> Replace (this, newshape, false);
newshape->SetFocus();
Hide();
wxWindow * parent = m_parent;
parent->RemoveChild(this);
parent->Layout();
parent->FitInside();
parent->SetVirtualSize(wxDefaultSize);
TRACEC;
device->Destroy();
// at this moment this points to invalid memory
TRACET(MutInputDeviceShape);
return true;
}
// instantiate MutInputDeviceShape
template<>
InputDevDlg * MutInputDeviceShape::ShowDeviceDialog() {
InputDevDlg * in = new InputDevDlg (m_parent);
#ifdef RTMIDI
if (rtmidiin) {
try {
rtmidi::PortList ports = rtmidiin->getPortList();
if (ports.empty()) {
in->AppendPortChoiceNoDevice();
}
else for (rtmidi::PortList::iterator i = ports.begin();
i != ports.end();
++i) {
in->AppendPortChoice(*i);
}
} catch (const rtmidi::Error &error) {
error.printMessage();
in->AppendPortChoiceNoDevice();
}
}
#else
STUBC;
#endif
// in->SetType(DTUnknown);
in->SelectMidiDevice(0);
in->SetMidiFile(wxEmptyString);
in->SetGUIDOFile(wxEmptyString);
InitializeDialog(in);
in->Fit();
return in;
}
template<>
OutputDevDlg * MutOutputDeviceShape::ShowDeviceDialog()
{
OutputDevDlg * out = new OutputDevDlg (m_parent);
#ifdef RTMIDI
if (rtmidiout) {
try {
rtmidi::PortList ports = rtmidiout->getPortList();
if (ports.empty()) {
out->AppendPortChoiceNoDevice();
}
else for (rtmidi::PortList::iterator i = ports.begin();
i != ports.end();
++i) {
out->AppendPortChoice(*i);
}
} catch (const rtmidi::Error &error) {
wxMessageBox(error.getMessage());
error.printMessage();
out->AppendPortChoiceNoDevice();
}
}
#else
/* nMidi = midiInGetNumDevs();
if ( nMidi )
{
for (int i = 0; i < nMidi; i++)
{
MIDIINCAPS miin;
midiInGetDevCaps(i, &miin, sizeof(MIDIINCAPS));
DataR0.Device.AddString(miin.szPname);
}
}
else
DataR0.Device.AddString("no device");*/
#endif
// in->SetType(DTUnknown);
out->SelectMidiDevice(0);
out->SetMidiFile(wxEmptyString);
out->SetGUIDOFile(wxEmptyString);
out->SetMidiBendingRange(2);
out->SetMidiFileBendingRange(2);
InitializeDialog(out);
out->Fit();
return out;
}
IMPLEMENT_ABSTRACT_CLASS_TEMPLATE1(MutDeviceShape, MutIconShape, inputdevicetypes)
IMPLEMENT_ABSTRACT_CLASS_TEMPLATE1(MutDeviceShape, MutIconShape, outputdevicetypes)
template class MutDeviceShape<inputdevicetypes>;
template class MutDeviceShape<outputdevicetypes>;
MUTABOR_NAMESPACE_END(mutaborGUI)
template class std::list<mutaborGUI::MutInputDeviceShape *>;
template class std::list<mutaborGUI::MutOutputDeviceShape *>;
/*
* \}
*/
| keinstein/mutabor | src/wxGUI/Routing/DeviceShape.cpp | C++ | gpl-2.0 | 15,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.